package com.steering.jobface.qcm.task;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TimerTask;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.model.qcm.*;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import org.apache.log4j.Logger;

public class JhyCpPhyToQcmPhyTask extends TimerTask{
	private static class JhyCpPhyToQcmPhyTaskClass{
		private static final JhyCpPhyToQcmPhyTask instance = new JhyCpPhyToQcmPhyTask();
	}
	
	private JhyCpPhyToQcmPhyTask(){}
	
	public static JhyCpPhyToQcmPhyTask getInstance(){
		return JhyCpPhyToQcmPhyTaskClass.instance;
	}
    private final Logger logger = Logger.getLogger(MainTask.class);

	public void run(){
		synchronized (this) {
			Connection qcmCon = null;
			Connection jhyCon = null;
			Statement jhyStmt = null;
			Statement qcmStmt = null;
			try {
				qcmCon = new DBCommon().getDao(CoreConstantData.sysbeanstr).getConnection();
				jhyCon = new DBCommon().getDao("JhyDao").getConnection();
				jhyCon.setAutoCommit(false);
				qcmCon.setAutoCommit(false);
				ArrayList<PipeCheckconsignDetailEntity> pipeDetails = getPipeCheckConsignDetail(jhyCon);
				jhyStmt = jhyCon.createStatement();
				qcmStmt = qcmCon.createStatement();
				SqlBuilder b = null;
				for (PipeCheckconsignDetailEntity pipeDetail : pipeDetails) {
					try {
						
						//如果是复样或者逐支则需要再获取初样的数据。
						ArrayList<PipeCheckconsignPhydetailEntity> pipePhyDetails = getFullSample(
								pipeDetail.getCheckNo(), pipeDetail.getPhyCodeMax(), jhyCon);
						
						//按试样号分组
						HashMap<String, ArrayList<PipeCheckconsignPhydetailEntity>> mapPhys = new HashMap<String, ArrayList<PipeCheckconsignPhydetailEntity>>();
						for(PipeCheckconsignPhydetailEntity pipePhyDetail : pipePhyDetails){
							if(!mapPhys.containsKey(pipePhyDetail.getPhyCodeMax())){
								mapPhys.put(pipePhyDetail.getPhyCodeMax(), new ArrayList<PipeCheckconsignPhydetailEntity>());
							}
							mapPhys.get(pipePhyDetail.getPhyCodeMax()).add(pipePhyDetail);
						}

						String newCheckNo = "";//共样新检验编号
						for(String key : mapPhys.keySet()){
							ArrayList<QcmJhyPhyresultEntity> qcmJhyPhys = new ArrayList<QcmJhyPhyresultEntity>();
							CopyData(pipeDetail, mapPhys.get(key), qcmJhyPhys);

							insertJhyPhy(pipeDetail.getCheckNo(), qcmJhyPhys, key, b, qcmStmt);
							
							//复制共样数据
                            newCheckNo = copyFdCheckConsign(pipeDetail, qcmJhyPhys, key, b, qcmCon, qcmStmt);
						}
						
						//把检化验同步标志置为5
						b = new SqlBuilder("JhyCpPhyToQcmPhyTask.getUpdateFlag");
						b.Fill(new String[]{ pipeDetail.getCheckNo(), pipeDetail.getPhyCodeMax(), "5" });
						//jhyStmt.addBatch(b.toString());
						jhyStmt.executeUpdate(b.toString());
						//同步实验室记录表
						insertLabResult(pipeDetail.getCheckNo(),b,jhyCon,qcmStmt);
						//更新委托一层表
						b = new SqlBuilder("JhyCpChemToQcmChemTask.updateBaseInfoFlag");
						b.Fill(new String[]{ pipeDetail.getCheckNo() });
						//jhyStmt.addBatch(b.toString());
						jhyStmt.executeUpdate(b.toString());
						//新增委托主表
						JhyCpChemToQcmChemTask.saveQcmJhyCheckconsign(pipeDetail, qcmCon, qcmStmt);
						//更新委托表的报出情况
						JhyCpChemToQcmChemTask.setConsignQuoteState(pipeDetail.getCheckNo(), qcmCon, qcmStmt);
						if(!newCheckNo.equals("")){
                            JhyCpChemToQcmChemTask.setConsignQuoteState(newCheckNo, qcmCon, qcmStmt);
                        }

						jhyCon.commit();
						qcmCon.commit();
					}catch(Exception ex) {
						jhyCon.rollback();
						qcmCon.rollback();
						//把检化验同步标志置为-1
						b = new SqlBuilder("JhyCpPhyToQcmPhyTask.getUpdateFlag");
						b.Fill(new String[]{ pipeDetail.getCheckNo(), pipeDetail.getPhyCodeMax(), "3" });
						jhyStmt.executeUpdate(b.toString());
						jhyCon.commit();
						qcmCon.commit();
						String msg = "JhyCpPhyToQcmPhyTask异常: CheckNo=" + pipeDetail.getCheckNo() + "PhyCodeMins="
                                + pipeDetail.getPhyCodeMax() + ex.getMessage();
                        logger.error(msg);
					}
				}
			} catch (Exception ex) {
				try {
					jhyCon.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				try {
					qcmCon.rollback();
				} catch (SQLException e) {
					e.printStackTrace();
				}
                logger.error("JhyCpPhyToQcmPhyTask异常: " + ex.getMessage());
				ex.printStackTrace();
			}finally{
				if(jhyStmt != null){
					try {
						jhyStmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if(qcmStmt != null){
					try {
						qcmStmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if(jhyCon != null){
					try {
						jhyCon.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				if(qcmCon != null){
					try {
						qcmCon.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private ArrayList<PipeCheckconsignDetailEntity> getPipeCheckConsignDetail(Connection con) {
		String sql = CoreXmlSqlParsersFactory.getSql("JhyCpPhyToQcmPhyTask.getPipeCheckConsignDetail");
		ArrayList<PipeCheckconsignDetailEntity> list = EntityTool.getEntitysBySqlNoClsCon(sql, con,
				PipeCheckconsignDetailEntity.class);
		return list;
	}

	private void CopyData(PipeCheckconsignDetailEntity pipeDetail,
			ArrayList<PipeCheckconsignPhydetailEntity> pipePhyDetails,
			ArrayList<QcmJhyPhyresultEntity> qcmJhyPhys) {
		Class<QcmJhyPhyresultEntity> qcmJhyPhyClass = QcmJhyPhyresultEntity.class;
		Class<PipeCheckconsignPhydetailEntity> pipePhyDetailClass = PipeCheckconsignPhydetailEntity.class;
		for (PipeCheckconsignPhydetailEntity pipePhyDetail : pipePhyDetails) {
				QcmJhyPhyresultEntity qcmJhyPhy = new QcmJhyPhyresultEntity();
				for(Method methodPhyDetail : pipePhyDetailClass.getMethods()){
					try {
					if(methodPhyDetail.getName().startsWith("set")) continue;
					String name = methodPhyDetail.getName().replaceFirst("get", "");
					Method method = qcmJhyPhyClass.getMethod("set" + name, String.class);
					method.invoke(qcmJhyPhy, methodPhyDetail.invoke(pipePhyDetail));
					} catch (Exception ex) {

					}
				}
				qcmJhyPhy.setSampleId(pipePhyDetail.getCheckNo());
				qcmJhyPhy.setPlineCode(pipeDetail.getPlineCode());
				qcmJhyPhy.setJudgeStoveNo(pipeDetail.getJudgeStoveNo());
				qcmJhyPhy.setSampleType(pipeDetail.getSampleType());
				qcmJhyPhy.setConsigner(pipeDetail.getConsigner());
				qcmJhyPhy.setLotNo(pipeDetail.getLotNo());
				qcmJhyPhy.setPhyCodeMax(pipePhyDetail.getPhyCodeMin());
				qcmJhyPhy.setPhyNameMax(pipePhyDetail.getPhyNameMin());
				qcmJhyPhy.setPhyCodeMin(pipePhyDetail.getPhyCodeMax());
				qcmJhyPhy.setPhyNameMin(pipePhyDetail.getPhyNameMax());
				qcmJhyPhy.setAverage(pipePhyDetail.getAverageValue());
				qcmJhyPhy.setCraftSource(pipeDetail.getCraftSource());
				qcmJhyPhy.setIsGood(pipePhyDetail.getIsGood());
				qcmJhyPhy.setIsDefect(pipePhyDetail.getIsDefect());
				qcmJhyPhy.setSampleSize(pipePhyDetail.getSampleType());
				qcmJhyPhy.setLotNoGroup(pipeDetail.getLotNoGroup());
				qcmJhyPhys.add(qcmJhyPhy);
		}
	}
	
	/**
	 * 添加之前的取样
	 */
	private ArrayList<PipeCheckconsignPhydetailEntity> getFullSample(
			String checkNo, String phyCodeMax, Connection jhyCon){
		SqlBuilder b = null;
		b = new SqlBuilder("JhyCpPhyToQcmPhyTask.getSampleByCheckNo");
		b.Fill(new String[]{ checkNo, phyCodeMax });
		ArrayList<PipeCheckconsignPhydetailEntity> pipePhyDetails = EntityTool.getEntitysBySqlNoClsCon(
				b.toString(), jhyCon, PipeCheckconsignPhydetailEntity.class);
		return pipePhyDetails;
	}

	private String copyFdCheckConsign(PipeCheckconsignDetailEntity pipeDetail, ArrayList<QcmJhyPhyresultEntity> qcmJhyPhys,
									String phyCodeMin, SqlBuilder b, Connection qcmCon, Statement qcmSt) throws SQLException {
		String checkNo = pipeDetail.getCheckNo();
		String checkNoNew = "G" + pipeDetail.getCheckNo();
		HashMap<String, QcmJhyPhyresultEntity> maps = new HashMap<String, QcmJhyPhyresultEntity>();
		for(QcmJhyPhyresultEntity jhyPhy : qcmJhyPhys){
			String key = jhyPhy.getSampleId() + jhyPhy.getJudgeStoveNo() + jhyPhy.getBatchNo();
			if(!maps.containsKey(key)){
				maps.put(key, jhyPhy);
			}
		}

		for(String key : maps.keySet()){
			QcmJhyPhyresultEntity jhyPhy = maps.get(key);
			b = new SqlBuilder("JhyCpChemToQcmChemTask.getCheckConsignByCheckNo");
			b.Fill(new String[]{ checkNo, jhyPhy.getJudgeStoveNo(), jhyPhy.getBatchNo() });
			QcmZcCheckconsignEntity checkConsign = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), qcmCon, QcmZcCheckconsignEntity.class);

			b = new SqlBuilder("JhyCpPhyToQcmPhyTask.getPhyCommon");
			b.Fill(new String[]{ checkConsign.getOrdLnDlyPk(), checkConsign.getCraftSeq() });
			CraftOrdDesignStdCicEntity craftCic = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), qcmCon, CraftOrdDesignStdCicEntity.class);
			if(craftCic == null || checkConsign.getCraftSource().equals("0")) return "";

			JhyCpChemToQcmChemTask.insertCheckConsign(checkConsign, checkNoNew, b, qcmSt);
			JhyCpChemToQcmChemTask.insertCheckConsignDetail(checkConsign, checkNo, checkNoNew, phyCodeMin, b, qcmCon, qcmSt);
		}

		insertJhyPhy(checkNoNew, qcmJhyPhys, phyCodeMin, b, qcmSt);

		return checkNoNew;
	}

	private void insertJhyPhy (String checkNoNew, ArrayList<QcmJhyPhyresultEntity> qcmJhyPhys,
							   String phyCodeMin, SqlBuilder b, Statement qcmSt) throws SQLException {
		//清除质量成分表
		b = new SqlBuilder("JhyCpPhyToQcmPhyTask.clear");
		b.Fill(new String[]{ checkNoNew, phyCodeMin });
		qcmSt.executeUpdate(b.toString());

		//新增质量理化表
		for(QcmJhyPhyresultEntity qcmJhyPhy : qcmJhyPhys){
			qcmJhyPhy.setSampleId(checkNoNew);
			String sql = CoreXmlSqlParsersFactory.getSql("JhyCpPhyToQcmPhyTask.Insert");
			sql = EntityTool.fillSqlByEntity(sql, qcmJhyPhy);
			qcmSt.executeUpdate(sql);
		}
	}
	
	private void insertLabResult (String checkNo,  SqlBuilder b, Connection jhyCon,Statement qcmSt) throws SQLException {
		//清除质量成分表
		b = new SqlBuilder("JhyCpPhyToQcmPhyTask.clearLabInfo");
		b.Fill(new String[]{ checkNo });
		qcmSt.executeUpdate(b.toString());
		
		b = new SqlBuilder("JhyCpPhyToQcmPhyTask.getLabInfoByCheckNo");
		b.Fill(new String[]{ checkNo });
		ArrayList<PipeLabResultEntity> ListLab = EntityTool.getEntitysBySqlNoClsCon(
				b.toString(), jhyCon, PipeLabResultEntity.class);
		//新增质量理化表
		for(PipeLabResultEntity lab : ListLab){
			if(lab.getTestDate()!=null && lab.getTestDate()!="")
				lab.setTestDate(lab.getTestDate().substring(0,lab.getTestDate().lastIndexOf(".")));
			if(lab.getReportedDate()!=null && lab.getReportedDate()!="")
				lab.setReportedDate(lab.getReportedDate().substring(0,lab.getReportedDate().lastIndexOf(".")));
			String sql = CoreXmlSqlParsersFactory.getSql("JhyCpPhyToQcmPhyTask.InsertLabInfo");
			sql = EntityTool.fillSqlByEntity(sql, lab);
			qcmSt.executeUpdate(sql);
		}
	}
}
