package com.steering.pss.ydm.pipemanage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.StringTool;
import com.steering.pss.ydm.base.FrmEndMaterial;
import com.steering.pss.ydm.entity.MatZcMEntity;
import com.steering.pss.ydm.entity.MatZcMEntity1;
import com.steering.pss.ydm.entity.MatZcMInfoEntity;

public class FrmJudge extends DBCommon{
   
	/***
	 * 成品查询
	 * @param parm
	 * @param arr
	 * @return
	 */
	public CoreReturnObject getMatData(ArrayList<String> parm,String[] arr,String custom)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmJudge.getMatData");
		sql += CoreConverter.toSqlConditionString("T1.BELONG_CODE", arr);
		if(!parm.get(0).equals(""))
		{
			sql += " AND T1.JUDGE_STOVE_NO = '"+parm.get(0)+"'";
		}
		if(!parm.get(1).equals(""))
		{
			sql += " AND T1.INSTOCK_TIME >=TO_DATE('"
			+ parm.get(1)
			+ "', 'YYYY-MM-DD HH24:MI:SS')AND T1.INSTOCK_TIME <=TO_DATE('"
			+ parm.get(2) + "', 'YYYY-MM-DD HH24:MI:SS')"; 
		}
		sql += " AND T1.SUPPLY_UNIT_CODE = '"+custom+"'";
		sql += " GROUP BY T1.BELONG_CODE,T1.BELONG_NAME,T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.PRODUCT_FLAG,T1.MAT_STATUS,T1.SPEC_CODE,T1.SPEC_NAME,"
			+ "T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.PRODUCCODE,T1.PRODUCNAME,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.STEELCODE,T1.STEELNAME,T1.JUDGE_STD_NAME,"
			+ "T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ORD_PK,T1.ORD_LN_PK,T1.ORD_LN_DLY_PK,T1.PRO_ORDER_NO,T1.PRO_ORDER_ID,T1.LOCK_FLAG,"
			+ "T1.MEMO,T1.JUDGE_RESULT_CODE,T1.JUDGE_RESULT,T2.STORAGE_NO,T1.MODEL_CODE,T1.MODEL_DESC,T1.STD_STYLE,T1.STD_STYLE_DESC,T1.SUPPLY_UNIT_CODE,T1.SUPPLY_UNIT "
			+	"ORDER BY T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.ORDER_NO,"
			+ "T1.ORDER_SEQ,T1.ORDER_SEQ_NO,MIN(T1.INSTOCK_TIME)";
		return this.getData(sql);
	}
	
	/***
	 * 查询改判实绩
	 * @param parm
	 * @param arr
	 * @return
	 */
	public CoreReturnObject getGpData(ArrayList<String> parm,String[] arr,String custom)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmJudge.getGpData");
		if(!parm.get(1).equals(""))
		{
			sql += " AND CREATE_TIME >=TO_DATE('"
			+ parm.get(1)
			+ "', 'YYYY-MM-DD HH24:MI:SS')AND CREATE_TIME <=TO_DATE('"
			+ parm.get(2) + "', 'YYYY-MM-DD HH24:MI:SS')"; 
		}
		sql += CoreConverter.toSqlConditionString("BELONG_CODE", arr);
		if(!parm.get(0).equals(""))
		{
			sql += " AND JUDGE_STOVE_NO_OLD = '"+parm.get(0)+"'";
		}
		sql += " AND SUPPLY_UNIT_CODE = '"+custom+"'";
		return this.getData(sql);
	}
	
	/***
	 * 改判物料
	 * @param parm
	 * @return
	 */
	public CoreReturnObject GpData(ArrayList<String> parm)
	{
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        //SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        //String yearMoth = df.format(now);
        String systime = dateFormat.format(now);
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        int actCount = 0;
        double wgt = 0;
        try {
        	connection.setAutoCommit(false); // 取消自动提交事务
        	String updateMatFlagSql = CoreXmlSqlParsersFactory.getSql("GpData.updateMat");//封锁材料表支数
        	PreparedStatement updateMatFlagpsta = connection.prepareStatement(updateMatFlagSql); 
        	String insertJudgeSql = CoreXmlSqlParsersFactory.getSql("GpData.insetJudgeData");
        	PreparedStatement insertJudgepsta = connection.prepareStatement(insertJudgeSql);
        	String judgeId = queryJudgeMaxId(connection);//生成id号
        	int changeCount = Integer.parseInt(parm.get(3));//改判支数
        	ArrayList<String> materialList = new ArrayList<String>();
        	materialList.add(parm.get(4));//品名
        	materialList.add(parm.get(5));
        	materialList.add(parm.get(8));//规格
        	materialList.add(parm.get(9));
        	materialList.add(parm.get(12));//标准类别
        	materialList.add(parm.get(13));
        	materialList.add(parm.get(6));//钢级
        	materialList.add(parm.get(7));
        	materialList.add(parm.get(10));//扣型
        	materialList.add(parm.get(11));
        	String[] materialS = FrmEndMaterial.formEndMaterial(materialList, connection);//生成新的物料码
        	sql = CoreXmlSqlParsersFactory.getSql("GpData.SelectCount");//查询支数是否满足
        	psta = connection.prepareStatement(sql);
        	psta.setString(1, parm.get(0));
        	psta.setString(2, parm.get(1));
        	psta.setString(3, parm.get(2));
//        	psta.setInt(4, changeCount+1);
        	rs = psta.executeQuery();
        	while(rs.next())
        	{
        		actCount = Integer.parseInt(rs.getString("ACOUNT"));
        	}
        	rs.close();
        	psta.close();
        	if(changeCount > actCount)
        	{
        		cro.setV_errMsg("物料数据已发生变化,请刷新页面!");
        		return cro;
        	}
        	sql = CoreXmlSqlParsersFactory.getSql("GpData.SelectMatNo");//查询出需要封锁的材料号
        	psta = connection.prepareStatement(sql);
        	psta.setString(1, parm.get(0));
        	psta.setString(2, parm.get(1));
        	psta.setString(3, parm.get(2));
        	psta.setInt(4, changeCount+1);
        	rs = psta.executeQuery();
        	ArrayList<MatZcMEntity1> MatZcList = EntityTool.getEntitysByRs(rs,
        			MatZcMEntity1.class);
        	rs.close();
        	psta.close();
        	for (MatZcMEntity1 matZcMEntity : MatZcList) {
        		updateMatFlagpsta.setString(1, judgeId);
				updateMatFlagpsta.setString(2, matZcMEntity.getMatNo());
				updateMatFlagpsta.addBatch();
				wgt += Double.parseDouble(String.valueOf(matZcMEntity.getActWeight()));
			}
        	insertJudgepsta.setString(1, judgeId);
        	insertJudgepsta.setString(2, parm.get(0));
        	insertJudgepsta.setString(3, parm.get(1));
        	insertJudgepsta.setString(4, parm.get(2));
        	insertJudgepsta.setString(5, String.valueOf(changeCount));
        	insertJudgepsta.setString(6, String.valueOf(wgt));
        	insertJudgepsta.setString(7, MatZcList.get(0).getMaterialNo());
        	insertJudgepsta.setString(8, MatZcList.get(0).getMaterialName());
        	insertJudgepsta.setString(9, MatZcList.get(0).getProduccode());
        	insertJudgepsta.setString(10, MatZcList.get(0).getProducname());
        	insertJudgepsta.setString(11, MatZcList.get(0).getSteelcode());
        	insertJudgepsta.setString(12, MatZcList.get(0).getSteelname());
        	insertJudgepsta.setString(13, MatZcList.get(0).getSpecCode());
        	insertJudgepsta.setString(14, MatZcList.get(0).getSpecName());
        	insertJudgepsta.setString(15, MatZcList.get(0).getModelCode());
        	insertJudgepsta.setString(16, MatZcList.get(0).getModelDesc());
        	insertJudgepsta.setString(17, MatZcList.get(0).getStdStyle());
        	insertJudgepsta.setString(18, MatZcList.get(0).getStdStyleDesc());
        	insertJudgepsta.setString(19, materialS[0]);
        	insertJudgepsta.setString(20, materialS[1]);
        	insertJudgepsta.setString(21, parm.get(4));
        	insertJudgepsta.setString(22, parm.get(5));
        	insertJudgepsta.setString(23, parm.get(6));
        	insertJudgepsta.setString(24, parm.get(7));
        	insertJudgepsta.setString(25, parm.get(8));
        	insertJudgepsta.setString(26, parm.get(9));
        	insertJudgepsta.setString(27, parm.get(10));
        	insertJudgepsta.setString(28, parm.get(11));
        	insertJudgepsta.setString(29, parm.get(12));
        	insertJudgepsta.setString(30, parm.get(13));
        	insertJudgepsta.setString(31, parm.get(14));
        	insertJudgepsta.setString(32, parm.get(15));
        	insertJudgepsta.setString(33, MatZcList.get(0).getBelongCode());
        	insertJudgepsta.setString(34, MatZcList.get(0).getBelongName());
			insertJudgepsta.setString(35, parm.get(16));
			insertJudgepsta.setString(36, parm.get(17));
        	insertJudgepsta.addBatch();
        	
        	updateMatFlagpsta.executeBatch();
        	insertJudgepsta.executeBatch();
        	connection.commit();
        	cro.setV_errMsg("申请改判成功!");
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                	cro.setV_errMsg(e.getMessage());
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
	}
	
	public String queryJudgeMaxId(Connection con)
	throws Exception
	{
		int seq = 0;
        PreparedStatement psta = null;
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat matter2 = new SimpleDateFormat("yyyyMMdd");
       String sqlLovsqe = CoreXmlSqlParsersFactory
               .getSql("FrmJudge.queryJudgeMaxId");
       psta = con.prepareStatement(sqlLovsqe);
       psta.setString(1, matter1.format(dt));
       ResultSet rs = psta.executeQuery();
       if (rs.next()) {
           String res = rs.getString(1);
           if (res == null) {
               res = matter2.format(dt) + "00001";
           }
           else {
               seq = Integer.parseInt(res.substring(8, 13));
           }
       }
       rs.close();
       psta.close();
       return  matter2.format(dt) + StringTool.formatDecimal(++seq, "00000");
	}
	
	/***
	 * 撤销改判记录
	 * @param judgeId
	 * @param userName
	 * @return
	 */
	public CoreReturnObject cancelGpData(String judgeId,String userName)
	{
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        String staus = "";
        try
        {
        	connection.setAutoCommit(false); // 取消自动提交事务
        	String updateJudgeSql = CoreXmlSqlParsersFactory.getSql("cancelGpData.updateJudge");//作废申请改判记录
        	PreparedStatement updateJudgepsta = connection.prepareStatement(updateJudgeSql);
        	String updateMatLockSql = CoreXmlSqlParsersFactory.getSql("cancelGpData.updateMat");//释放锁定资源
        	PreparedStatement updateMatLockpsta = connection.prepareStatement(updateMatLockSql);
        	sql = CoreXmlSqlParsersFactory.getSql("cancelGpData.SelectStaus");
        	psta = connection.prepareStatement(sql);
        	psta.setString(1, judgeId);
        	rs = psta.executeQuery();
        	while(rs.next())
        	{
        		staus = rs.getString("AGREE_FLAG");
        	}
        	rs.close();
        	psta.close();
        	if(!staus.equals("0"))
        	{
        		cro.setV_errMsg("此申请改判记录已提交审批,不允许撤销!");
        		return cro;
        	}
        	updateJudgepsta.setString(1, userName);
			updateJudgepsta.setString(2, judgeId);
			updateJudgepsta.addBatch();

			updateMatLockpsta.setString(1, judgeId);
			updateMatLockpsta.addBatch();
			
			updateJudgepsta.executeBatch();
			updateMatLockpsta.executeBatch();
			connection.commit();
			cro.setV_errMsg("撤销申请改判成功!");

        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                	cro.setV_errMsg(e.getMessage());
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
	}
}
