package com.steerinfo.ems.Utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.steerinfo.ems.usagedata.model.UsageData;

public class UsageDataUtils {
	private static final Logger logger = LoggerFactory.getLogger(UsageDataUtils.class);
	
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://172.16.10.252:3306/gov_data_upload?useSSL=false&connectTimeout=3000&socketTimeout=3000";
    // 数据库的用户名与密码
    static final String USER = "root";
    static final String PASS = "!QAZ2wsx";
    
	/**
	 * 数据同步_晋泰信和
	 * 
	 * @param usageData
	 * @return 插入数据条数（1：表示成功，其他失败）
	 */
    public static int Insert(UsageData usageData) {
		if (usageData == null || usageData.getId() == null || usageData.getDataCode() == null
				|| usageData.getDt() == null || usageData.getUsage() == null || usageData.getCt() == null) {
			return -2;
		}
    	Connection conn = null;
        Statement stmt = null;
        String sql = "";
        try{
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            stmt = conn.createStatement();
            String id = usageData.getId();
            String dataCode = usageData.getDataCode();
            String dt = usageData.getDt();
            String sumval = usageData.getSumval().toPlainString();
            String ct = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(usageData.getCt());
            sql = "update usage_data set dt='"+dt+"', `usage`="+sumval+",ct='"+ct+"' where energy_code='"+dataCode+"';";
        	int r = stmt.executeUpdate(sql);
        	if(r<1){
        		sql = "INSERT INTO usage_data VALUES ("+id+", '"+dataCode+"', '"+dt+"', "+sumval+", '"+ct+"', 0);";
        		return stmt.executeUpdate(sql);
        	}
        	return r;
        }catch(Exception e){
            // e.printStackTrace();
        	logger.error("sql:" + sql);
            logger.error("数据同步_晋泰信和失败", e);
            return -1;
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            	logger.error("数据同步_晋泰信和失败2", se2);
            }
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
            	logger.error("数据同步_晋泰信和失败3", se);
            }
        }
    }
    
    public static void main(String[] args) {
    	int asd = Insert(null);
		System.out.println(asd);
	}
}
