package com.steering.jobface.mch;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimerTask;
import java.util.Date;
import java.util.regex.Matcher;
import java.text.SimpleDateFormat;

import com.steering.comm.converter.CoreConverter;
import com.steering.jobface.sale.CoreOrderLineSpotLineTask;
import org.apache.log4j.Logger;

import CoreFS.SA08.CoreXmlSqlParsersFactory;

import com.steering.comm.db.DBCommon;
import com.steering.comm.file.CoreFTPClient;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.StringTool;
import com.steering.model.mch.RtdMeasurePosdataEntity;
import org.hsqldb.lib.StringUtil;

/**
 *
 * @ClassName:       CoreRtdMeasurePosDataTask
 * @Description:    定时任务
 * @author:            朱少波
 * @date:            2017年6月8日        上午10:00:32
 */
public class CoreRtdMeasurePosDataTask{
    private  String originalDaoName;
    private String targetDaoName;
    private String idHeader;
    public Logger logger = Logger.getLogger(CoreRtdMeasurePosDataTask.class);
    private Boolean searchAll = false;

    /**
     *
     * @Title:            CoreRtdMeasurePosDataTask
     * @Description:    构造函数
     * @param:            @param OriginalDaoName   原始数据库Dao
     * @param:            @param TargetDaoName   目标数据库Dao
     * @param:            @param IDHeader   数据库ID的head 多个数据库导入一个数据库 用head去区分开
     * @throws
     */
    public CoreRtdMeasurePosDataTask(String OriginalDaoName,String TargetDaoName,String IDHeader, Boolean SearchAll)
    {
        originalDaoName = OriginalDaoName;
        targetDaoName = TargetDaoName;
        idHeader = IDHeader;
        searchAll = SearchAll;
    }

    /**
     *
     * @Title:            CoreRtdMeasurePosDataTask
     * @Description:    构造函数
     * @param:            @param OriginalDaoName   原始数据库Dao
     * @param:            @param TargetDaoName   目标数据库Dao
     * @param:            @param IDHeader   数据库ID的head 多个数据库导入一个数据库 用head去区分开
     * @throws
     */
    public CoreRtdMeasurePosDataTask(String OriginalDaoName,String TargetDaoName,String IDHeader)
    {
        originalDaoName = OriginalDaoName;
        targetDaoName = TargetDaoName;
        idHeader = IDHeader;
        searchAll = false;
    }



    public void Main() {
        long a=System.currentTimeMillis();
        DBCommon db = new DBCommon();
        Connection con = null;
        Connection conTg = null;
        String sql ="";
        try {
            con = db.getDao(originalDaoName).getConnection();
            conTg  = db.getDao(targetDaoName).getConnection();


            List<RtdMeasurePosdataEntity> listData = null;

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreOrderLineSpotLineTask.QueryMaxID");

            Long ID = 0l;
            PreparedStatement ps = conTg.prepareStatement(sql);
            ps.setObject(1, idHeader);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                ID  = rs.getLong("ID");

            }
            rs.close();
            ps.close();

            if (ID==0) {
                return;
            }

            if (searchAll) {

                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderLineSpotLineTask.FindID");

                ArrayList<String> IDS = new ArrayList<String>();
                ps = conTg.prepareStatement(sql);
                ps.setObject(1,idHeader);
                ps.setObject(2,idHeader);
                rs = ps.executeQuery();
                while (rs.next()) {
                    IDS.add(rs.getString("KEY_ID"));
                }
                rs.close();
                ps.close();


                if(IDS!=null && IDS.size()>0) {

                    String[] StoveNos = new String[IDS.size()];


                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderLineSpotLineTask.GetOriginalMeasurePosDataAll");

                    sql += CoreConverter.toSqlConditionString("T.ID", IDS.toArray(StoveNos));

                    ArrayList<Object> paramete = new ArrayList<Object>();
                    paramete.add(idHeader);

                    logger.info(idHeader + ( searchAll ? "1" : "0" ) + "  ID:" + ID + "  sql:" + sql);

                    listData = EntityTool.getEntitysBySqlParameter(
                            sql, con, paramete, RtdMeasurePosdataEntity.class);
                }
            }
            else{



                sql =   CoreXmlSqlParsersFactory
                        .getSql("CoreOrderLineSpotLineTask.GetOriginalMeasurePosDataByID");

                ArrayList<Object> paramete = new ArrayList<Object>();
                paramete.add(idHeader);
                paramete.add(ID);

                logger.info(idHeader + (searchAll?"1":"0") +"  ID:" +ID+ "  sql:" +sql );

                listData = EntityTool.getEntitysBySqlParameter(
                        sql, con, paramete, RtdMeasurePosdataEntity.class);
            }

            if (listData!=null && listData.size()>0) {
                logger.info(idHeader + (searchAll?"1":"0") + " 查询到数据" + listData==null?0:listData.size()  +"条   ID:" +ID+ "  sql:" +sql );

                conTg.setAutoCommit(true);

                String Lastline = "";
                String LastGroup = "";
                String LastDate = "";
                String Shift = "";


                for (RtdMeasurePosdataEntity data : listData) {

                    try {
                        // 数据按线，时间做排序  当线变化 或者 班组变化   或者2笔数据时间差比较多   认为是换班   重新根据第一笔数据时间算班次
                      /*  if (!data.getPlineCode().equals(Lastline) || !data.getProBz().equals(LastGroup) || HoursBetween(LastDate, data.getMsauerDate()) > 6) {
                            Shift = (idHeader.endsWith("B"))?GetShiftB(data.getMsauerDate()): GetShift(data.getMsauerDate());
                            Lastline = data.getPlineCode();
                            LastGroup = data.getProBz();
                        }*/

                      if(StringUtil.isEmpty(data.getMatNo()) || data.getMatNo().equals("-1")){
                          data.setJudgeStoveNo( data.getJudgeStoveNo() + "?" ); // 出现-1的管号, 依然插入, 改变炉号防止界面出现
                      }


                        Shift = (idHeader.endsWith("B"))?GetShiftB(data.getMsauerDate()): GetShift(data.getMsauerDate());
                   /*     Lastline = data.getPlineCode();
                        LastGroup = data.getProBz();
                        LastDate = data.getMsauerDate();*/
                        data.setProBc(Shift);
                        //通过ID在存储的表中取出数据
                        sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
                                .getSql("CoreOrderLineSpotLineTask.FindByID"), data);
                        RtdMeasurePosdataEntity savedData = EntityTool.getEntityBySqlNoClsCon(
                                sql, conTg, RtdMeasurePosdataEntity.class);

                        //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        //若不存在 则插入原始数据
                        if (savedData == null || StringTool.isNullOrEmpty(savedData.getKeyId())) {
                            sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
                                    .getSql("CoreOrderLineSpotLineTask.SaveOriginalMeasurePosData"), data);

                            ps = conTg.prepareStatement(sql);
                            rs = ps.executeQuery();

                            rs.close();
                            ps.close();

                            Long NewID = 0L;

                            if (StringTool.isInteger(data.getKeyId().replace(idHeader, ""))) {
                                NewID = Long.parseLong(data.getKeyId().replace(idHeader, ""));
                            }

                            if (NewID < ID) {
                                NewID = ID;
                            }

                            sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
                                    .getSql("CoreOrderLineSpotLineTask.UpdateMaxID"), data);

                            ps = conTg.prepareStatement(sql);
                            ps.setObject(1, NewID);
                            ps.setObject(2, idHeader);
                            rs = ps.executeQuery();

                            rs.close();
                            ps.close();


                            // System.out.println(df.format(new Date())+"  " + sql );// new Date()为获取当前系统时间

                        }
                        //若有存储原始数据，但原始数据的状态更新为删除数据  则更新状态
                        else if (savedData.getFlag().equals("00") && !data.getFlag().equals("00")) {
                            sql = EntityTool.fillSqlByEntity(CoreXmlSqlParsersFactory
                                    .getSql("CoreOrderLineSpotLineTask.MarkMeasurePosData"), data);

                            ps = conTg.prepareStatement(sql);
                            rs = ps.executeQuery();
                            rs.close();
                            ps.close();

                            // System.out.println(df.format(new Date())+"  " + sql );// new Date()为获取当前系统时间
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(sql);
                        logger.error(e);
                    }

                }


                logger.info(idHeader + ( searchAll ? "1" : "0" ) + "  插入成功");
            }
        }
        catch (Exception e) {

            e.printStackTrace();
            logger.error(sql);
            logger.error(e);
            logger.error(e.getStackTrace());
            try {
                if (con != null && !con.isClosed()) {
                    con.rollback();
                }
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }

            try {
                if (conTg != null && !conTg.isClosed()) {
                    con.rollback();
                }
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                logger.error(e);
                e.printStackTrace();
            }

            try {
                if (conTg != null && !conTg.isClosed()) {
                    conTg.close();
                }
            }
            catch (SQLException e) {
                logger.error(e);
                e.printStackTrace();
            }

        }
    }


    public  int HoursBetween(String startTime, String endTime) {
        if (startTime.equals("")|| endTime.equals(""))
        {
            return 1000;

        }


        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");
        Calendar cal = Calendar.getInstance();
        long time1 = 0;
        long time2 = 0;

        try{
            cal.setTime(sdf.parse(startTime));
            time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(endTime));
            time2 = cal.getTimeInMillis();
        }catch(Exception e){
            e.printStackTrace();
        }
        long between_Hours=(time2-time1)/(1000*3600);

        return Integer.parseInt(String.valueOf(between_Hours));
    }


    public  String GetShift(String date) throws Exception
    {
        //算第一笔数据的时间   
        if (DateCompare(date,"07:00","14:00"))
            return "1";
        else if (DateCompare(date,"14:00","19:00"))
            return "2";
        else
            return "3";
    }

    public  String GetShiftB(String date) throws Exception
    {
        //算第一笔数据的时间
        if (DateCompare(date,"08:00","20:00"))
            return "0";
        else
            return "3";
    }

    ;
    public boolean DateCompare(String source, String Start, String End) throws Exception {
        if (source.length() <11 ) source = "2000-01-01 " +source;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date sourceDate = format.parse(source);
        Date StartDate = format.parse(Start.length()<11? (source.substring(0,11) + Start):Start);
        Date EndDate = format.parse(End.length()<11? (source.substring(0,11) + End):End);

        return sourceDate.after(StartDate) && sourceDate.before(EndDate);
    }
}
