package com.steering.mes.mcp.common;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.converter.EntityTool;
import com.steering.comm.converter.QualityDesignTool;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.StringTool;
import com.steering.mes.mcp.Mch.FrmMchBugD;
import com.steering.mes.mcp.Mch.FrmMcpLoading;
import com.steering.mes.mcp.coup.PhosphateResultService;
import com.steering.mes.mcp.entity.*;
import com.steering.message.server.messageHelper;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * Created by 朱少波 on 2018/11/7.
 */
public class frmEntrust extends DBCommon {

    /**
     * 查询产线默认付费方
     *
     * @param plinCode 产线
     * @return 付费方代码
     */
    public CoreReturnObject doQueryDefaultPay(String plinCode) {
        return this.getDataBySqlID("frmEntrust.doQueryDefaultPay",
                new Object[]{plinCode});
    }

    /**
     * 查询产线默认付费方
     *
     * @return 付费方代码
     */
    public CoreReturnObject doQueryStorage() {
        return this
                .getDataBySqlID("frmEntrust.doQueryStorage", new Object[]{});
    }

    /**
     * 查询产线默认付费方
     *
     * @return 付费方代码
     */
    public CoreReturnObject doQueryStorage(String[] plineCodes) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryStorage2");


        sql += "AND (B.BASENAME IS NOT NULL OR  ";
        sql +=   CoreConverter.toSqlConditionString("A.STORAGE_NO",
                plineCodes).replace("AND","");
        sql += ")";



        return this.getData(sql);
    }


    /**
     * 查询离线数据
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject doQueryOffline(String start, String end,
                                           String judgeStoveNo, String[] plinCodes, String Status) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryOffline");
        String Time1 = "";
        String Time2 = "";
        String Time3 = "";
        String Time4 = "";
        String JudgeStr = "";
        String PlineCodesStr = "";
        String PlineCodesStr1 = "";
        String StatusStr = "";
        String StatusStr1 = "/";

        if (!start.equals("")) {
            Time1 = " AND T.OFFLINE_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')AND T.OFFLINE_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";

            Time2 = " AND T.PRO_TIME >=TO_DATE('" + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.PRO_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
            Time3 = " AND T.COL_TIME >=TO_DATE('" + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.COL_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
            Time4 = " AND T.INSTOCK_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.INSTOCK_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        PlineCodesStr = CoreConverter.toSqlConditionString("T.PLINE_CODE",
                plinCodes);
        PlineCodesStr1 = CoreConverter.toSqlConditionString("'002001001'",
                plinCodes);

        if (!judgeStoveNo.equals("")) {
            JudgeStr = " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (Status.equals("1")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG IS NULL OR E.SUBCONTRACT_LOG = '20' OR E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("2")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG = '10' OR E.SUBCONTRACT_LOG ='00'  OR E.SUBCONTRACT_LOG ='30')";
        } else if (Status.equals("3")) {
            StatusStr = " AND ( E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("4")) {
            StatusStr1 = "BC";
        } else if (Status.equals("5")) {
            StatusStr1 = "ZC";
        }

        sql = sql.replace("#TIME1#", Time1).replace("#TIME2#", Time2).replace(
                "#TIME3#", Time3).replace("#TIME4#", Time4).replace(
                "#JUDGESTOVE#", JudgeStr).replace("#STATUS#", StatusStr)
                .replace("#STATUS1#", StatusStr1).replace("#PLINECODE#",
                        PlineCodesStr).replace("#PLINECODE1#", PlineCodesStr1);

        return this.getData(sql);
    }



    /**
     * 查询离线数据
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @param flagstove
     * @return
     */
    public CoreReturnObject doQueryOffline(String start, String end,
                                           String judgeStoveNo, String[] plinCodes, String Status,String flagstove) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryOffline");
        String Time1 = "";
        String Time2 = "";
        String Time3 = "";
        String Time4 = "";
        String JudgeStr = "";
        String PlineCodesStr = "";
        String PlineCodesStr1 = "";
        String StatusStr = "";
        String flagstoveStr="";
        String StatusStr1 = "/";

        if (!start.equals("")) {
            Time1 = " AND T.OFFLINE_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')AND T.OFFLINE_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";

            Time2 = " AND T.PRO_TIME >=TO_DATE('" + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.PRO_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
            Time3 = " AND T.COL_TIME >=TO_DATE('" + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.COL_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
            Time4 = " AND T.INSTOCK_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.INSTOCK_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        PlineCodesStr = CoreConverter.toSqlConditionString("T.PLINE_CODE",
                plinCodes);
        PlineCodesStr1 = CoreConverter.toSqlConditionString("'002001001'",
                plinCodes);

        if (!judgeStoveNo.equals("")) {
            JudgeStr = " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (Status.equals("1")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG IS NULL OR E.SUBCONTRACT_LOG = '20' OR E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("2")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG = '10' OR E.SUBCONTRACT_LOG ='00'  OR E.SUBCONTRACT_LOG ='30')";
        } else if (Status.equals("3")) {
            StatusStr = " AND ( E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("4")) {
            StatusStr1 = "BC";
        } else if (Status.equals("5")) {
            StatusStr1 = "ZC";
        }

        sql = sql.replace("#TIME1#", Time1).replace("#TIME2#", Time2).replace(
                "#TIME3#", Time3).replace("#TIME4#", Time4).replace(
                "#JUDGESTOVE#", JudgeStr).replace("#STATUS#", StatusStr)
                .replace("#STATUS1#", StatusStr1).replace("#PLINECODE#",
                        PlineCodesStr).replace("#PLINECODE1#", PlineCodesStr1) ;
        if (!flagstove.equals("")) {
            sql =  sql+" AND NVL(s.FLAG_STOVE_NO,s.JUDGE_STOVE_NO)  LIKE  '" + flagstove + "%'";
        }

        System.out.println("Hello, World!");
        System.out.println(sql);
        CoreReturnObject assd = this.getData(sql);
        
        return assd;
    }


    /**
     * 查询离线数据
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject doQueryBc(String start, String end,
                                      String judgeStoveNo, String[] plinCodes, String Status) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQueryBC");

        String Time4 = "";

        String JudgeStr = "";

        String PlineCodesStr1 = "";

        String StatusStr = "";
        String StatusStr1 = "BC";

        if (!start.equals("")) {
            Time4 = " AND T.INSTOCK_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.INSTOCK_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        PlineCodesStr1 = CoreConverter.toSqlConditionString("PLINE_CODE",
                plinCodes);

        if (!judgeStoveNo.equals("")) {
            JudgeStr = " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (Status.equals("BC")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG IS NULL OR E.SUBCONTRACT_LOG = '20' OR E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("2")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG = '10' OR E.SUBCONTRACT_LOG ='00'  OR E.SUBCONTRACT_LOG ='30')";
        } else if (Status.equals("3")) {
            StatusStr = " AND ( E.SUBCONTRACT_LOG ='60')";
        }

        sql = sql.replace("#TIME4#", Time4).replace("#JUDGESTOVE#", JudgeStr)
                .replace("#STATUS#", StatusStr)
                .replace("#STATUS1#", StatusStr1).replace("#PLINECODE1#",
                        PlineCodesStr1);

        return this.getData(sql);
    }

    /**
     * 查询离线数据
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject doQueryZc(String start, String end,
                                      String judgeStoveNo, String[] plinCodes, String Status,String orderNo) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQueryZC");

        String Time4 = "";

        String JudgeStr = "";

        String PlineCodesStr1 = "";

        String StatusStr = "";
        String StatusStr1 = "'ZC'";

        if (!start.equals("")) {
            Time4 = " AND T.INSTOCK_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND T.INSTOCK_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        PlineCodesStr1 = CoreConverter.toSqlConditionString("BELONG_CODE",
                plinCodes);

        if (!judgeStoveNo.equals("")) {
            JudgeStr = " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }
        if (!orderNo.equals("")) {
            orderNo = " AND T.ORDER_NO LIKE  '" + orderNo + "%'";
        }

        if (Status.equals("1")) {
            StatusStr = " AND (E.SUBCONTRACT_LOG IS NULL OR E.SUBCONTRACT_LOG = '20' OR E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("2")) { // 已委外
            StatusStr = " AND (E.SUBCONTRACT_LOG = '10' OR E.SUBCONTRACT_LOG ='00'  OR E.SUBCONTRACT_LOG ='30')";
        } else if (Status.equals("3")) { // 委外完成
            StatusStr = " AND ( E.SUBCONTRACT_LOG ='60')";
        } else if (Status.equals("SP")){ // 商品
            StatusStr1 = "'SP'";
        } else if (Status.equals("0")){ // 全部
            StatusStr1 = "'SP','ZC'";
        }

        sql = sql.replace("#TIME4#", Time4).replace("#JUDGESTOVE#", JudgeStr)
                .replace("#STATUS#", StatusStr).replace("#ORDERNO#", orderNo)
                .replace("#STATUS1#", StatusStr1).replace("#PLINECODE1#",
                        PlineCodesStr1);

        return this.getData(sql);
    }

    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Step
     * @param Status
     * @param Target
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end,
                                         String judgeStoveNo, String[] plinCodes, String Step,
                                         String Status, String Target) {

        return doQueryApply(start, end,
                judgeStoveNo, plinCodes, Step,
                Status, Target, null);
    }

    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Step
     * @param Status
     * @param Target
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end,
                                         String judgeStoveNo, String[] plinCodes, String Step,
                                         String Status, String Target, String[] items) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQueryApply");

        if (!start.equals("")) {

            sql += " AND T.SUBCONTRACT_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')AND T.SUBCONTRACT_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        if (items != null && items.length > 0) {
            sql += " AND  EXISTS (SELECT 1 FROM HTT_ENTRUST_PROJECT P" +
                    " WHERE T.SUBCONTRACT_NO = P.SUBCONTRACT_NO" +
                    " AND T.SUBCONTRACT_NO_SEQ = P.SUBCONTRACT_NO_SEQ " +
                    CoreConverter.toSqlNotLikeConditionString("P.PROJECT_CODE", items) +
                    ")";
        } else {

            sql += " AND (";

            sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plinCodes)
                    .replace("AND", "");

            sql += " OR ";

            sql += CoreConverter.toSqlConditionString("T.SUBCONTRACT_PLINE_CODE",
                    plinCodes).replace("AND", "");


            sql += ") ";
        }

        if (!judgeStoveNo.equals("")) {
            sql += " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (Step.equals("1")) {
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('00','23','25','27') ";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('10', '20') ";
            }
        } else if (Step.equals("2")) {
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('28')  AND  SUBCONTRACT_TYPE = '1'";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('22', '23') ";
            }
        } else if (Step.equals("3")) {
            if (Status.equals("1")) {
                sql += " AND ((T.SUBCONTRACT_LOG IN ('28') AND  SUBCONTRACT_TYPE = '0' ) OR (T.SUBCONTRACT_LOG IN ('22') AND  SUBCONTRACT_TYPE = '1' ) ) ";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('24', '25') ";
            } else if (Status.equals("3")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('50') ";
            }
        } else if (Step.equals("4")) {
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('40') ";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('50') ";
            }
        } else if(Step.equals("7")){
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('10') ";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('26', '27') ";
            }
        } else if(Step.equals("8")){
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('26') ";
            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN ('28') ";
            }
        }

        if (!Target.equals("")) {
            sql += " AND T.SUBCONTRACT_TARGET = '" + Target + "'";
        }


        sql += " ORDER BY T.SUBCONTRACT_TARGET,T.PLINE_CODE,T.SUBCONTRACT_TIME,T.SUBCONTRACT_NO,T.SUBCONTRACT_NO_SEQ ";

        return this.getData(sql);
    }

    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param OrderNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end,
                                         String judgeStoveNo, String OrderNo, String[] plinCodes,
                                         String Status) {

        return doQueryApply(start, end, "", judgeStoveNo, OrderNo, plinCodes,
                Status, "");
    }


    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param No
     * @param judgeStoveNo
     * @param OrderNo
     * @param plinCodes
     * @param Status
     * @param Target
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end, String No,
                                         String judgeStoveNo, String OrderNo, String[] plinCodes,
                                         String Status, String Target) {

        return doQueryApply(start, end, No, judgeStoveNo, OrderNo, plinCodes,
                Status, Target, null, "", "");
    }


    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param No
     * @param judgeStoveNo
     * @param OrderNo
     * @param plinCodes
     * @param Status
     * @param Target
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end, String No,
                                         String judgeStoveNo, String OrderNo, String[] plinCodes,
                                         String Status, String Target, String timeType, String userName) {

        return doQueryApply(start, end, No, judgeStoveNo, OrderNo, plinCodes,
                Status, Target, null, timeType, userName);
    }

    /**
     * 查询委托单
     *
     * @param start
     * @param end
     * @param No
     * @param judgeStoveNo
     * @param OrderNo
     * @param plinCodes
     * @param Status
     * @param Target
     * @return
     */
    public CoreReturnObject doQueryApply(String start, String end, String No,
                                         String judgeStoveNo, String OrderNo, String[] plinCodes,
                                         String Status, String Target, String[] items, String timeType, String userName) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQueryApply");

        if ("".equals(timeType) || "0".equals(timeType)) {

            if (!start.equals("")) {

                sql += " AND T.SUBCONTRACT_TIME >=TO_DATE('"
                        + start
                        + "', 'YYYY-MM-DD HH24:MI:SS')AND T.SUBCONTRACT_TIME <=TO_DATE('"
                        + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
            }
        } else {
            sql += " AND EXISTS (SELECT 1 FROM Htt_Entrust_Process p WHERE p.subcontract_no = t.subcontract_no AND " +
                    " p.operate_action IN (";
            if (timeType.equals("1")) {
                sql += "'科室审核通过'";
            } else  if (timeType.equals("2")) {
                sql += "'制造部审核通过','管理部门审核通过'";
            }else  if (timeType.equals("3")) {
                sql += "'回报完毕'";
            }else  if (timeType.equals("4")) {
                sql += "'委外回报审核通过'";
            }else  if (timeType.equals("5")) {
                sql += "'委托完成','委内完成','委外完成'";
            }else  if (timeType.equals("7")) {
                sql += "'主管审核通过'";
            }else  if (timeType.equals("8")) {
                sql += "'生产计划部审核通过'";
            }else {
                sql += "''";
            }

            sql += ")";
            if (!"".equals(userName)) {
                sql += " AND P.OPERATE_NAME LIKE '%" + userName + "%' ";
            }
            sql += "AND P.OPERATE_DATE >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')  AND P.OPERATE_DATE <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS')) ";

        }

        sql += " AND (";

        sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plinCodes)
                .replace("AND", "");

        sql += " OR ";

        sql += CoreConverter.toSqlConditionString("T.SUBCONTRACT_PLINE_CODE",
                plinCodes).replace("AND", "");

        sql += ") ";

        if (!judgeStoveNo.equals("")) {
            sql += " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (!OrderNo.equals("")) {
            sql += " AND T.ORDER_NO LIKE  '" + OrderNo + "%'";
        }
        if (!No.equals("")) {
            sql += " AND T.SUBCONTRACT_NO LIKE  '" + No + "%'";
        }

        if (!Status.equals("")) {
            if (Status.equals("1")) {
                sql += " AND T.SUBCONTRACT_LOG =  '60' ";

            } else if (Status.equals("2")) {
                sql += " AND T.SUBCONTRACT_LOG IN  ('29','30') ";

            } else {
                sql += " AND T.SUBCONTRACT_LOG <>  '60' ";
            }
        }

        if (!Target.equals("")) {
            sql += " AND T.SUBCONTRACT_TARGET = '" + Target + "'";
        }

        if (items != null && items.length > 0) {
            sql += " AND  EXISTS (SELECT 1 FROM HTT_ENTRUST_PROJECT P" +
                    " WHERE T.SUBCONTRACT_NO = P.SUBCONTRACT_NO" +
                    " AND T.SUBCONTRACT_NO_SEQ = P.SUBCONTRACT_NO_SEQ " +
                    CoreConverter.toSqlNotLikeConditionString("P.PROJECT_CODE", items) +
                    ")";
        }

        sql += " ORDER BY T.SUBCONTRACT_TARGET,T.PLINE_CODE,T.SUBCONTRACT_TIME,T.SUBCONTRACT_NO,T.SUBCONTRACT_NO_SEQ ";

        return this.getData(sql);
    }

    /**
     * 查询回报界面委托单
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject QueryRelpay(String start, String end,
                                        String judgeStoveNo, String[] plinCodes, String Status) {

        return QueryRelpay(start, end,
                judgeStoveNo, plinCodes, Status, null);
    }

    /**
     * 查询回报界面委托单
     *
     * @param start
     * @param end
     * @param judgeStoveNo
     * @param plinCodes
     * @param Status
     * @return
     */
    public CoreReturnObject QueryRelpay(String start, String end,
                                        String judgeStoveNo, String[] plinCodes, String Status, String[] items) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQueryApply");

        if (!start.equals("")) {

            sql += " AND T.SP_TIME >=TO_DATE('" + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')AND T.SP_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }

        sql += CoreConverter.toSqlConditionString("T.SUBCONTRACT_PLINE_CODE",
                plinCodes);

        if (!judgeStoveNo.equals("")) {
            sql += " AND T.JUDGE_STOVE_NO LIKE  '" + judgeStoveNo + "%'";
        }

        if (Status.equals("1")) {
            sql += " AND ((T.SUBCONTRACT_LOG IN ('29','30','24') AND T.SUBCONTRACT_TARGET= '0') "
                    + "OR (T.SUBCONTRACT_LOG IN ('29','10','30') AND T.SUBCONTRACT_TARGET= '1')  )";
        } else if (Status.equals("2")) {
            sql += " AND T.SUBCONTRACT_LOG IN ('40','50','60') ";
        } else if (Status.equals("3")) {
            sql += " AND ((T.SUBCONTRACT_LOG IN ('24') AND T.SUBCONTRACT_TARGET= '0') "
                    + "OR (T.SUBCONTRACT_LOG IN ('10') AND T.SUBCONTRACT_TARGET= '1')  )";
        } else if (Status.equals("4")) {
            sql += " AND T.SUBCONTRACT_LOG IN ('29','30') ";
        } else {

            sql += " AND ((T.SUBCONTRACT_LOG IN ('29','30','24','40','50','60') AND T.SUBCONTRACT_TARGET= '0') "
                    + "OR (T.SUBCONTRACT_LOG IN ('29','30','10','40','50','60') AND T.SUBCONTRACT_TARGET= '1')  )";

        }

        if (items != null && items.length > 0) {
            sql += " AND  EXISTS (SELECT 1 FROM HTT_ENTRUST_PROJECT P" +
                    " WHERE T.SUBCONTRACT_NO = P.SUBCONTRACT_NO" +
                    " AND T.SUBCONTRACT_NO_SEQ = P.SUBCONTRACT_NO_SEQ " +
                    CoreConverter.toSqlNotLikeConditionString("P.PROJECT_CODE", items) +
                    ")";
        }

        sql += " ORDER BY T.PLINE_CODE,T.SUBCONTRACT_TIME ,T.SUBCONTRACT_NO,T.SUBCONTRACT_NO_SEQ ";

        return this.getData(sql);
    }

    /**
     * 查询委托项目
     *
     * @param SubNo
     * @param Seq
     * @return
     */
    public CoreReturnObject QueryProject(String SubNo, String Seq) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.selectProject");

        sql += " AND  SUBCONTRACT_NO ='" + SubNo + "' AND SUBCONTRACT_NO_SEQ='"
                + Seq + "'  ORDER BY  PROJECT_SEQ,PROJECT_CODE";

        return this.getData(sql);
    }

    /**
     * 查询委托项目
     *
     * @param SubNo
     * @return
     */
    public CoreReturnObject QueryProject(String[] SubNo) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.selectProject");

        sql += PlanService.toSqlConditionString("T.SUBCONTRACT_NO", SubNo);

        return this.getData(sql);
    }

    /**
     * 查询委托审批流程
     *
     * @param SubNo
     * @param Seq
     * @return
     */
    public CoreReturnObject QueryProcess(String SubNo, String Seq) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.selectProcess");

        sql += " AND  SUBCONTRACT_NO ='" + SubNo + "'  ORDER BY OPERATE_SEQ";

        return this.getData(sql);
    }

    /**
     * 查询委托回报实绩
     *
     * @param SubNo
     * @param SubSeq
     * @return
     */
    public CoreReturnObject doQueryResult(String SubNo, String SubSeq) {
        return this.getDataBySqlID("frmEntrust.doQueryResult", new Object[]{
                SubNo, SubSeq});
    }

    /**
     * 委托申请
     *
     * @param ResultNos
     * @param Process
     * @param PlineCode
     * @param ProjectStrs
     * @param Name
     * @param Shift
     * @param Group
     * @param SubTarget
     * @param Note
     * @param Operator
     * @return
     */
    public CoreReturnObject Apply(ArrayList<String> ResultNos, String Process,
                                  String PlineCode, ArrayList<String> ProjectStrs, String Name,
                                  String Shift, String Group, String SubTarget, String Note,
                                  String Operator, String No) {
        ArrayList<ArrayList<String>> Re = new ArrayList<ArrayList<String>>();
        Re.add(ResultNos);

        return ApplyAll(Re, Process, PlineCode, ProjectStrs, Name, Shift,
                Group, SubTarget, Note, Operator, No, "0");
    }

    /**
     * 委托申请
     *
     * @param ResultNos
     * @param Process
     * @param PlineCode
     * @param ProjectStrs
     * @param Name
     * @param Shift
     * @param Group
     * @param SubTarget
     * @param Note
     * @param Operator
     * @return
     */
    public CoreReturnObject Apply(ArrayList<String> ResultNos, String Process,
                                  String PlineCode, ArrayList<String> ProjectStrs, String Name,
                                  String Shift, String Group, String SubTarget, String Note,
                                  String Operator, String No, String Flag) {
        ArrayList<ArrayList<String>> Re = new ArrayList<ArrayList<String>>();
        Re.add(ResultNos);

        return ApplyAll(Re, Process, PlineCode, ProjectStrs, Name, Shift,
                Group, SubTarget, Note, Operator, No, Flag);
    }

    /**
     * 委托申请
     *
     * @param Process
     * @param PlineCode
     * @param ProjectStrs
     * @param Name
     * @param Shift
     * @param Group
     * @param SubTarget
     * @param Note
     * @param Operator
     * @return
     */
    public CoreReturnObject ApplyAll(ArrayList<ArrayList<String>> ResultNoSs,
                                     String Process, String PlineCode, ArrayList<String> ProjectStrs,
                                     String Name, String Shift, String Group, String SubTarget,
                                     String Note, String Operator, String No) {
        return ApplyAll(ResultNoSs, Process, PlineCode, ProjectStrs, Name,
                Shift, Group, SubTarget, Note, Operator, No, "0");
    }

    /**
     * 委托申请
     *
     * @param Process
     * @param PlineCode
     * @param ProjectStrs
     * @param Name
     * @param Shift
     * @param Group
     * @param SubTarget
     * @param Note
     * @param Operator
     * @return
     */
    public CoreReturnObject ApplyAll(ArrayList<ArrayList<String>> ResultNoSs,
                                     String Process, String PlineCode, ArrayList<String> ProjectStrs,
                                     String Name, String Shift, String Group, String SubTarget,
                                     String Note, String Operator, String No, String Flag) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            for (ArrayList<String> ResultNos : ResultNoSs) {

                String sqlAddProcess = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.AddProcess");
                PreparedStatement patAddProcess = connection
                        .prepareStatement(sqlAddProcess);

                String SubNo = "";
                String sqlloading = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.doQueryMaxNo");// 查询最大实绩编号
                PreparedStatement psta = connection
                        .prepareStatement(sqlloading);
                psta.setObject(1, PlineCode);
                psta.setObject(2, PlineCode);
                ResultSet rs1 = psta.executeQuery();
                if (rs1.next()) {
                    SubNo = rs1.getString("SUBCONTRACT_NO");
                }
                rs1.close();
                psta.close();

                int Count = 0;

                StringBuilder Projects = new StringBuilder();
                StringBuilder JudgeStove = new StringBuilder();
                String PlineName = "";

                for (String OffLineDataStr : ResultNos) {
                    OfflineResultEntity OffLineData = EntityTool
                            .getEntityByJSONStr(OffLineDataStr,
                                    OfflineResultEntity.class);
                    String ResultNo = OffLineData.getResultNo();

                    List<OfflineResultEntity> OfflineResultEntitys = GetOffLineResultEntity(
                            Process, connection, ResultNo, OffLineData
                                    .getMatNos());
                    if (OfflineResultEntitys == null
                            || OfflineResultEntitys.size() <= 0) {
                        throw new Exception("数据异常, 找不到离线数据，请刷新数据");
                    }

                    if (!OfflineResultEntitys.get(0).getType().equals("")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "BC")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "ZC")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "SP")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "null")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "20")
                            && !OfflineResultEntitys.get(0).getType().equals(
                            "60")) {
                        throw new Exception("已经申请委外，不能重复申请");
                    }

                    int TotalOffNum = 0;
                    double TotalOffWt = 0d;

                    Boolean IsCrack = false;


                    for (int i = 0; i < OfflineResultEntitys.size(); i++, Count++) {
                        OfflineResultEntity entity = OfflineResultEntitys
                                .get(i);
                        String NewBatchNo = "";

                        String sqlAddProject = CoreXmlSqlParsersFactory
                                .getSql("frmEntrust.AddApplyProject");
                        PreparedStatement patAddProject = connection
                                .prepareStatement(sqlAddProject);

                        if (ProjectStrs.size() <= 0) {
                            throw new Exception("请选择需要委托的项目");
                        }

                        if (JudgeStove.toString().equals("")) JudgeStove = new StringBuilder(entity.getJudgeStoveNo());
                        else if (!JudgeStove.toString().equals(entity.getJudgeStoveNo()) && !JudgeStove.toString().contains("," + entity.getJudgeStoveNo()) && !JudgeStove.toString().contains(entity.getJudgeStoveNo() + ","))
                            JudgeStove.append(",").append(entity.getJudgeStoveNo());

                        int ProjectSeq = 1;

                        Projects = new StringBuilder();
                        PlineName = entity.getPlineName();

                        boolean isExitsPackage = false;
                        boolean isExitsNonePackage = false;


                        for (String ProjectStr : ProjectStrs) {
                            HttEntrustProjectEntity Project = EntityTool
                                    .getEntityByJSONStr(ProjectStr,
                                            HttEntrustProjectEntity.class);

                            if (Projects.toString().equals("")) Projects = new StringBuilder(Project.getProjectName());
                            else Projects.append(",").append(Project.getProjectName());

                            if (Project.getProjectCode().startsWith("702201")) {
                                NewBatchNo = GetNewBatchNo(connection, entity
                                        .getJudgeStoveNo(), entity.getProcess());
                                if (NewBatchNo.equals("")
                                        || NewBatchNo.equals("null")) {
                                    throw new Exception("未委托过的批号无法申请热处理");
                                }
                            }

                            if (Project.getProjectCode().startsWith("702202")) {
                                if (entity.getBatchNo().equals("")
                                        && !Process.equals("D")) {
                                    throw new Exception("未分批不能申请探伤");
                                }

                                IsCrack = true;
                            }

                            if (Project.getProjectCode().startsWith("702205")) {
                                isExitsPackage = true;
                            } else {
                                isExitsNonePackage = true;
                            }

                            patAddProject
                                    .setObject(1, Project.getProjectCode());
                            patAddProject
                                    .setObject(2, Project.getProjectName());
                            patAddProject.setObject(3, Project
                                    .getProjectStatus());
                            patAddProject
                                    .setObject(4, Project.getProjectMemo());
                            patAddProject
                                    .setObject(5, Project.getProjectFlag());
                            patAddProject.setObject(6, SubNo);
                            patAddProject.setObject(7, Count + "");
                            patAddProject
                                    .setObject(8, Project.getProjectType());
                            patAddProject
                                    .setObject(9, Project.getProjectMemo());
                            patAddProject.setObject(10, Project
                                    .getProjectType());
                            patAddProject.setObject(11, Project
                                    .getPayDepartmentCode());
                            patAddProject.setObject(12, Project
                                    .getPayDepartmentName());
                            patAddProject.setObject(13, ProjectSeq++);
                            patAddProject.addBatch();

                        }


                        if (isExitsPackage && isExitsNonePackage) {
                            throw new Exception("钢管包装项目不能与非钢管包装项目同时委托!");
                        }

                        patAddProject.executeBatch();

                        int OffNum = 0;
                        double OffWt = 0d;

                        if (StringTool.isInteger(entity.getOfflineNum())) {
                            OffNum = Integer.parseInt(entity.getOfflineNum());
                        }

                        if (StringTool.isDouble(entity.getOfflineWt())) {
                            OffWt = Double.parseDouble(entity.getOfflineWt());
                        }

                        TotalOffNum = TotalOffNum + OffNum;
                        TotalOffWt = TotalOffWt + OffWt;

                        if (OffNum == 0)
                            continue;

                        HttEntrustEntity EntrustEntity = new HttEntrustEntity();
                        EntrustEntity.setSubcontractNo(SubNo);
                        EntrustEntity.setSubcontractNoSeq(Count + "");
                        EntrustEntity.setPlineCode(entity.getPlineCode());
                        EntrustEntity.setPlineName(entity.getPlineName());
                        EntrustEntity.setHeatPlanNo(entity.getHeatPlanNo());
                        EntrustEntity.setLotNo(entity.getZyBatchId());
                        EntrustEntity.setJudgeStoveNo(entity.getJudgeStoveNo());
                        EntrustEntity.setBatchNo(entity.getBatchNo());
                        EntrustEntity.setProPlanId(entity.getProPlanId());
                        EntrustEntity.setGxPlanNo(entity.getGxPlanNo());
                        EntrustEntity.setProduccode(entity.getProduccode());
                        EntrustEntity.setProducname(entity.getProducname());
                        EntrustEntity.setSteelcode(entity.getSteelcode());
                        EntrustEntity.setSteelname(entity.getSteelname());
                        EntrustEntity.setGradecode(entity.getGradecode());
                        EntrustEntity.setGradename(entity.getGradename());
                        EntrustEntity.setModelCode(entity.getModelCode());
                        EntrustEntity.setModelDesc(entity.getModelDesc());
                        EntrustEntity.setStdCode(entity.getStdCode());
                        EntrustEntity.setStdName(entity.getStdName());
                        EntrustEntity.setStdStyle(entity.getStdStyle());
                        EntrustEntity.setStdStyleDesc(entity.getStdStyleDesc());
                        EntrustEntity.setSpecCode(entity.getSpecCode());
                        EntrustEntity.setSpecName(entity.getSpecName());
                        EntrustEntity.setResultNo(ResultNo);
                        EntrustEntity.setSubcontractLog("00");
                        EntrustEntity.setSubcontractUser(Name);
                        EntrustEntity.setSubcontractShift(Shift);
                        EntrustEntity.setSubcontractGroup(Group);
                        EntrustEntity.setSubcontractType(IsCrack ? "1" : "0");
                        EntrustEntity.setNewBatchNo(NewBatchNo);
                        EntrustEntity.setOrderNo(entity.getOrderNo());
                        EntrustEntity.setActDimater(entity.getActDimater());
                        EntrustEntity.setActHeight(entity.getActHeight());
                        EntrustEntity.setSubcontractNum(entity.getOfflineNum());
                        EntrustEntity.setSubcontractWt(entity.getOfflineWt());
                        EntrustEntity.setProcessCode(entity.getProcess());
                        EntrustEntity.setSubcontractNote(Note);
                        EntrustEntity.setDrawingno(No);
                        EntrustEntity.setCic(entity.getCic());
                        EntrustEntity.setDic(entity.getDic());
                        EntrustEntity.setPic(entity.getPic());
                        EntrustEntity.setWic(entity.getWic());
                        EntrustEntity.setSic(entity.getSic());
                        EntrustEntity.setGic(entity.getGic());
                        EntrustEntity.setMscPline(entity.getMscPline());
                        EntrustEntity.setDesginKey(entity.getDesginKey());
                        EntrustEntity.setSubcontractTarget(SubTarget);
                        EntrustEntity.setSubcontractOperator(Operator);
                        EntrustEntity.setStorageTypeNo(OffLineData
                                .getStorageTypeNo());
                        EntrustEntity.setStorageTypeName(OffLineData
                                .getStorageTypeNo());
                        EntrustEntity.setIfMonitor(OffLineData.getIfMonitor());
                        EntrustEntity.setFlagStoveNo(OffLineData
                                .getFlagStoveNo());
                        EntrustEntity.setIsReturn(Flag);
                        EntrustEntity.setOutputStandard(entity.getOutputStandard());
                        EntrustEntity.setLoadJudgeStoveNo(entity.getLoadJudgeStoveNo());
                        EntrustEntity.setSubcontractLen(entity.getActLen());
                        String sqlAdd = CoreXmlSqlParsersFactory
                                .getSql("frmEntrust.AddApply");
                        sqlAdd = com.steering.common.EntityTool
                                .fillSqlByEntity(sqlAdd, EntrustEntity);
                        PreparedStatement patAdd = connection
                                .prepareStatement(sqlAdd);
                        patAdd.addBatch();
                        patAdd.executeBatch();

                        if (!NewBatchNo.equals(""))
                            UpdatePortBatchNo(connection, entity
                                            .getHeatPlanNo(), entity.getResultNo(),
                                    entity.getJudgeStoveNo(), entity
                                            .getBatchNo(), NewBatchNo, entity
                                            .getProcess(), EntrustEntity
                                            .getSubcontractNum());

                        if (Process.equals("H")) {
                            OffLineData
                                    .setMatNos(GetJGOfflieMatEntity(connection,
                                            OfflineResultEntitys.get(0)
                                                    .getJudgeStoveNo(),
                                            OfflineResultEntitys.get(0)
                                                    .getBatchNo(),
                                            OfflineResultEntitys.get(0)
                                                    .getBatchGroudNo(),
                                            OfflineResultEntitys.get(0)
                                                    .getOfflineNum()));
                        }

                        UpdateMatSubNo(Process, connection, SubNo, Count + "",
                                ResultNo, OffLineData.getMatNos());



						/*AppMessageEntity appMessageEntity = new AppMessageEntity();
                        String MessageNo = "";
						String messageNoSql = CoreXmlSqlParsersFactory
								.getSql("frmEntrust.getMessageNo");// 查询最大实绩编号
						psta = connection
								.prepareStatement(messageNoSql);
						psta.setObject(1, PlineCode);
						psta.setObject(2, PlineCode);
						rs1 = psta.executeQuery();
						if (rs1.next()) {
							MessageNo = rs1.getString("MESSAGE_NO");
						}
						rs1.close();
						psta.close();
						appMessageEntity.setMessageNo(MessageNo);
						appMessageEntity.setMessageTitle(EntrustEntity.getPlineName() +"-"
								+ (EntrustEntity.getSubcontractTarget().equals("1")?"委内申请":"委外申请")
						);
						appMessageEntity.setMessageLevelCode("90040101");
						appMessageEntity.setMessageClassCode("90040202");
						appMessageEntity.setMessageContent("项目" +":" +Projects);
						appMessageEntity.setReleaseName(EntrustEntity.getSubcontractUser());
						appMessageEntity.setValidflag("20");
						appMessageEntity.setCreateName(EntrustEntity.getSubcontractUser());
						appMessageEntity.setCre*/
                    }

                    if (TotalOffNum <= 0) {
                        throw new Exception(OfflineResultEntitys.get(0)
                                .getJudgeStoveNo()
                                + "炉没有足够的离线支数,无法申请");
                    }

                    UpdateEntrustNum(Process, connection, ResultNo);

                }

                patAddProcess.setObject(1, SubNo);
                patAddProcess.setObject(2, SubNo);
                patAddProcess.setObject(3, "申请委托");
                patAddProcess.setObject(4, Name);
                patAddProcess.setObject(5, "");
                patAddProcess.setObject(6, "");
                patAddProcess.setObject(7, "00");
                patAddProcess.addBatch();


                patAddProcess.executeBatch();


                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        "00", "1",
                        "[" + ( "0".equals(SubTarget) ? "委外" : "委内" ) + "] " + PlineName,
                        JudgeStove.toString() + " " + Projects.toString()
                        , "", Name);



                if(PlineCode.equals("C072") || PlineCode.equals("C091") ){
                    ArrayList<String> list = new ArrayList<String>();
                    list.add(SubNo);

                    ApprovalOKM(list,"1","C092","", Name,false,true,"1",connection);
                }


            }




            core.setV_errMsg("申请成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 撤销申请
     *
     * @param SubNos
     * @param Process
     * @return
     */
    public CoreReturnObject CancelApply(ArrayList<String> SubNos, String Process) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                if (!HttEntrustEntitys.get(0).getSubcontractLog().equals("00")) {
                    throw new Exception("已审批,无法撤销!");
                }

                String sqlAdd = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.DeleteApply");//
                PreparedStatement patAdd = connection.prepareStatement(sqlAdd);
                patAdd.setObject(1, SubNo);
                patAdd.addBatch();
                patAdd.executeBatch();

                String sqlDelete = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.DeleteApplyProject");//
                PreparedStatement patDelete = connection
                        .prepareStatement(sqlDelete);
                patDelete.setObject(1, SubNo);
                patDelete.addBatch();
                patDelete.executeBatch();

                String sqlDelete1 = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.deleteProcess");//
                PreparedStatement patDelete1 = connection
                        .prepareStatement(sqlDelete1);
                patDelete1.setObject(1, SubNo);
                patDelete1.addBatch();
                patDelete1.executeBatch();


                String sqlDelete2 = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.deletemessge");//
                PreparedStatement patDelete2 = connection
                        .prepareStatement(sqlDelete2);
                patDelete2.setObject(1, SubNo);
                patDelete2.addBatch();
                patDelete2.executeBatch();


                for (int i = 0; i < HttEntrustEntitys.size(); i++) {
                    HttEntrustEntity entity = HttEntrustEntitys.get(i);

                    for (String Type : entity.getSubcontractType().split(",")) {
                        if (Type.equals("0")) {
                            String CheckNo = "";
                            String sql = CoreXmlSqlParsersFactory
                                    .getSql("frmEntrust.CheckApproval0");
                            PreparedStatement psta = connection
                                    .prepareStatement(sql);
                            psta.setString(1, entity.getJudgeStoveNo().split(
                                    "-")[0]);
                            psta.setString(2, entity.getNewBatchNo());
                            ResultSet rs = psta.executeQuery();
                            if (rs.next()) {
                                throw new Exception("请先撤销新批号,再审批!");
                            }
                            rs.close();
                            psta.close();
                        }
                    }

                    if (!entity.getNewBatchNo().equals("")) {
                        UpdatePortBatchNo(connection, entity.getHeatPlanNo(),
                                entity.getResultNo(), entity.getJudgeStoveNo(),
                                entity.getNewBatchNo(), entity.getBatchNo(),
                                entity.getProcessCode(), entity
                                        .getSubcontractNum());

                    }

                    UpdateEntrustNum(Process, connection, HttEntrustEntitys
                            .get(i).getResultNo());

                    String MatNos = GetEntrustMatNo(connection, Process, SubNo);

                    UpdateMatSubNo(Process, connection, "", "",
                            HttEntrustEntitys.get(i).getResultNo(), MatNos);

                }

            }

            core.setV_errMsg("撤销申请成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 删除委托单
     *
     * @param SubNos
     * @return
     */
    public CoreReturnObject Delete(ArrayList<String> SubNos) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                Integer CountResult = 0;

                String Countsql = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.doQueryResultCount");
                PreparedStatement pstaCount = connection
                        .prepareStatement(Countsql);
                pstaCount.setObject(1, SubNo);
                ResultSet rs1 = pstaCount.executeQuery();
                if (rs1.next()) {
                    CountResult = rs1.getInt("COUNT");
                }
                rs1.close();
                pstaCount.close();

                if (CountResult > 0) {
                    throw new Exception("已回报实绩,不允许删除!");
                }

                String sqlAdd = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.DeleteApply");//
                PreparedStatement patAdd = connection.prepareStatement(sqlAdd);
                patAdd.setObject(1, SubNo);
                patAdd.addBatch();
                patAdd.executeBatch();

                String sqlDelete = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.DeleteApplyProject");//
                PreparedStatement patDelete = connection
                        .prepareStatement(sqlDelete);
                patDelete.setObject(1, SubNo);
                patDelete.addBatch();
                patDelete.executeBatch();

                String sqlDelete1 = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.deleteProcess");//
                PreparedStatement patDelete1 = connection
                        .prepareStatement(sqlDelete1);
                patDelete1.setObject(1, SubNo);
                patDelete1.addBatch();
                patDelete1.executeBatch();

                String sqlDelete2 = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.deleteProcessAuto");//
                PreparedStatement patDelete2 = connection
                        .prepareStatement(sqlDelete2);
                patDelete2.setObject(1, SubNo);
                patDelete2.addBatch();
                patDelete2.executeBatch();


                String sqlDelete3 = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.deletemessge");//
                PreparedStatement patDelete3 = connection
                        .prepareStatement(sqlDelete3);
                patDelete3.setObject(1, SubNo);
                patDelete3.addBatch();
                patDelete3.executeBatch();

                for (int i = 0; i < HttEntrustEntitys.size(); i++) {
                    HttEntrustEntity entity = HttEntrustEntitys.get(i);

                    for (String Type : entity.getSubcontractType().split(",")) {
                        if (Type.equals("0")) {
                            String CheckNo = "";
                            String sql = CoreXmlSqlParsersFactory
                                    .getSql("frmEntrust.CheckApproval0");
                            PreparedStatement psta = connection
                                    .prepareStatement(sql);
                            psta.setString(1, entity.getJudgeStoveNo().split(
                                    "-")[0]);
                            psta.setString(2, entity.getNewBatchNo());
                            ResultSet rs = psta.executeQuery();
                            if (rs.next()) {
                                throw new Exception("请先撤销新批号,再审批!");
                            }
                            rs.close();
                            psta.close();
                        }
                    }

                    if (!entity.getNewBatchNo().equals("")) {
                        UpdatePortBatchNo(connection, entity.getHeatPlanNo(),
                                entity.getResultNo(), entity.getJudgeStoveNo(),
                                entity.getNewBatchNo(), entity.getBatchNo(),
                                entity.getProcessCode(), entity
                                        .getSubcontractNum());

                    }

                    UpdateEntrustNum(HttEntrustEntitys.get(i).getProcessCode(),
                            connection, HttEntrustEntitys.get(i).getResultNo());

                    String MatNos = GetEntrustMatNo(connection,
                            HttEntrustEntitys.get(i).getProcessCode(), SubNo);

                    UpdateMatSubNo(HttEntrustEntitys.get(i).getProcessCode(),
                            connection, "", "", HttEntrustEntitys.get(i)
                                    .getResultNo(), MatNos);

					/*
					 * String MatNos =
					 * GetEntrustMatNo(connection,Process,SubNo);
					 * UpdateMatSubNo(
					 * HttEntrustEntitys.get(i).getProcessCode(),connection
					 * ,"","",HttEntrustEntitys.get(i).getResultNo(),MatNos);
					 */

                }

            }

            core.setV_errMsg("删除成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 审批不通过
     *
     * @param SubNos
     * @param Step
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject ApprovalFail(ArrayList<String> SubNos, String Step,
                                         String Note, String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                String Status = "";
                String Info = "";
                String NextNo = "";

                for (int i = 0; i < HttEntrustEntitys.size(); i++) {
                    HttEntrustEntity entity = HttEntrustEntitys.get(i);

                    if (Step.equals("1")) {
                        if (!HttEntrustEntitys.get(i).getSubcontractLog()
                                .equals("00")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("23")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("25")) {
                            throw new Exception("不是未审核状态,无法审核!");
                        }
                        Info = "科室审核不通过";
                        Status = "20";
                        NextNo = "/";

                    } else if (Step.equals("2")) {
                        if (!HttEntrustEntitys.get(i).getSubcontractLog()
                                .equals("26")) {
                            throw new Exception("不是未审核状态,无法审核!");
                        }
                        Info = "探伤审核不通过";
                        Status = "23";
                        NextNo = "1";
                    } else if (Step.equals("3")) {
                        if (HttEntrustEntitys.get(i).getSubcontractType()
                                .equals("1")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("22")) {
                            throw new Exception("不是未审核状态,无法审核!");

                        }

                        if (HttEntrustEntitys.get(i).getSubcontractType()
                                .equals("0")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("10")) {
                            throw new Exception("不是未审核状态,无法审核!");
                        }

                        if (HttEntrustEntitys.get(i).getSubcontractType()
                                .equals("1")) {
                            NextNo = "2";
                        } else {
                            NextNo = "1";
                        }


                        Info = "管理部门审核不通过";
                        Status = "25";
                    } else if(Step.equals("7")){
                        if (!HttEntrustEntitys.get(i).getSubcontractLog()
                                .equals("10")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("23")
                                && !HttEntrustEntitys.get(i)
                                .getSubcontractLog().equals("25")) {
                            throw new Exception("不是未审核状态,无法审核!");
                        }
                        Info = "主管审核不通过";
                        Status = "27";
                        NextNo = "7";
                    }

                    // region 检查
                    if (Step.equals("1")) {
                        String sql = CoreXmlSqlParsersFactory
                                .getSql("frmEntrust.selectProject");// 查询新增物料信息
                        sql += " AND  SUBCONTRACT_NO =? AND SUBCONTRACT_NO_SEQ=?";
                        PreparedStatement psta = connection
                                .prepareStatement(sql);
                        psta.setObject(1, entity.getSubcontractNo());
                        psta.setObject(2, entity.getSubcontractNoSeq());
                        ResultSet rs = psta.executeQuery();
                        List<HttEntrustProjectEntity> Lists = EntityTool
                                .getEntitysByRs(
                                        rs,
                                        com.steering.mes.mcp.entity.HttEntrustProjectEntity.class);
                        rs.close();
                        psta.close();

                        for (HttEntrustProjectEntity Project : Lists) {
                            if (Project.getProjectCode().equals("702201")) {
                                String CheckNo = "";
                                sql = CoreXmlSqlParsersFactory
                                        .getSql("frmEntrust.CheckApproval0");
                                psta = connection.prepareStatement(sql);
                                psta.setString(1, entity.getJudgeStoveNo()
                                        .split("-")[0]);
                                psta.setString(2, entity.getNewBatchNo());
                                rs = psta.executeQuery();
                                if (rs.next()) {
                                    throw new Exception("请先撤销委托,再撤销审批!");
                                }
                                rs.close();
                                psta.close();
                            }
                        }
                    }
                    // endregion

                    if (!entity.getNewBatchNo().equals(""))
                        UpdatePortBatchNo(connection, entity.getHeatPlanNo(),
                                entity.getResultNo(), entity.getJudgeStoveNo(),
                                entity.getNewBatchNo(), entity.getBatchNo(),
                                entity.getProcessCode(), entity
                                        .getSubcontractNum());

                    if (i == 0) {

                        UpdateEntrustStatus(connection, SubNo, Status, "", "",
                                "", HttEntrustEntitys.get(0)
                                        .getSubcontractOperator(),
                                HttEntrustEntitys.get(0).getDrawingno(),
                                HttEntrustEntitys.get(0).getSubcontractNote());

                    }

                    if (Step.equals("1")) {
                        UpdateEntrustNum(entity.getProcessCode(), connection,
                                entity.getResultNo());

                        UpdateMatSubNo(entity.getProcessCode(), connection,
                                entity.getSubcontractNo(), "0");

                    }

                }

                patAddProcess.setObject(1, SubNo);
                patAddProcess.setObject(2, SubNo);
                patAddProcess.setObject(3, Info);
                patAddProcess.setObject(4, Name);
                patAddProcess.setObject(5, Note);
                patAddProcess.setObject(6, HttEntrustEntitys.get(0)
                        .getSubcontractLog());
                patAddProcess.setObject(7, Status);
                patAddProcess.addBatch();


                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        "60", NextNo,
                        "[" + ( "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntitys.get(0).getPlineName(),
                        ""
                        , "", Name);
            }
            patAddProcess.executeBatch();

            core.setV_errMsg("审核不通过成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    public CoreReturnObject ApprovalOk(ArrayList<String> SubNos, String Step,
                                       String PlineCode, String Note, String Name, String transCode) {

        return ApprovalOk(SubNos, Step, PlineCode, Note, Name, false, false,
                transCode);
    }

    /**
     * 审批通过
     *
     * @param SubNos
     * @param Step
     * @param PlineCode
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject ApprovalOk(ArrayList<String> SubNos, String Step,
                                       String PlineCode, String Note, String Name, Boolean Flag1,
                                       Boolean Flag2, String transCode) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();


        try {

            connection.setAutoCommit(false); // 取消自动提交事务

            ApprovalOKM(SubNos, Step, PlineCode, Note, Name, Flag1, Flag2, transCode, connection);

            core.setV_errMsg("审核通过成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务

                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }

            } catch (Exception e2) {
            }
        }
        return core;

    }

    private void ApprovalOKM(ArrayList<String> SubNos, String Step, String PlineCode, String Note, String Name, Boolean Flag1, Boolean Flag2, String transCode, Connection connection) throws Exception {
        String sqlAddProcess = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.AddProcess");
        PreparedStatement patAddProcess = connection
                .prepareStatement(sqlAddProcess);

        String sqlAddProcessAuto = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.AddProcessAuto");
        PreparedStatement patAddProcessAuto = connection
                .prepareStatement(sqlAddProcessAuto);

        for (String SubNo : SubNos) {

            if (SubNo.equals("")) {
                throw new Exception("未申请委外,请确认!");
            }

            List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                    connection, SubNo);
            if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                    || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                    "null")) {
                throw new Exception("未申请委外,请确认!");
            }

            String Status = "";
            String Info = "";
            String nextNo = "";

            for (int i = 0; i < HttEntrustEntitys.size(); i++) {

                HttEntrustEntity Entity = HttEntrustEntitys.get(i);

                if (Step.equals("1")) {
                    if (!HttEntrustEntitys.get(i).getSubcontractLog()
                            .equals("00")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("23")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("25")) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }
                    Info = "科室审核通过";
                    Status = "10";

                    if (HttEntrustEntitys.get(i).getSubcontractType().equals("1") && HttEntrustEntitys.get(i).getSubcontractTarget().equals("0")) {
                        nextNo = "2";
                    } else if (HttEntrustEntitys.get(i).getSubcontractType().equals("0") && HttEntrustEntitys.get(i).getSubcontractTarget().equals("0")) {
                        nextNo = "3";
                    } else {
                        nextNo = "5";
                    }

                } else if (Step.equals("2")) {
                    if (!HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("28")) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }
                    Info = "探伤审核通过";
                    Status = "22";
                    nextNo = "3";
                } else if (Step.equals("3")) {
                    if (HttEntrustEntitys.get(i).getSubcontractType()
                            .equals("1")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("22") ) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }

                    if (HttEntrustEntitys.get(i).getSubcontractType()
                            .equals("0")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("28")) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }

                    Info = "管理部门审核通过";
                    Status = "24";
                    nextNo = "4";
                } else if (Step.equals("4")) {
                    if (!HttEntrustEntitys.get(i).getSubcontractLog()
                            .equals("40")) {
                        throw new Exception("该委托单未全部回报完成!");
                    }
                    Status = "50";
                    Info = "委外回报审核通过";
                    nextNo = "6";
                } else if (Step.equals("7")) {
                    if (!HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("10")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("23")
                            && !HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("25")) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }
                    Status = "26";
                    Info = "主管审核通过";
                    nextNo = "7";
                }else if (Step.equals("8")) {
                    if (!HttEntrustEntitys.get(i)
                            .getSubcontractLog().equals("26")) {
                        throw new Exception("不是未审核状态,无法审核!");
                    }
                    Status = "28";
                    Info = "生产计划部审核通过";
                    nextNo = "8";
                }

                // region 检查
                if (Step.equals("1")) {
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.selectProject");
                    sql += " AND  SUBCONTRACT_NO =? AND SUBCONTRACT_NO_SEQ=?";
                    PreparedStatement psta = connection
                            .prepareStatement(sql);
                    psta.setObject(1, Entity.getSubcontractNo());
                    psta.setObject(2, Entity.getSubcontractNoSeq());
                    ResultSet rs = psta.executeQuery();
                    List<HttEntrustProjectEntity> Lists = EntityTool
                            .getEntitysByRs(
                                    rs,
                                    HttEntrustProjectEntity.class);
                    rs.close();
                    psta.close();

                    for (HttEntrustProjectEntity Project : Lists) {
                        if (Project.getProjectCode().equals("702201")) {
                            String CheckNo = "";
                            sql = CoreXmlSqlParsersFactory
                                    .getSql("frmEntrust.CheckApproval0");
                            psta = connection.prepareStatement(sql);
                            psta.setString(1, Entity.getJudgeStoveNo()
                                    .split("-")[0]);
                            psta.setString(2, Entity.getNewBatchNo());
                            rs = psta.executeQuery();
                            if (rs.next()) {
                                CheckNo = String.valueOf(rs
                                        .getString("CHECK_NO"));
                            }
                            rs.close();
                            psta.close();

                            /*if (CheckNo.equals("")) {
                                throw new Exception("请先委托新批号,再审批!");
                            }*/

                            /*sql = CoreXmlSqlParsersFactory
                                    .getSql("frmEntrust.UpdateEntrustCheckNo");
                            psta = connection.prepareStatement(sql);
                            psta.setString(1, CheckNo);
                            psta.setString(2, Entity.getSubcontractNo());
                            psta.setString(3, Entity.getSubcontractNoSeq());
                            psta.addBatch();
                            psta.executeBatch();*/
                        }
                    }
                }
                // endregion

                UpdateEntrustTransCode(connection, transCode, Entity
                        .getSubcontractNo(), Entity.getSubcontractNoSeq());
            }

            UpdateEntrustStatus(connection, SubNo, Status, PlineCode
                            .equals("") ? HttEntrustEntitys.get(0)
                            .getSubcontractPlineCode() : PlineCode, "", "",
                    HttEntrustEntitys.get(0).getSubcontractOperator(),
                    HttEntrustEntitys.get(0).getDrawingno(),
                    HttEntrustEntitys.get(0).getSubcontractNote());

            patAddProcess.setObject(1, SubNo);
            patAddProcess.setObject(2, SubNo);
            patAddProcess.setObject(3, Info);
            patAddProcess.setObject(4, Name);
            patAddProcess.setObject(5, Note);
            patAddProcess.setObject(6, HttEntrustEntitys.get(0)
                    .getSubcontractLog());
            patAddProcess.setObject(7, Status);
            patAddProcess.addBatch();
            patAddProcess.executeBatch();


            if (Flag1) {
                patAddProcessAuto.setObject(1, SubNo);
                patAddProcessAuto.setObject(2, "4");
                patAddProcessAuto.setObject(3, "0");
                patAddProcessAuto.addBatch();
                patAddProcessAuto.executeBatch();
            }

            if (Flag2) {
                patAddProcessAuto.setObject(1, SubNo);
                patAddProcessAuto.setObject(2, HttEntrustEntitys.get(0).getSubcontractTarget().equals("0") ? "6" : "5");
                patAddProcessAuto.setObject(3, "0");
                patAddProcessAuto.addBatch();
                patAddProcessAuto.executeBatch();
            }

            HttEntrustProcessDefaulEntity last = AutoApproval(connection, HttEntrustEntitys.get(0), null, Status);


            if (last == null) {
                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        Status, nextNo,
                        "[" + ( "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntitys.get(0).getPlineName(),
                        ""
                        , "", Name);
            } else {
                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        last.getStatusNext(), last.getApprovalNoNext(),
                        "[" + ( "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntitys.get(0).getPlineName(),
                        ""
                        , "", Name);
            }

        }
    }

    public HttEntrustProcessDefaulEntity AutoApproval(Connection connection, HttEntrustEntity Entity,
                                                      ArrayList<String> UsedStatus, String CurrentStatus)
            throws Exception {

        if (UsedStatus == null)
            UsedStatus = new ArrayList<String>();

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.QueryProcessByAuto");
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, CurrentStatus);
        psta.setObject(2, Entity.getSubcontractTarget());
        psta.setObject(3, Entity.getSubcontractNo());
        ResultSet rs = psta.executeQuery();
        List<HttEntrustProcessDefaulEntity> HttEntrustProcessDefaulEntitys = EntityTool
                .getEntitysByRs(rs, HttEntrustProcessDefaulEntity.class);
        rs.close();
        psta.close();

        if (HttEntrustProcessDefaulEntitys == null
                || HttEntrustProcessDefaulEntitys.size() <= 0) {
            return null;
        }

        String sqlAddProcess = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.AddProcess");
        PreparedStatement patAddProcess = connection
                .prepareStatement(sqlAddProcess);
        patAddProcess.setObject(1, Entity.getSubcontractNo());
        patAddProcess.setObject(2, Entity.getSubcontractNo());
        patAddProcess.setObject(3, HttEntrustProcessDefaulEntitys.get(0)
                .getMemo());
        patAddProcess.setObject(4, "系统");
        patAddProcess.setObject(5, "系统自动操作");
        patAddProcess.setObject(6, CurrentStatus);
        patAddProcess.setObject(7, HttEntrustProcessDefaulEntitys.get(0)
                .getStatusNext());
        patAddProcess.addBatch();
        patAddProcess.executeBatch();

        List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                connection, Entity.getSubcontractNo());
        if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
            throw new Exception("数据异常, 找不到委托数据，请刷新数据");
        }

        for (int i = 0; i < HttEntrustEntitys.size(); i++) {

            HttEntrustEntity data = HttEntrustEntitys.get(i);

            if (!data.getSubcontractLog().equals(CurrentStatus))
                return null;
        }

        if (HttEntrustProcessDefaulEntitys.get(0).getIsEnd().trim().equals("2")) {


            MarkCompleted("系统", connection, Entity.getSubcontractNo(),
                    HttEntrustEntitys);
            return HttEntrustProcessDefaulEntitys.get(0);


        } else {

            UpdateEntrustStatus(connection, Entity.getSubcontractNo(),
                    HttEntrustProcessDefaulEntitys.get(0).getStatusNext(),
                    Entity.getSubcontractPlineCode(), "", "", Entity
                            .getSubcontractOperator(), Entity.getDrawingno(),
                    Entity.getSubcontractNote());


            if (UsedStatus.contains(HttEntrustProcessDefaulEntitys.get(0)
                    .getStatusNext()))
                return null;

            UsedStatus.add(CurrentStatus);
            HttEntrustProcessDefaulEntity last = AutoApproval(connection, Entity, UsedStatus,
                    HttEntrustProcessDefaulEntitys.get(0).getStatusNext());

            if (last == null) return HttEntrustProcessDefaulEntitys.get(0);
            else return last;
        }

    }

    /**
     * 委托完成
     *
     * @param SubNos
     * @param Step
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject MarkCompleted(ArrayList<String> SubNos,
                                          String Step, String Note, String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                if (!Step.equals("1")
                        && HttEntrustEntitys.get(0).getSubcontractTarget()
                        .equals("1")) {
                    throw new Exception("无权限关闭委内委托单！!");
                }

                if (!Step.equals("3")
                        && HttEntrustEntitys.get(0).getSubcontractTarget()
                        .equals("0")) {
                    throw new Exception("无权限关闭委外委托单！!");
                }

                String Info = "委托完成";
                String Status = "60";
                MarkCompleted(Name, connection, SubNo, HttEntrustEntitys);

                patAddProcess.setObject(1, SubNo);
                patAddProcess.setObject(2, SubNo);
                patAddProcess.setObject(3, Info);
                patAddProcess.setObject(4, Name);
                patAddProcess.setObject(5, Note);
                patAddProcess.setObject(6, HttEntrustEntitys.get(0)
                        .getSubcontractLog());
                patAddProcess.setObject(7, Status);
                patAddProcess.addBatch();


            }
            patAddProcess.executeBatch();

            core.setV_errMsg("委托完成！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    private void MarkCompleted(String Name, Connection connection,
                               String SubNo, List<HttEntrustEntity> httEntrustEntitys)
            throws Exception {

        for (int i = 0; i < httEntrustEntitys.size(); i++) {

            HttEntrustEntity Entity = httEntrustEntitys.get(i);

            if (Entity.getSubcontractTarget().equals("0")) {

                if (!Entity.getSubcontractLog().equals("50")) {
                    throw new Exception("委托单回报未审核!");
                }
            } else {
                if (!Entity.getSubcontractLog().equals("40")) {
                    throw new Exception("委托单未回报完成!");
                }
            }
        }

        UpdateEntrustStatus(connection, SubNo, "60", httEntrustEntitys.get(0)
                .getSubcontractPlineCode(), "", "", httEntrustEntitys.get(0)
                .getSubcontractOperator(), httEntrustEntitys.get(0)
                .getDrawingno(), httEntrustEntitys.get(0).getSubcontractNote());

        messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                "60", "/",
                "[" + ( "0".equals(httEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + httEntrustEntitys.get(0).getPlineName(),
                ""
                , "", Name);

        // 半成品写出库记录
        if (httEntrustEntitys.get(0).getProcessCode().equals("BC")) {
            String sendOut = FrmMcpLoading.querySendOut(connection, "800808",
                    "");
            String sqlAddBcOutList = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.InsertBcOutList");
            PreparedStatement patAddBcOutList = connection
                    .prepareStatement(sqlAddBcOutList);
            patAddBcOutList.setObject(1, sendOut);
            patAddBcOutList.setObject(2, sendOut);
            patAddBcOutList.setObject(3, Name);
            patAddBcOutList.setObject(4, SubNo);
            patAddBcOutList.addBatch();
            patAddBcOutList.executeBatch();
        } // 半成品写出库记录
        if (httEntrustEntitys.get(0).getProcessCode().equals("ZC")) {
//            String sendOut = FrmMcpLoading.queryZcSendOut(connection, "800813",
//                    "");
//            String sqlAddBcOutList = CoreXmlSqlParsersFactory
//                    .getSql("frmEntrust.InsertZcOutList");
//            PreparedStatement patAddBcOutList = connection
//                    .prepareStatement(sqlAddBcOutList);
//            patAddBcOutList.setObject(1, sendOut);
//            patAddBcOutList.setObject(2, sendOut);
//            patAddBcOutList.setObject(3, Name);
//            patAddBcOutList.setObject(4, SubNo);
//            patAddBcOutList.addBatch();
//            patAddBcOutList.executeBatch();
        }

        for (int i = 0; i < httEntrustEntitys.size(); i++) {

            HttEntrustEntity Entity = httEntrustEntitys.get(i);

            UpdateEntrustNum(Entity.getProcessCode(), connection, Entity
                    .getResultNo());

            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.selectProject");
            sql += " AND  SUBCONTRACT_NO =? AND SUBCONTRACT_NO_SEQ=?";
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setObject(1, Entity.getSubcontractNo());
            psta.setObject(2, Entity.getSubcontractNoSeq());
            ResultSet rs = psta.executeQuery();
            List<HttEntrustProjectEntity> Lists = EntityTool.getEntitysByRs(rs,
                    HttEntrustProjectEntity.class);
            rs.close();
            psta.close();

            for (HttEntrustProjectEntity Project : Lists) {
                if (Project.getProjectCode().startsWith("702203")
                        || Project.getProjectCode().startsWith("702213")) {
                    UpdateCutMat(connection, Entity);
                    break;
                }
            }

        }

        UpdateFailMatStatus(connection, httEntrustEntitys.get(0)
                .getProcessCode(), SubNo, true);
        UpdateMatSubNo(httEntrustEntitys.get(0).getProcessCode(), connection,
                httEntrustEntitys.get(0).getSubcontractNo(), "0");

        // 半成品写入库记录
        if (httEntrustEntitys.get(0).getProcessCode().equals("BC")) {
            String sendOut = FrmMcpLoading.querySendIn(connection, "800706");
            String sqlAddBcOutList = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.InsertBcInList");
            PreparedStatement patAddBcOutList = connection
                    .prepareStatement(sqlAddBcOutList);
            patAddBcOutList.setObject(1, sendOut);
            patAddBcOutList.setObject(2, sendOut);
            patAddBcOutList.setObject(3, Name);
            patAddBcOutList.setObject(4, SubNo);
            patAddBcOutList.addBatch();
            patAddBcOutList.executeBatch();
        } // 成品写入库记录
        if (httEntrustEntitys.get(0).getProcessCode().equals("ZC")) {
//            String sendOut = FrmMcpLoading.queryZcSendIn(connection, "800713");
//            String sqlAddBcOutList = CoreXmlSqlParsersFactory
//                    .getSql("frmEntrust.InsertZcInList");
//            PreparedStatement patAddBcOutList = connection
//                    .prepareStatement(sqlAddBcOutList);
//            patAddBcOutList.setObject(1, sendOut);
//            patAddBcOutList.setObject(2, sendOut);
//            patAddBcOutList.setObject(3, Name);
//            patAddBcOutList.setObject(4, SubNo);
//            patAddBcOutList.addBatch();
//            patAddBcOutList.executeBatch();
        }
    }

    /**
     * 更改分切库存和增加管号队列
     *
     * @param connection
     * @param entity
     */
    private void UpdateCutMat(Connection connection, HttEntrustEntity entity)
            throws Exception {


        if (entity.getProcessCode().equals("D")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            int count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            patDeleteBc.executeUpdate();


            patDeleteYdmButress.setObject(1, entity.getResultNo());
            patDeleteYdmButress.executeUpdate();

        } else if (entity.getProcessCode().equals("G")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutPortMch");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustPortMch");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            patDeletePort.executeUpdate();


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            patDeleteBc.executeUpdate();


            patDeleteYdmButress.setObject(1, entity.getResultNo());
            patDeleteYdmButress.executeUpdate();

        } else if (entity.getProcessCode().equals("F")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutPortHtt");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustPortHtt");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            patDeletePort.executeUpdate();


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            patDeleteBc.executeUpdate();


            patDeleteYdmButress.setObject(1, entity.getResultNo());
            patDeleteYdmButress.executeUpdate();

        } else if (entity.getProcessCode().equals("E")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutPortVrp");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustPortVrp");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            patDeletePort.executeUpdate();


            patAddBc.setObject(1, "00");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            patDeleteBc.executeUpdate();


            patDeleteYdmButress.setObject(1, entity.getResultNo());
            patDeleteYdmButress.executeUpdate();

        } else if (entity.getProcessCode().equals("BC")) {


            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            int count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            patDeleteBc.executeUpdate();


            patDeleteYdmButress.setObject(1, entity.getResultNo());
            patDeleteYdmButress.executeUpdate();

        } else if (entity.getProcessCode().equals("ZC")) {


            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutZcMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);
            
            //新增销售入库
            String sqlAddBcXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchInsertEntrustCutZcMat");
            PreparedStatement patAddBcXs = connection.prepareStatement(sqlAddBcXs);
            
            

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustCutZcBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            //新增销售入库记录
            String sqlAddYdmButressXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchInsertEntrustCutZcBut");
            PreparedStatement patAddYdmButressXs = connection.prepareStatement(sqlAddYdmButressXs);
            
//            String sqlDeleteBc = CoreXmlSqlParsersFactory
//                    .getSql("frmEntrust.BatchDeleteEntrustZcMat");
//            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);
//
//            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
//                    .getSql("frmEntrust.BatchDeleteEntrustZcBut");
//            PreparedStatement patDeleteYdmButress = connection
//                    .prepareStatement(sqlDeleteYdmButress);


            patAddBc.setObject(1, entity.getResultNo());
            patAddBcXs.setObject(1, entity.getResultNo());
            patAddBcXs.executeUpdate();
            int count = patAddBc.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();
            
            patAddYdmButressXs.setObject(1, entity.getResultNo());
            patAddYdmButressXs.executeUpdate();

            if (count != CutData.size()) {
                throw new Exception("库存正在倒运中!");
            }


//            patDeleteBc.setObject(1, entity.getResultNo());
//            patDeleteBc.executeUpdate();


//            patDeleteYdmButress.setObject(1, entity.getResultNo());
//            patDeleteYdmButress.executeUpdate();
        } else if (entity.getProcessCode().equals("H")) {

            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.DeleteMat");
            PreparedStatement patDeleteBc = connection
                    .prepareStatement(sqlDeleteBc);

            patDeleteBc.setObject(1, entity.getSubcontractNo());
            patDeleteBc.setObject(2, entity.getSubcontractNoSeq());
            patDeleteBc.addBatch();

            patDeleteBc.executeBatch();

        }

    }

    /**
     * 标记各工序队列废品
     *
     * @param connection
     * @param Process
     * @param SubNo
     * @param Fail
     * @throws SQLException
     */
    private void UpdateFailMatStatus(Connection connection, String Process,
                                     String SubNo, boolean Fail) throws SQLException {

        if (Process.equals("E")) {
            String sqlUpdatePortE = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMatPortE");
            PreparedStatement patUpdatePortE = connection
                    .prepareStatement(sqlUpdatePortE);

            String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMat");
            PreparedStatement patUpdateFailMat = connection
                    .prepareStatement(sqlUpdateFailMat);

            patUpdatePortE.setObject(1, Fail ? "40" : "20");
            patUpdatePortE.setObject(2, SubNo);
            patUpdatePortE.addBatch();
            patUpdatePortE.executeBatch();

            patUpdateFailMat.setObject(1, Fail ? "22" : "11");
            patUpdateFailMat.setObject(2, Fail ? "22" : "11");
            patUpdateFailMat.setObject(3, SubNo);
            patUpdateFailMat.addBatch();
            patUpdateFailMat.executeBatch();

        } else if (Process.equals("F")) {
            String sqlUpdatePortF = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMatPortF");
            PreparedStatement patUpdatePortF = connection
                    .prepareStatement(sqlUpdatePortF);

            String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMat");
            PreparedStatement patUpdateFailMat = connection
                    .prepareStatement(sqlUpdateFailMat);

            patUpdatePortF.setObject(1, Fail ? "40" : "20");
            patUpdatePortF.setObject(2, SubNo);
            patUpdatePortF.addBatch();
            patUpdatePortF.executeBatch();

            patUpdateFailMat.setObject(1, Fail ? "22" : "11");
            patUpdateFailMat.setObject(2, Fail ? "22" : "11");
            patUpdateFailMat.setObject(3, SubNo);
            patUpdateFailMat.addBatch();
            patUpdateFailMat.executeBatch();

        } else if (Process.equals("G")) {
            String sqlUpdatePortG = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMatPortG");
            PreparedStatement patUpdatePortG = connection
                    .prepareStatement(sqlUpdatePortG);

            String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMat");
            PreparedStatement patUpdateFailMat = connection
                    .prepareStatement(sqlUpdateFailMat);

            patUpdatePortG.setObject(1, Fail ? "40" : "20");
            patUpdatePortG.setObject(2, SubNo);
            patUpdatePortG.addBatch();
            patUpdatePortG.executeBatch();

            patUpdateFailMat.setObject(1, Fail ? "22" : "11");
            patUpdateFailMat.setObject(2, Fail ? "22" : "11");
            patUpdateFailMat.setObject(3, SubNo);
            patUpdateFailMat.addBatch();
            patUpdateFailMat.executeBatch();

        } else if (Process.equals("BC")) {

            String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateFailMat");
            PreparedStatement patUpdateFailMat = connection
                    .prepareStatement(sqlUpdateFailMat);

            patUpdateFailMat.setObject(1, Fail ? "22" : "00");
            patUpdateFailMat.setObject(2, Fail ? "22" : "00");
            patUpdateFailMat.setObject(3, SubNo);
            patUpdateFailMat.addBatch();
            patUpdateFailMat.executeBatch();

        } else if (Process.equals("ZC")) {

            if (Fail) {
                String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.UpdateZcFailMat");
                PreparedStatement patUpdateFailMat = connection
                        .prepareStatement(sqlUpdateFailMat);

                patUpdateFailMat.setObject(1, SubNo);
                patUpdateFailMat.addBatch();
                patUpdateFailMat.executeBatch();
            } else {

                String sqlUpdateFailMat = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.UpdateZcFailMat2");
                PreparedStatement patUpdateFailMat = connection
                        .prepareStatement(sqlUpdateFailMat);
                patUpdateFailMat.setObject(1, SubNo);
                patUpdateFailMat.addBatch();
                patUpdateFailMat.executeBatch();
            }

        }

    }

    /**
     * 撤销委托完成
     *
     * @param SubNos
     * @param Step
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject CancleMarkCompleted(ArrayList<String> SubNos,
                                                String Step, String Note, String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                String Status = HttEntrustEntitys.get(0).getSubcontractTarget()
                        .equals("0") ? "50" : "40";
                String Info = "撤销委托完成";

                UpdateEntrustStatus(connection, SubNo, Status,
                        HttEntrustEntitys.get(0).getSubcontractPlineCode(), "",
                        "", HttEntrustEntitys.get(0).getSubcontractOperator(),
                        HttEntrustEntitys.get(0).getDrawingno(),
                        HttEntrustEntitys.get(0).getSubcontractNote());

                UpdateFailMatStatus(connection, HttEntrustEntitys.get(0)
                        .getProcessCode(), SubNo, false);

                for (int i = 0; i < HttEntrustEntitys.size(); i++) {

                    HttEntrustEntity Entity = HttEntrustEntitys.get(i);

                    String MatNos = GetEntrustMatNo(connection, Entity
                            .getProcessCode(), SubNo);
                    List<OfflineResultEntity> OfflineResultEntity = GetOffLineResultEntity(
                            Entity.getProcessCode(), connection, Entity
                                    .getResultNo(), MatNos);

                    if (OfflineResultEntity == null
                            || OfflineResultEntity.size() <= 0) {
                        throw new Exception("数据已返线,无法撤销");
                    }

                    if (!Entity.getSubcontractNo().equals(SubNo)) {
                        throw new Exception("已经重新申请委托,无法撤销");
                    }

                    if (!Entity.getSubcontractLog().equals("60")) {
                        throw new Exception("委托单未委托完成!");
                    }

                    UpdateEntrustNum(Entity.getProcessCode(), connection,
                            Entity.getResultNo());

                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.selectProject");
                    sql += " AND  SUBCONTRACT_NO =? AND SUBCONTRACT_NO_SEQ=?";
                    PreparedStatement psta = connection.prepareStatement(sql);
                    psta.setObject(1, Entity.getSubcontractNo());
                    psta.setObject(2, Entity.getSubcontractNoSeq());
                    ResultSet rs = psta.executeQuery();
                    List<HttEntrustProjectEntity> Lists = EntityTool
                            .getEntitysByRs(
                                    rs,
                                    com.steering.mes.mcp.entity.HttEntrustProjectEntity.class);
                    rs.close();
                    psta.close();

                    for (HttEntrustProjectEntity Project : Lists) {
                        if (Project.getProjectCode().startsWith("702203")
                                || Project.getProjectCode().startsWith(
                                "70221303")) {
                            CancelCutMat(connection, Entity);
                            break;
                        }
                    }

                }

                UpdateMatSubNo(HttEntrustEntitys.get(0).getProcessCode(),
                        connection,
                        HttEntrustEntitys.get(0).getSubcontractNo(), "1");

                patAddProcess.setObject(1, SubNo);
                patAddProcess.setObject(2, SubNo);
                patAddProcess.setObject(3, Info);
                patAddProcess.setObject(4, Name);
                patAddProcess.setObject(5, Note);
                patAddProcess.setObject(6, HttEntrustEntitys.get(0)
                        .getSubcontractLog());
                patAddProcess.setObject(7, Status);
                patAddProcess.addBatch();

                if (HttEntrustEntitys.get(0).getProcessCode().equals("BC")) {
                    Date now = new Date();
                    SimpleDateFormat dateFormat1 = new SimpleDateFormat(
                            "yyyyMM", Locale.CHINA);
                    String systime1 = dateFormat1.format(now);

                    String OutBalYear = "";
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.SelectBcOutListBalyear");
                    PreparedStatement psta = connection.prepareStatement(sql);
                    psta.setObject(1, SubNo);
                    ResultSet rs = psta.executeQuery();
                    if (rs.next()) {
                        OutBalYear = rs.getString("BAL_YEAR_MONTH");
                    }
                    rs.close();
                    psta.close();

                    if (!OutBalYear.equals(systime1)) {
                        core.setV_errMsg("半成品出库记录已经结转,不能撤销委托!");
                        return core;
                    }

                    String sqlDeleteOutList = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.DeleteBcOutList");
                    PreparedStatement patDeleteOutList = connection
                            .prepareStatement(sqlDeleteOutList);
                    patDeleteOutList.setObject(1, SubNo);
                    patDeleteOutList.addBatch();
                    patDeleteOutList.executeBatch();

                    String sqlDeleteInList = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.DeleteBcInList");
                    PreparedStatement patDeleteInList = connection
                            .prepareStatement(sqlDeleteInList);
                    patDeleteInList.setObject(1, SubNo);
                    patDeleteInList.addBatch();
                    patDeleteInList.executeBatch();
                }

                if (HttEntrustEntitys.get(0).getProcessCode().equals("ZC")) {
                    Date now = new Date();
                    SimpleDateFormat dateFormat1 = new SimpleDateFormat(
                            "yyyyMM", Locale.CHINA);
                    String systime1 = dateFormat1.format(now);

                    String OutBalYear = "";
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.SelectZcOutListBalyear");
                    PreparedStatement psta = connection.prepareStatement(sql);
                    psta.setObject(1, SubNo);
                    ResultSet rs = psta.executeQuery();
                    if (rs.next()) {
                        OutBalYear = rs.getString("BAL_YEAR_MONTH");
                    }
                    rs.close();
                    psta.close();

                    if (!OutBalYear.equals(systime1)) {
                        core.setV_errMsg("成品出库记录已经结转,不能撤销委托!");
                        return core;
                    }

                    String sqlDeleteOutList = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.DeleteZcOutList");
                    PreparedStatement patDeleteOutList = connection
                            .prepareStatement(sqlDeleteOutList);
                    patDeleteOutList.setObject(1, SubNo);
                    patDeleteOutList.addBatch();
                    patDeleteOutList.executeBatch();

                    String sqlDeleteInList = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.DeleteZcInList");
                    PreparedStatement patDeleteInList = connection
                            .prepareStatement(sqlDeleteInList);
                    patDeleteInList.setObject(1, SubNo);
                    patDeleteInList.addBatch();
                    patDeleteInList.executeBatch();

                }


                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        "60", "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "5" : "6",
                        "[" + ( "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntitys.get(0).getPlineName(),
                        ""
                        , "", Name);

            }
            patAddProcess.executeBatch();


            core.setV_errMsg("撤销委托完成！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 更改分切库存和增加管号队列
     *
     * @param connection
     * @param entity
     */
    private void CancelCutMat(Connection connection, HttEntrustEntity entity)
            throws Exception {


        if (entity.getProcessCode().equals("G")) {
            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustPortMch");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutPortMch");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            patAddPort.setObject(2, entity.getResultNo());
            patAddPort.setObject(3, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            count = patDeletePort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("F")) {
            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustPortHtt");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutPortHtt");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            count = patDeletePort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("E")) {
            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustPortVrp");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutPortVrp");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            count = patDeletePort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("D")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            int count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("BC")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddPort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustPortHtt");
            PreparedStatement patAddPort = connection
                    .prepareStatement(sqlAddPort);

            String sqlDeletePort = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutPortHtt");
            PreparedStatement patDeletePort = connection
                    .prepareStatement(sqlDeletePort);

            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);

            patAddPort.setObject(1, entity.getResultNo());
            int count = patAddPort.executeUpdate();
            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("管号队列异常");
            }

            patDeletePort.setObject(1, entity.getResultNo());
            patDeletePort.setObject(2, entity.getResultNo());
            patDeletePort.setObject(3, entity.getResultNo());
            count = patDeletePort.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }


            patAddBc.setObject(1, "00");
            patAddBc.setObject(2, entity.getResultNo());
            count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("E")) {
            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);


            patAddBc.setObject(1, "11");
            patAddBc.setObject(2, entity.getResultNo());
            int count = patAddBc.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }


            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("ZC")) {

            List<HttEntrustMatNoEntity> CutData = GetHttEntrustCutDetailEntity(
                    connection, entity.getResultNo());
            if (CutData.size() <= 1)
                return;


            String sqlAddBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustZcMat");
            PreparedStatement patAddBc = connection.prepareStatement(sqlAddBc);

            //新增销售库存
            String sqlAddBcXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchInsertEntrustZcMat");
            PreparedStatement patAddBcXs = connection.prepareStatement(sqlAddBcXs);
            
            
            String sqlAddYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchInsertEntrustZcBut");
            PreparedStatement patAddYdmButress = connection.prepareStatement(sqlAddYdmButress);
            
            //新增销售库存记录
            String sqlAddYdmButressXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchInsertEntrustZcBut");
            PreparedStatement patAddYdmButressXs = connection.prepareStatement(sqlAddYdmButressXs);


            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutZcMat");
            PreparedStatement patDeleteBc = connection.prepareStatement(sqlDeleteBc);

            //删除销售库存
            String sqlDeleteBcXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchDeleteEntrustCutZcMat");
            PreparedStatement patDeleteBcXs = connection.prepareStatement(sqlDeleteBcXs);
            
            
            String sqlDeleteYdmButress = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.BatchDeleteEntrustCutZcBut");
            PreparedStatement patDeleteYdmButress = connection
                    .prepareStatement(sqlDeleteYdmButress);
            
            //删除销售库存记录
            String sqlDeleteYdmButressXs = CoreXmlSqlParsersFactory
                    .getSql("xsmat.BatchDeleteEntrustCutZcBut");
            PreparedStatement patDeleteYdmButressXs = connection
                    .prepareStatement(sqlDeleteYdmButressXs);
            

            patAddBc.setObject(1, entity.getResultNo());
            int count = patAddBc.executeUpdate();
            
            patAddBcXs.setObject(1, entity.getResultNo());
            patAddBcXs.executeUpdate();
            
            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存异常");
            }

            patAddYdmButress.setObject(1, entity.getResultNo());
            count = patAddYdmButress.executeUpdate();
            
            patAddYdmButressXs.setObject(1, entity.getResultNo());
            patAddYdmButressXs.executeUpdate();

            if (count != Integer.parseInt(entity.getSubcontractNum())) {
                throw new Exception("库存正在倒运中!");
            }


            patDeleteBc.setObject(1, entity.getResultNo());
            count = patDeleteBc.executeUpdate();
            
            patDeleteBcXs.setObject(1, entity.getResultNo());
            patDeleteBcXs.executeUpdate();
            
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

            patDeleteYdmButress.setObject(1, entity.getResultNo());
            count = patDeleteYdmButress.executeUpdate();
            
            patDeleteYdmButressXs.setObject(1, entity.getResultNo());
            patDeleteYdmButressXs.executeUpdate();
            if (count != CutData.size()) {
                throw new Exception("管号队列异常");
            }

        } else if (entity.getProcessCode().equals("H")) {

            String sqlDeleteBc = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.revertMat");
            PreparedStatement patDeleteBc = connection
                    .prepareStatement(sqlDeleteBc);

            patDeleteBc.setObject(1, entity.getSubcontractNo());
            patDeleteBc.setObject(2, entity.getSubcontractNoSeq());
            patDeleteBc.addBatch();

            patDeleteBc.executeBatch();
            patDeleteBc.executeBatch();

        }

    }

    /**
     * 撤销审批
     *
     * @param SubNos
     * @param Step
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject CancelApproval(ArrayList<String> SubNos,
                                           String Step, String Note, String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        //Statement wlStmt = null;
        //Connection wlCon = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
          //TZH 24.4.24 注销物流接口
            /*wlCon = new DBCommon().getDao("TmsDao").getConnection();
            wlCon.setAutoCommit(false);
            wlStmt = wlCon.createStatement();*/
            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);

            for (String SubNo : SubNos) {

                if (SubNo.equals("")) {
                    throw new Exception("未申请委外,请确认!");
                }

                List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                        connection, SubNo);
                if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                String MatNos = GetEntrustMatNo(connection, HttEntrustEntitys
                        .get(0).getProcessCode(), SubNo);

                List<OfflineResultEntity> OfflineResultEntity = GetOffLineResultEntity(
                        HttEntrustEntitys.get(0).getProcessCode(), connection,
                        HttEntrustEntitys.get(0).getResultNo(), MatNos);

                if (OfflineResultEntity == null
                        || OfflineResultEntity.size() <= 0) {
                    throw new Exception("数据已返线,无法撤销审核");
                }

                if (!OfflineResultEntity.get(0).getSubcontractNo()
                        .equals(SubNo)) {
                    throw new Exception("已经重新申请委托,无法撤销旧的委托申请");
                }

                if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                        || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                        "null")
                        || HttEntrustEntitys.get(0).getSubcontractType()
                        .equals("00")) {
                    throw new Exception("未审核,请确认!");
                }

                String Info = "";
                String Status = "";
                String NextNo = "";

                if (Step.equals("1")) {
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "10")
                            && !HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("20")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }
                    Info = "撤销科室审核";
                    Status = "00";

                    String sqlDelete2 = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.deleteProcessAuto");//
                    PreparedStatement patDelete2 = connection
                            .prepareStatement(sqlDelete2);
                    patDelete2.setObject(1, SubNo);
                    patDelete2.addBatch();
                    patDelete2.executeBatch();


                } else if (Step.equals("2")) {
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "22")
                            && !HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("23")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }
                    Info = "撤销探伤审核";
                    Status = "26";


                } else if (Step.equals("3")) {
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "24")
                            && !HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("25")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }

                    Info = "撤销管理部门审核";
                    Status = HttEntrustEntitys.get(0).getSubcontractType()
                            .equals("1") ? "22" : "26";

                    String sqlDelete2 = CoreXmlSqlParsersFactory
                            .getSql("frmEntrust.deleteProcessAuto");//
                    PreparedStatement patDelete2 = connection
                            .prepareStatement(sqlDelete2);
                    patDelete2.setObject(1, SubNo);
                    patDelete2.addBatch();
                    patDelete2.executeBatch();


                } else if (Step.equals("4")) {
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "50")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }
                    Info = "撤销回报审核";
                    Status = "40";
                } else if(Step.equals("7")){
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "26")
                            && !HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("27")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }
                    Info = "撤销主管审核";
                    Status = "10";
                } else if(Step.equals("8")){
                    if (!HttEntrustEntitys.get(0).getSubcontractLog().equals(
                            "28")) {
                        throw new Exception("不是已审核状态,无法撤销审核!");
                    }
                    Info = "撤销生产计划部审核";
                    Status = "26";
                }

                for (int i = 0; i < HttEntrustEntitys.size(); i++) {
                    HttEntrustEntity entity = HttEntrustEntitys.get(i);
                    if (!entity.getNewBatchNo().equals("")
                            && HttEntrustEntitys.get(0).getSubcontractLog()
                            .equals("20"))
                        UpdatePortBatchNo(connection, entity.getHeatPlanNo(),
                                entity.getResultNo(), entity.getJudgeStoveNo(),
                                entity.getBatchNo(), entity.getNewBatchNo(),
                                entity.getProcessCode(), entity
                                        .getSubcontractNum());
                    // 修改用车方式
                    UpdateEntrustTransCode(connection, "0", SubNo, entity
                            .getSubcontractNoSeq());
                }

                UpdateEntrustStatus(connection, SubNo, Status,
                        Step.equals("4") ? HttEntrustEntitys.get(0)
                                .getSubcontractPlineCode() : "", "", "",
                        HttEntrustEntitys.get(0).getSubcontractOperator(),
                        HttEntrustEntitys.get(0).getDrawingno(),
                        HttEntrustEntitys.get(0).getSubcontractNote());

              //TZH 24.4.24 注销物流接口
                // 删除物流表数据
                //String sqlDelete = CoreXmlSqlParsersFactory
                //        .getSql("frmEntrust.deleteWlInfo");//
                //PreparedStatement patDelete = wlCon.prepareStatement(sqlDelete);
               // patDelete.setObject(1, SubNo);
               // patDelete.addBatch();
               // patDelete.executeBatch();

                if (Step.equals("1"))
                    UpdateEntrustNum(HttEntrustEntitys.get(0).getProcessCode(),
                            connection, HttEntrustEntitys.get(0).getResultNo());

                patAddProcess.setObject(1, SubNo);
                patAddProcess.setObject(2, SubNo);
                patAddProcess.setObject(3, Info);
                patAddProcess.setObject(4, Name);
                patAddProcess.setObject(5, Note);
                patAddProcess.setObject(6, HttEntrustEntitys.get(0)
                        .getSubcontractLog());
                patAddProcess.setObject(7, Status);
                patAddProcess.addBatch();


                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        Status, Step,
                        "[" + ( "0".equals(HttEntrustEntitys.get(0).getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntitys.get(0).getPlineName(),
                        ""
                        , "", Name);
            }

            patAddProcess.executeBatch();

            core.setV_errMsg("撤销审核成功！");
            core.setResult(1);
            connection.commit();
          //TZH 24.4.24 注销物流接口
            //wlCon.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                  //TZH 24.4.24 注销物流接口
                  //  wlCon.rollback();
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
              //TZH 24.4.24 注销物流接口
               // if (wlCon != null && !wlCon.isClosed()) {
               //     wlCon.close();
               // }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 增加探伤实绩
     *
     * @param SubNo
     * @param SubNoSeq
     * @param loadStr
     * @param ScrappedList
     * @param SuspiciousList
     * @param UnpassList
     * @param CrackParaStr
     * @param ProbeString
     * @param StandString
     * @return
     */
    public CoreReturnObject DoAddCrack(String SubNo, String SubNoSeq,
                                       String loadStr, ArrayList<String> ScrappedList,
                                       ArrayList<String> SuspiciousList, ArrayList<String> UnpassList,
                                       String CrackParaStr, ArrayList<String> ProbeString,
                                       ArrayList<String> StandString) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            String sqlupdatepln = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus2");// 修改委托表状态
            PreparedStatement patupdatepln = connection
                    .prepareStatement(sqlupdatepln);

            HttCrackDetectionEtEntity Load = EntityTool.getEntityByJSONStr(
                    loadStr, HttCrackDetectionEtEntity.class);
            HttCrackDetectionParaEntity Para = EntityTool.getEntityByJSONStr(
                    CrackParaStr, HttCrackDetectionParaEntity.class);

            Load.setJudgeStoveNo(Load.getJudgeStoveNo().split("-")[0]);

            Load.setColUser(Para.getOperatorName());
            Para.setColGroup(Load.getColGroup());
            Para.setShift(Load.getColShift());

            if (Load.getTestingType().equals("")) {
                core.setV_errMsg("探伤种类不能为空！");
                return core;
            }

            if (Load.getTestingGrade().equals("")
                    && !Load.getTestingType().equals("MT")) {
                core.setV_errMsg("探伤等级不能为空！");
                return core;
            }

            HttEntrustEntity HttEntrustEntitys = GetHttEntrustEntity(
                    connection, SubNo, SubNoSeq);
            if (HttEntrustEntitys == null) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("")
                    || HttEntrustEntitys.getSubcontractLog().equals("null")) {
                throw new Exception("未申请委外,请确认!");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("40")
                    && HttEntrustEntitys.getSubcontractLog().equals("50")
                    && HttEntrustEntitys.getSubcontractLog().equals("60")) {
                throw new Exception("已回报完毕,无法新增数据!");
            }

            if (HttEntrustEntitys.getSubcontractTarget().equals("0")) {

                if (!HttEntrustEntitys.getSubcontractLog().equals("24")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法新增数据!");
                }
            } else {
                if (!HttEntrustEntitys.getSubcontractLog().equals("10")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法新增数据!");
                }
            }

            int SubNum = 0;
            int count = 0;
            int detCount = 0;

            if (StringTool.isInteger(Load.getEwasteNum())) {
                detCount += Integer.parseInt(Load.getEwasteNum());
            }
            if (StringTool.isInteger(Load.getEwasteNumEt())) {
                detCount += Integer.parseInt(Load.getEwasteNumEt());
            }
            if (StringTool.isInteger(Load.getRejectNum())) {
                detCount += Integer.parseInt(Load.getRejectNum());
            }
            if (StringTool.isInteger(Load.getTestingNum())) {
                count = Integer.parseInt(Load.getTestingNum());
            }

            if (StringTool.isInteger(HttEntrustEntitys.getSubcontractNum())) {
                SubNum = Integer
                        .parseInt(HttEntrustEntitys.getSubcontractNum());
            }

            if (SubNum == count) {
                Load.setTestingWt(HttEntrustEntitys.getSubcontractWt());
            }

            if (count <= 0) {
                core.setV_errMsg("请输入正确的探伤支数！");
                return core;
            }

            if (count < detCount) {
                core.setV_errMsg("废品支数不能大于探伤支数！");
                return core;
            }

            String resultNo = "";
            Date dt = new Date();
            String sqlloading = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryMaxResultNo");// 查询最大实绩编号
            psta = connection.prepareStatement(sqlloading);
            psta.setObject(1, Load.getPlineCode() + "W" + matter1.format(dt));
            psta.setObject(2, Load.getPlineCode() + "W" + matter1.format(dt));

            ResultSet rs1 = psta.executeQuery();
            if (rs1.next()) {
                resultNo = rs1.getString("RESULT_NO");
            }
            rs1.close();
            psta.close();

            String sqlAdd = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.AddCrackDetection");// 新增探伤
            Load.setZyBatchId(HttEntrustEntitys.getLotNo());
            Load.setProPlanId(HttEntrustEntitys.getProPlanId());
            Load.setGxPlanNo(HttEntrustEntitys.getGxPlanNo());
            Load.setResultNo(resultNo);
            sqlAdd = com.steering.common.EntityTool.fillSqlByEntity(sqlAdd,
                    Load);
            PreparedStatement patAdd = connection.prepareStatement(sqlAdd);
            patAdd.addBatch();

            String ProbeID = "";
            if (ProbeString.size() > 0) {
                String sql = CoreXmlSqlParsersFactory
                        .getSql("FrmHttCrackDetectResult.getMaxProbeId");
                psta = connection.prepareStatement(sql);
                psta.setObject(1, Load.getJudgeStoveNo() + Load.getBatchNo());
                psta.setObject(2, Load.getJudgeStoveNo() + Load.getBatchNo());

                rs1 = psta.executeQuery();
                if (rs1.next()) {
                    ProbeID = rs1.getString("PROBE_ID");
                }
                rs1.close();
                psta.close();

            }

            String StandID = "";

            if (StandString.size() > 0) {
                String sql = CoreXmlSqlParsersFactory
                        .getSql("FrmHttCrackDetectResult.getMaxProbeId");
                sql = CoreXmlSqlParsersFactory
                        .getSql("FrmHttCrackDetectResult.getMaxStandID");
                psta = connection.prepareStatement(sql);
                psta.setObject(1, Load.getJudgeStoveNo() + Load.getBatchNo());
                psta.setObject(2, Load.getJudgeStoveNo() + Load.getBatchNo());

                rs1 = psta.executeQuery();
                if (rs1.next()) {
                    StandID = rs1.getString("STANDARD_ID");
                }
                rs1.close();
                psta.close();

            }

            String sqlAddPara = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.AddCrackDetectionPara");
            Para.setResultNo(resultNo);
            Para.setReportNo(Load.getReportNo());
            Para.setProbeId(ProbeID);
            Para.setStandardId(StandID);
            Para.setHeatPlanNo(Load.getHeatPlanNo());
            Para.setBatchNo(Load.getBatchNo());
            Para.setJudgeStoveNo(Load.getJudgeStoveNo());
            Para.setShift(Load.getColShift());
            Para.setProDate(Load.getColTime());
            Para.setColGroup(Load.getColGroup());
            sqlAddPara = com.steering.common.EntityTool.fillSqlByEntity(
                    sqlAddPara, Para);
            PreparedStatement patAddPara = connection
                    .prepareStatement(sqlAddPara);
            patAddPara.addBatch();
            patAddPara.executeBatch();

            for (int i = 0; i < ProbeString.size(); i++) {
                HttCrackDetectionProbeEntity probeEntity = EntityTool
                        .getEntityByJSONStr(ProbeString.get(i),
                                HttCrackDetectionProbeEntity.class);

                String sqlAddProbe = CoreXmlSqlParsersFactory
                        .getSql("FrmHttCrackDetectResult.AddCrackDetectionProbe");
                probeEntity.setProbeId(ProbeID);
                probeEntity.setProbeSeq(( i + 1 ) + "");
                sqlAddProbe = com.steering.common.EntityTool.fillSqlByEntity(
                        sqlAddProbe, probeEntity);
                PreparedStatement patAddProbe = connection
                        .prepareStatement(sqlAddProbe);
                patAddProbe.addBatch();
                patAddProbe.executeBatch();
            }

            for (int i = 0; i < StandString.size(); i++) {
                HttCrackDetectionStandardEntity probeEntity = EntityTool
                        .getEntityByJSONStr(StandString.get(i),
                                HttCrackDetectionStandardEntity.class);

                String sqlAddStand = CoreXmlSqlParsersFactory
                        .getSql("FrmHttCrackDetectResult.AddCrackDetectionStandard");
                probeEntity.setStandardId(StandID);
                probeEntity.setStandardSeq(( i + 1 ) + "");
                sqlAddStand = com.steering.common.EntityTool.fillSqlByEntity(
                        sqlAddStand, probeEntity);
                PreparedStatement patAddStand = connection
                        .prepareStatement(sqlAddStand);
                patAddStand.addBatch();
                patAddStand.executeBatch();
            }

            patupdatepln.setObject(1, SubNo);
            patupdatepln.setObject(2, SubNoSeq);
            patupdatepln.addBatch();

            String sqlAddHead = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.AddCrackHead2");// 新增探伤
            PreparedStatement patAddHead = connection
                    .prepareStatement(sqlAddHead);
            patAddHead.setObject(1, resultNo);
            patAddHead.setObject(2, Load.getJudgeStoveNo());
            patAddHead.setObject(3, Load.getBatchNo());
            patAddHead.setObject(4, SubNo);
            patAddHead.setObject(5, SubNoSeq);
            patAddHead.addBatch();

            patAddHead.executeBatch();
            patAdd.executeBatch();

            String sqlAddEnResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddResultNo");// 新增探伤
            PreparedStatement patAddEnResult = connection
                    .prepareStatement(sqlAddEnResult);
            patAddEnResult.setObject(1, SubNo);
            patAddEnResult.setObject(2, SubNoSeq);
            patAddEnResult.setObject(3, Load.getResultNo());
            patAddEnResult.addBatch();
            patAddEnResult.executeBatch();

            patupdatepln.executeBatch();

            FrmMchBugD.AddMchWaste(connection, Load.getHeatPlanNo(), resultNo,
                    Load.getPlineCode(), Load.getColUser(), "w",
                    SuspiciousList, ScrappedList, UnpassList, false,
                    HttEntrustEntitys.getProcessCode().endsWith("BC")
                            || HttEntrustEntitys.getProcessCode()
                            .endsWith("ZC") ? "2" : "1");

            if (HttEntrustEntitys.getProcessCode().equals("F")) {
                String addPlnInfo = CoreXmlSqlParsersFactory
                        .getSql("HttLoadingService.AddComInfoResult");// 新增公共信息
                PreparedStatement patsPlan = connection
                        .prepareStatement(addPlnInfo);

                PlnZyRclMEntity pln = PlanService.getSendHttPlanCInfo(
                        connection, HttEntrustEntitys.getHeatPlanNo());

                // 新增探伤公共信息
                patsPlan.setObject(1, resultNo);
                patsPlan.setObject(2, Load.getZyBatchId());
                // patsPlan.setObject(3, pln.getProdIndex());
                patsPlan.setObject(3, Load.getProPlanId());
                patsPlan.setObject(4, Load.getGxPlanNo());
                patsPlan.setObject(5, "");
                patsPlan.setObject(6, "");
                patsPlan.setObject(7, "");
                patsPlan.setObject(8, "");
                patsPlan.setObject(9, pln.getPlineCode());
                patsPlan.setObject(10, pln.getPlineName());
                patsPlan.setObject(11, "600209");
                patsPlan.setObject(12, "探伤");
                patsPlan.setObject(13, pln.getGradecode());
                patsPlan.setObject(14, pln.getGradename());
                patsPlan.setObject(15, pln.getSteelcode());
                patsPlan.setObject(16, pln.getSteelname());
                patsPlan.setObject(17, pln.getOutdiameterIn());
                patsPlan.setObject(18, pln.getWallthickIn());
                patsPlan.setObject(19, "");
                patsPlan.setObject(20, "");
                patsPlan.setObject(21, "");
                patsPlan.setObject(22, "");
                patsPlan.setObject(23, "");
                patsPlan.setObject(24, "");
                patsPlan.setObject(25, "");
                patsPlan.setObject(26, "");
                patsPlan.setObject(27, pln.getOutwlId());
                patsPlan.setObject(28, pln.getOutwlDesc());
                patsPlan.setObject(29, pln.getInwlId());
                patsPlan.setObject(30, pln.getInwlDesc());
                patsPlan.setObject(31, pln.getMonitorPoint());
                patsPlan.setObject(32, "");
                patsPlan.setObject(33, pln.getPrdcrNo());
                patsPlan.setObject(34, "");
                patsPlan.setObject(35, "");
                patsPlan.setObject(36, pln.getStationRoad());
                patsPlan.setObject(37, pln.getCraftFileNo());
                patsPlan.setObject(38, pln.getCraftFileMan());
                patsPlan.setObject(39, pln.getCraftSeq());
                patsPlan.setObject(40, Load.getTestingNum());
                patsPlan.setObject(41, Load.getTestingWt());
                patsPlan.setObject(42, Load.getEwasteNum());
                patsPlan.setObject(43, resultNo);
                patsPlan.setObject(44, "");
                patsPlan.setObject(45, "");
                patsPlan.setObject(46, "");
                patsPlan.setObject(47, "");
                patsPlan.setObject(48, "1");
                patsPlan.setObject(49, Load.getColTime());
                patsPlan.setObject(50, "");
                patsPlan.setObject(51, Load.getColUser());
                patsPlan.setObject(52, Load.getColShift());
                patsPlan.setObject(53, Load.getColGroup());
                patsPlan.setObject(54, "1");
                patsPlan.setObject(55, systime);
                patsPlan.setObject(56, "");
                patsPlan.setObject(57, Load.getHeatPlanNo());
                patsPlan.setObject(58, pln.getJudgeStoveNo());
                patsPlan.setObject(59, pln.getBatchNo());
                patsPlan.setObject(60, "");
                patsPlan.setObject(61, pln.getProduccode());
                patsPlan.setObject(62, pln.getProducname());
                patsPlan.setObject(63, pln.getSpecCode());
                patsPlan.setObject(64, pln.getSpecName());
                patsPlan.setObject(65, Load.getProcessSeq());
                patsPlan.addBatch();
                patsPlan.executeBatch();
            }
            
            ResultSet rs = null;
            int feipingNum = 0;
            String sql = CoreXmlSqlParsersFactory
					.getSql("frmEntrust.queryFpNum");
			psta = connection.prepareStatement(sql);
			psta.setObject(1, SubNo);
			psta.setObject(2, SubNoSeq);
			rs = psta.executeQuery();
			if (rs.next()) {
				feipingNum = Integer.parseInt(rs.getString("ACOUNT")) ;
			}
			rs.close();
			psta.close();
			if(feipingNum > 0 )
			{
				core.setV_errMsg("成品委托不能废！");
				return core;
			}

            core.setV_errMsg("新增成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 增加其他实绩
     *
     * @param SubNo
     * @param SubNoSeq
     * @param loadStr
     * @param ScrappedList
     * @param CutDetail
     * @return
     */
    public CoreReturnObject DoAdd(String SubNo, String SubNoSeq,
                                  String loadStr, ArrayList<String> ScrappedList,
                                  ArrayList<String> CutDetail) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            String sqlupdatepln = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus2");// 修改委托表状态
            PreparedStatement patupdatepln = connection
                    .prepareStatement(sqlupdatepln);

            HttEntrustResultEntity Load = EntityTool.getEntityByJSONStr(
                    loadStr, HttEntrustResultEntity.class);

            HttEntrustEntity HttEntrustEntitys = GetHttEntrustEntity(
                    connection, SubNo, SubNoSeq);
            if (HttEntrustEntitys == null) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("")
                    || HttEntrustEntitys.getSubcontractLog().equals("null")) {
                throw new Exception("未申请委外,请确认!");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("40")
                    || HttEntrustEntitys.getSubcontractLog().equals("50")
                    || HttEntrustEntitys.getSubcontractLog().equals("60")) {
                throw new Exception("已回报完毕,无法新增数据!");
            }

            if (HttEntrustEntitys.getSubcontractTarget().equals("0")) {

                if (!HttEntrustEntitys.getSubcontractLog().equals("24")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法新增数据!");
                }
            } else {
                if (!HttEntrustEntitys.getSubcontractLog().equals("10")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法新增数据!");
                }
            }

            int SubNum = 0;

            int count = 0;
            int detCount = 0;
            int CutNum = 0;

            if (StringTool.isInteger(Load.getFailNum())) {
                detCount += Integer.parseInt(Load.getFailNum());
            }

            if (StringTool.isInteger(Load.getProNum())) {
                count = Integer.parseInt(Load.getProNum());
            }

            if (StringTool.isInteger(HttEntrustEntitys.getSubcontractNum())) {
                SubNum = Integer
                        .parseInt(HttEntrustEntitys.getSubcontractNum());
            }

            if (SubNum == count) {
                Load.setProWt(HttEntrustEntitys.getSubcontractWt());
            }

            if (StringTool.isInteger(Load.getOutnumCut())) {
                CutNum = Integer.parseInt(Load.getOutnumCut());
            }

            if (count <= 0) {
                core.setV_errMsg("请输入正确的作业支数！");
                return core;
            }

            if (count * CutNum < detCount) {
                core.setV_errMsg("废品支数不能大于作业支数！");
                return core;
            }

            String resultNo = "";
            Date dt = new Date();
            String sqlloading = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryMaxResultNo");// 查询最大实绩编号
            psta = connection.prepareStatement(sqlloading);
            psta.setObject(1, Load.getPlineCode() + "W" + matter1.format(dt));
            psta.setObject(2, Load.getPlineCode() + "W" + matter1.format(dt));

            ResultSet rs1 = psta.executeQuery();
            if (rs1.next()) {
                resultNo = rs1.getString("RESULT_NO");
            }
            rs1.close();
            psta.close();

            Load.setResultNo(resultNo);

            String sqlAddEnResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddNewResultNo");// 新增
            sqlAddEnResult = com.steering.common.EntityTool.fillSqlByEntity(
                    sqlAddEnResult, Load);
            PreparedStatement patAddEnResult = connection
                    .prepareStatement(sqlAddEnResult);
            patAddEnResult.addBatch();
            patAddEnResult.executeBatch();

            patupdatepln.executeBatch();

            if (Load.getProjectCode().equals("702206")) {
                String sqlAddWaterData = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.AddHyResultNo");// 新增
                PreparedStatement patAddWaterData = connection
                        .prepareStatement(sqlAddWaterData);
                patAddWaterData.setObject(1, Load.getResultNo());
                patAddWaterData.addBatch();
                patAddWaterData.executeBatch();

            }

            FrmMchBugD.AddMchWaste(connection, Load.getHeatPlanNo(), resultNo,
                    Load.getPlineCode(), Load.getProUser(), "w",
                    new ArrayList<String>(), ScrappedList,
                    new ArrayList<String>(), false, HttEntrustEntitys
                            .getProcessCode().endsWith("BC")
                            || HttEntrustEntitys.getProcessCode()
                            .endsWith("ZC") ? "2" : "1");

            patupdatepln.setObject(1, SubNo);
            patupdatepln.setObject(2, SubNoSeq);
            patupdatepln.addBatch();
            patupdatepln.executeBatch();

            String sqlAddCutDetail = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddCutDetail");// 新增
            PreparedStatement patAddCutDetail = connection
                    .prepareStatement(sqlAddCutDetail);

            for (int i = 0; i < CutDetail.size(); i++) {

                HttEntrustMatNoEntity Cutentity = EntityTool
                        .getEntityByJSONStr(CutDetail.get(i),
                                HttEntrustMatNoEntity.class);
                patAddCutDetail.setObject(1, resultNo);
                patAddCutDetail.setObject(2, HttEntrustEntitys.getResultNo());
                patAddCutDetail.setObject(3, Cutentity.getMatNo());
                patAddCutDetail.setObject(4, Cutentity.getMatNoCut());
                patAddCutDetail.setObject(5, Cutentity.getMatStatus());
                patAddCutDetail.setObject(6, Cutentity.getCutNum());
                patAddCutDetail.setObject(7, HttEntrustEntitys
                        .getSubcontractNo());
                patAddCutDetail.setObject(8, HttEntrustEntitys
                        .getSubcontractNoSeq());
                patAddCutDetail.addBatch();

            }

            patAddCutDetail.executeBatch();

            String sqlUpdateEntrust = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus5");
            PreparedStatement patUpdateEntrust = connection
                    .prepareStatement(sqlUpdateEntrust);
            patUpdateEntrust.setObject(1, SubNo);
            patUpdateEntrust.setObject(2, SubNoSeq);
            patUpdateEntrust.addBatch();
            patUpdateEntrust.executeBatch();
            
            ResultSet rs = null;
            int feipingNum = 0;
            String sql = CoreXmlSqlParsersFactory
					.getSql("frmEntrust.queryFpNum");
			psta = connection.prepareStatement(sql);
			psta.setObject(1, SubNo);
			psta.setObject(2, SubNoSeq);
			rs = psta.executeQuery();
			if (rs.next()) {
				feipingNum = Integer.parseInt(rs.getString("ACOUNT")) ;
			}
			rs.close();
			psta.close();
			if(feipingNum > 0 )
			{
				core.setV_errMsg("成品委托不能废！");
				return core;
			}

            core.setV_errMsg("新增成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 删除实绩
     *
     * @param ResultNo
     * @return
     */
    public CoreReturnObject DoDelete(String ResultNo) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            String sqlDelete = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResult");// 删除上探伤实绩
            PreparedStatement patDelete = connection
                    .prepareStatement(sqlDelete);
            String sqlDeletePara = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResultPara");// 删除上探伤参数
            PreparedStatement patDeletepara = connection
                    .prepareStatement(sqlDeletePara);

            String sqlDeleteProbe = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResultProbe");// 删除上探伤探头
            PreparedStatement patDeleteProbe = connection
                    .prepareStatement(sqlDeleteProbe);

            String sqlDeleteStandard = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResultStandard");// 删除上探伤标准
            PreparedStatement patDeleteStandard = connection
                    .prepareStatement(sqlDeleteStandard);

            String sqlDeleteHead = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResultHead");// 删除上探伤实绩
            PreparedStatement patDeleteHead = connection
                    .prepareStatement(sqlDeleteHead);

            String sqlDeleteComInfo = CoreXmlSqlParsersFactory
                    .getSql("FrmHttCrackDetectResult.deleteHttCrackResultComInfo");// 删除上探伤实绩
            PreparedStatement patDeleteComInfo = connection
                    .prepareStatement(sqlDeleteComInfo);

            String sqlDeleteResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.DeleteResultNo");// 删除上探伤实绩
            PreparedStatement patDeleteResultd = connection
                    .prepareStatement(sqlDeleteResult);

            String sqlDeleteCutResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.DeleteCutDetail");// 删除上探伤实绩
            PreparedStatement patDeleteCutResultd = connection
                    .prepareStatement(sqlDeleteCutResult);

            String sqlDeleteHyResultNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.DeleteHyResultNo");// 删除上探伤实绩
            PreparedStatement patDeleteHyResultNo = connection
                    .prepareStatement(sqlDeleteHyResultNo);

            HttEntrustResultEntity HttEntrustResultEntity = GetHttEntrustResultEntity(
                    connection, ResultNo);
            if (HttEntrustResultEntity == null) {
                throw new Exception("数据异常, 找不到实绩数据，请刷新数据");
            }

            HttEntrustEntity HttEntrustEntitys = GetHttEntrustEntity(
                    connection, HttEntrustResultEntity.getSubcontractNo(),
                    HttEntrustResultEntity.getSubcontractNoSeq());
            if (HttEntrustEntitys == null) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("")
                    || HttEntrustEntitys.getSubcontractLog().equals("null")) {
                throw new Exception("未申请委外,请确认!");
            }

            if (HttEntrustEntitys.getSubcontractTarget().equals("0")) {

                if (!HttEntrustEntitys.getSubcontractLog().equals("24")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法删除数据!");
                }
            } else {
                if (!HttEntrustEntitys.getSubcontractLog().equals("10")
                        && !HttEntrustEntitys.getSubcontractLog().equals("30")
                        && !HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("已撤销审核,无法删除数据!");
                }
            }

            int detCount = 0;

            if (StringTool.isInteger(HttEntrustResultEntity.getFailNum())) {
                detCount += Integer.parseInt(HttEntrustResultEntity
                        .getFailNum());
            }

            String sqlupdatepln = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus2");
            PreparedStatement patupdatepln = connection
                    .prepareStatement(sqlupdatepln);

            patDelete.setObject(1, ResultNo);
            patDelete.addBatch();
            patDelete.executeBatch();

            patDeleteHead.setObject(1, ResultNo);
            patDeleteHead.addBatch();
            patDeleteHead.executeBatch();

            patDeleteProbe.setObject(1, ResultNo);
            patDeleteProbe.addBatch();
            patDeleteProbe.executeBatch();

            patDeleteStandard.setObject(1, ResultNo);
            patDeleteStandard.addBatch();
            patDeleteStandard.executeBatch();

            patDeletepara.setObject(1, ResultNo);
            patDeletepara.addBatch();
            patDeletepara.executeBatch();

            patDeleteResultd.setObject(1, ResultNo);
            patDeleteResultd.addBatch();
            patDeleteResultd.executeBatch();

            patDeleteCutResultd.setObject(1, ResultNo);
            patDeleteCutResultd.addBatch();
            patDeleteCutResultd.executeBatch();

            patDeleteComInfo.setObject(1, ResultNo);
            patDeleteComInfo.addBatch();
            patDeleteComInfo.executeBatch();

            patDeleteHyResultNo.setObject(1, ResultNo);
            patDeleteHyResultNo.addBatch();
            patDeleteHyResultNo.executeBatch();

            patupdatepln
                    .setObject(1, HttEntrustResultEntity.getSubcontractNo());
            patupdatepln.setObject(2, HttEntrustResultEntity
                    .getSubcontractNoSeq());
            patupdatepln.addBatch();

            patupdatepln.executeBatch();

            FrmMchBugD.DeleteMchWaste(connection, "", ResultNo, "", "w",
                    detCount, HttEntrustEntitys.getProcessCode().endsWith("BC")
                            || HttEntrustEntitys.getProcessCode()
                            .endsWith("ZC") ? "2" : "1");

            String sqlUpdateEntrust = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus5");
            PreparedStatement patUpdateEntrust = connection
                    .prepareStatement(sqlUpdateEntrust);
            patUpdateEntrust.setObject(1, HttEntrustResultEntity
                    .getSubcontractNo());
            patUpdateEntrust.setObject(2, HttEntrustResultEntity
                    .getSubcontractNoSeq());
            patUpdateEntrust.addBatch();
            patUpdateEntrust.executeBatch();

            core.setV_errMsg("删除成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 回报完毕
     *
     * @param SubNo
     * @param SubSeq
     * @param Name
     * @return
     */
    public CoreReturnObject DoReplay(String SubNo, String SubSeq, String Name) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            HttEntrustEntity HttEntrustEntity = GetHttEntrustEntity(connection,
                    SubNo, SubSeq);
            if (HttEntrustEntity == null) {
                throw new Exception("委外单不存在!!");
            }
            if (HttEntrustEntity.getSubcontractLog().equals("40")
                    || HttEntrustEntity.getSubcontractLog().equals("50")
                    || HttEntrustEntity.getSubcontractLog().equals("60")) {
                throw new Exception("委外单已经回报完毕!");
            }

			/*
			 * if(!HttEntrustEntity.getSubcontractLog().equals("30")){ throw new
			 * Exception("委外单未回报,请先新增委外实绩!"); }
			 */

            String sqlUpdateEntrust = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus3");
            PreparedStatement patUpdateEntrust = connection
                    .prepareStatement(sqlUpdateEntrust);
            patUpdateEntrust.setObject(1, SubNo);
            patUpdateEntrust.setObject(2, SubSeq);
            patUpdateEntrust.addBatch();
            patUpdateEntrust.executeBatch();

            // UpdateEntrustNum(HttEntrustEntity.getProcessCode(),connection,HttEntrustEntity.getResultNo());

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);
            patAddProcess.setObject(1, SubNo);
            patAddProcess.setObject(2, SubNo);
            patAddProcess.setObject(3, "回报完毕");
            patAddProcess.setObject(4, Name);
            patAddProcess.setObject(5, "");
            patAddProcess.setObject(6, "30");
            patAddProcess.setObject(7, "40");
            patAddProcess.addBatch();
            patAddProcess.executeBatch();

            HttEntrustProcessDefaulEntity last = AutoApproval(connection, HttEntrustEntity, null, "40");

            if (last == null) {
                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        "40", "0".equals(HttEntrustEntity.getSubcontractTarget()) ? "4" : "5",
                        "[" + ( "0".equals(HttEntrustEntity.getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntity.getPlineName(),
                        ""
                        , "", Name);
            } else {
                messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                        last.getStatusNext(), last.getApprovalNoNext(),
                        "[" + ( "0".equals(HttEntrustEntity.getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntity.getPlineName(),
                        ""
                        , "", Name);
            }

            core.setV_errMsg("回报成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 回报完毕
     *
     * @param SubNo
     * @param SubSeq
     * @return
     */
    public CoreReturnObject CheckRelay(String SubNo, String SubSeq) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            String UnReplayData = "";
            Date dt = new Date();
            String sqlloading = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.CheckRelay");// 查询最大实绩编号
            psta = connection.prepareStatement(sqlloading);
            psta.setObject(1, SubNo);
            psta.setObject(2, SubSeq);

            ResultSet rs1 = psta.executeQuery();
            while (rs1.next()) {
                UnReplayData += UnReplayData
                        + ( UnReplayData.equals("") ? "" : "," )
                        + rs1.getString("PROJECT_NAME");
            }
            rs1.close();
            psta.close();

            core.setV_errMsg(UnReplayData);
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 取消回报完毕
     *
     * @param SubNo
     * @param SubSeq
     * @param Name
     * @return
     */
    public CoreReturnObject CancelReplay(String SubNo, String SubSeq,
                                         String Name) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            HttEntrustEntity HttEntrustEntity = GetHttEntrustEntity(connection,
                    SubNo, SubSeq);
            if (HttEntrustEntity == null) {
                throw new Exception("委外单不存在!!");
            }
            if (!HttEntrustEntity.getSubcontractLog().equals("40")) {
                throw new Exception("委外单未回报完毕!");
            }

            String MatNos = GetEntrustMatNo(connection, HttEntrustEntity
                    .getProcessCode(), SubNo);
            List<OfflineResultEntity> OfflineResultEntity = GetOffLineResultEntity(
                    HttEntrustEntity.getProcessCode(), connection,
                    HttEntrustEntity.getResultNo(), MatNos);

            if (OfflineResultEntity == null || OfflineResultEntity.size() <= 0) {
                throw new Exception("数据已返线,无法撤销");
            }

            if (!OfflineResultEntity.get(0).getSubcontractNo().equals(SubNo)) {
                throw new Exception("已经重新申请委托,无法撤销");
            }

            String sqlUpdateEntrust = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus4");
            PreparedStatement patUpdateEntrust = connection
                    .prepareStatement(sqlUpdateEntrust);
            patUpdateEntrust.setObject(1, SubNo);
            patUpdateEntrust.setObject(2, SubSeq);
            patUpdateEntrust.addBatch();
            patUpdateEntrust.executeBatch();

            // UpdateEntrustNum(HttEntrustEntity.getProcessCode(),connection,HttEntrustEntity.getResultNo());

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddProcess");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);
            patAddProcess.setObject(1, SubNo);
            patAddProcess.setObject(2, SubNo);
            patAddProcess.setObject(3, "撤销回报完毕");
            patAddProcess.setObject(4, Name);
            patAddProcess.setObject(5, "");
            patAddProcess.setObject(6, "40");
            patAddProcess.setObject(7, "30");
            patAddProcess.addBatch();
            patAddProcess.executeBatch();

            messageHelper.addOrUpdateEntrustMessage(connection, SubNo,
                    "30", "/",
                    "[" + ( "0".equals(HttEntrustEntity.getSubcontractTarget()) ? "委外" : "委内" ) + "] " + HttEntrustEntity.getPlineName(),
                    ""
                    , "", Name);

            core.setV_errMsg("撤销成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 获取各工序点离线数据
     *
     * @param Process
     * @param connection
     * @param ResultNo
     * @return
     * @throws Exception
     */
    private List<OfflineResultEntity> GetOffLineResultEntity(String Process,
                                                             Connection connection, String ResultNo, String MatNos)
            throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryOfflineD");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, Paras[0]);
            psta.setObject(2, Paras[1]);
            psta.setObject(3, Paras[2]);
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();

        } else if (Process.equals("E")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryOfflineE");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, ResultNo);
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();

        } else if (Process.equals("F")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryOfflineF");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, ResultNo);
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();

        } else if (Process.equals("G")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryOfflineG");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, ResultNo);
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();
        } else if (Process.equals("H")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 2) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryOfflineH");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, Paras[0]);
            psta.setObject(2, Paras[1]);
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();
        } else if (Process.equals("BC")) {
            if (MatNos == null || MatNos.equals("")) {
                throw new Exception("库存数据发生改变,无法进行此操作");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryBC2");// 查询新增物料信息
            String MatNo = PlanService.toSqlConditionString("T.MAT_NO", MatNos
                    .split(","));
            sqlMatNo = sqlMatNo.replace("#MAT_NO#", MatNo);
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            int DataCount = 0;
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();

        } else if (Process.equals("ZC") || Process.equals("SP")) {
            if (MatNos == null || MatNos.equals("")) {
                throw new Exception("库存数据发生改变,无法进行此操作");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doQueryZC2");// 查询新增物料信息
            String MatNo = PlanService.toSqlConditionString("T.MAT_NO", MatNos
                    .split(","));
            sqlMatNo = sqlMatNo.replace("#MAT_NO#", MatNo);
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            int DataCount = 0;
            ResultSet rs = psta.executeQuery();
            OfflineResultEntity = EntityTool.getEntitysByRs(rs,
                    com.steering.mes.mcp.entity.OfflineResultEntity.class);
            rs.close();
            psta.close();
        }

        return OfflineResultEntity;
    }

    /**
     * 获取委托单信息
     *
     * @param connection
     * @param SubNo
     * @return
     * @throws Exception
     */
    private List<HttEntrustEntity> GetHttEntrustEntity(Connection connection,
                                                       String SubNo) throws Exception {
        List<HttEntrustEntity> HttEntrustEntity = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryApply");

        sqlMatNo += " AND SUBCONTRACT_NO=?";
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, SubNo);
        ResultSet rs = psta.executeQuery();
        HttEntrustEntity = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustEntity.class);
        rs.close();
        psta.close();

        return HttEntrustEntity;
    }

    private String GetEntrustMatNo(Connection connection, String process,
                                   String SubNo) throws Exception {
        String MatNos = "";

        if (process.equals("ZC") || process.equals("SP")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryEntrustZcMatNoBySubNo");

            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                MatNos = rs.getString("MAT_NOS");
            }
            rs.close();
            psta.close();

            rs.close();
            psta.close();
        } else {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryEntrustBcMatNoBySubNo");

            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                MatNos = rs.getString("MAT_NOS");
            }
            rs.close();
            psta.close();

            rs.close();
            psta.close();

        }

        return MatNos;
    }

    /**
     * 获取委托单分切详细
     *
     * @param connection
     * @param OfflineResultNo
     * @param MatNo
     * @return
     * @throws Exception
     */
    private List<HttEntrustMatNoEntity> GetHttEntrustCutDetailEntity(
            Connection connection, String OfflineResultNo, String MatNo)
            throws Exception {
        List<HttEntrustMatNoEntity> HttEntrustMatNoEntitys = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.GetHttEntrustCutDetailEntity");

        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, OfflineResultNo);
        psta.setObject(2, MatNo);
        ResultSet rs = psta.executeQuery();
        HttEntrustMatNoEntitys = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustMatNoEntity.class);
        rs.close();
        psta.close();

        return HttEntrustMatNoEntitys;
    }


    /**
     * 获取委托单分切详细
     *
     * @param connection
     * @param OfflineResultNo
     * @return
     * @throws Exception
     */
    private List<HttEntrustMatNoEntity> GetHttEntrustCutDetailEntity(
            Connection connection, String OfflineResultNo)
            throws Exception {
        List<HttEntrustMatNoEntity> HttEntrustMatNoEntitys = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.GetHttEntrustCutDetailEntity3");

        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, OfflineResultNo);
        ResultSet rs = psta.executeQuery();
        HttEntrustMatNoEntitys = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustMatNoEntity.class);
        rs.close();
        psta.close();

        return HttEntrustMatNoEntitys;
    }

    /**
     * 获取委托单分切详细
     *
     * @param connection
     * @param MatNo
     * @return
     * @throws Exception
     */
    private List<HttEntrustMatNoEntity> GetHttEntrustCutDetailEntity(
            Connection connection, String SubNo, String SubSeq, String MatNo)
            throws Exception {
        List<HttEntrustMatNoEntity> HttEntrustMatNoEntitys = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.GetHttEntrustCutDetailEntity2");

        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, SubNo);
        psta.setObject(2, SubSeq);
        psta.setObject(3, MatNo);
        ResultSet rs = psta.executeQuery();
        HttEntrustMatNoEntitys = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustMatNoEntity.class);
        rs.close();
        psta.close();

        return HttEntrustMatNoEntitys;
    }

    /**
     * 获取委托单信息
     *
     * @param connection
     * @param SubNo
     * @param SubNoSeq
     * @return
     * @throws Exception
     */
    private HttEntrustEntity GetHttEntrustEntity(Connection connection,
                                                 String SubNo, String SubNoSeq) throws Exception {
        List<HttEntrustEntity> HttEntrustEntity = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryApply");// 查询新增物料信息

        sqlMatNo += " AND SUBCONTRACT_NO=?";
        sqlMatNo += " AND SUBCONTRACT_NO_SEQ=?";
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, SubNo);
        psta.setObject(2, SubNoSeq);
        ResultSet rs = psta.executeQuery();
        HttEntrustEntity = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustEntity.class);
        rs.close();
        psta.close();

        return HttEntrustEntity == null || HttEntrustEntity.size() <= 0 ? null
                : HttEntrustEntity.get(0);
    }

    /**
     * 获取实绩
     *
     * @param connection
     * @param ResultNo
     * @return
     * @throws Exception
     */
    private HttEntrustResultEntity GetHttEntrustResultEntity(
            Connection connection, String ResultNo) throws Exception {
        List<HttEntrustResultEntity> HttEntrustResultEntitys = null;

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.doQueryResult2");//
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, ResultNo);
        ResultSet rs = psta.executeQuery();
        HttEntrustResultEntitys = EntityTool.getEntitysByRs(rs,
                com.steering.mes.mcp.entity.HttEntrustResultEntity.class);
        rs.close();
        psta.close();

        return HttEntrustResultEntitys == null
                || HttEntrustResultEntitys.size() <= 0 ? null
                : HttEntrustResultEntitys.get(0);
    }

    /**
     * 更新离线表信息
     *
     * @param Process
     * @param connection
     * @param ResultNo
     * @throws Exception
     */
    private void UpdateEntrustNum(String Process, Connection connection,
                                  String ResultNo) throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineD");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, Paras[0]);
            psta.setObject(2, Paras[1]);
            psta.setObject(3, Paras[2]);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("E")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineE");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, ResultNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();

        } else if (Process.equals("F")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineF");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, ResultNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("G")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineG");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, ResultNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("H")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 2) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineH");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, Paras[0]);
            psta.setObject(2, Paras[1]);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        }

    }

    private void UpdateMatSubNo(String Process, Connection connection,
                                String SubNo, String SubSeq, String ResultNo, String MatNos)
            throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcMD");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            psta.setObject(2, SubSeq);
            psta.setObject(3, Paras[0]);
            psta.setObject(4, Paras[1]);
            psta.setObject(5, Paras[2]);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("H")) {
            if (MatNos == null || MatNos.equals("") || MatNos.equals("null")) {
                return;
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcMBC3");
            sqlMatNo += CoreConverter.toSqlConditionString("T.MAT_NO", MatNos
                    .split(","));
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            psta.setObject(2, SubSeq);
            psta.addBatch();
            psta.executeBatch();
            psta.close();

        } else if (Process.equals("BC")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcMBC");
            sqlMatNo += CoreConverter.toSqlConditionString("T.MAT_NO", MatNos
                    .split(","));
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            psta.setObject(2, SubSeq);
            psta.setObject(3, SubNo.equals("") ? "0" : "1");
            psta.addBatch();
            psta.executeBatch();
            psta.close();

        } else if (Process.equals("ZC")|| Process.equals("SP")) {

            if(MatNos!=null && MatNos.length()>0) {
                String sqlMatNo = CoreXmlSqlParsersFactory
                        .getSql("frmEntrust.UpdateMatBcMZC");
                sqlMatNo += CoreConverter.toSqlConditionString("T.MAT_NO", MatNos
                        .split(","));
                PreparedStatement psta = connection.prepareStatement(sqlMatNo);
                psta.setObject(1, SubNo);
                psta.setObject(2, SubSeq);
                psta.setObject(3, SubNo.equals("") ? "0" : "1");
                psta.addBatch();
                psta.executeBatch();
                psta.close();
            }

        } else {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcM");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, SubNo);
            psta.setObject(2, SubSeq);
            psta.setObject(3, ResultNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        }
    }

    private void UpdateMatSubNo(String Process, Connection connection,
                                String SubNo, String Flag) throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("BC")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcMBC2");
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, Flag);
            psta.setObject(2, SubNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("ZC")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateMatBcMZC2");
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);
            psta.setObject(1, Flag);
            psta.setObject(2, SubNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        }
    }

    /**
     * 更新管号队列信息
     *
     * @param Process
     * @param connection
     * @param SubNo
     * @throws Exception
     */
    private void UpdatePort(String Process, Connection connection, String SubNo)
            throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("D")) {
            // 不更新管号队列, 返线 会更新。
        } else if (Process.equals("E")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdatePortE");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, SubNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();

        } else if (Process.equals("F")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineF");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, SubNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("G")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateOfflineG");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, SubNo);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        }
    }

    /**
     * 更新委托单信息
     *
     * @param connection
     * @param SubNo
     * @param Status
     * @param PlineCode
     * @param Note
     * @param Name
     * @param Operator
     * @throws Exception
     */
    private void UpdateEntrustStatus(Connection connection, String SubNo,
                                     String Status, String PlineCode, String Note, String Name,
                                     String Operator, String No, String Memo) throws Exception {

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.UpdateEntrustStatus");
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, Status);
        psta.setObject(2, PlineCode);
        psta.setObject(3, PlineCode);
        psta.setObject(4, Note);
        psta.setObject(5, Name);
        psta.setObject(6, Operator);
        psta.setObject(7, No);
        psta.setObject(8, Memo);
        psta.setObject(9, SubNo);
        psta.addBatch();
        psta.executeBatch();
        psta.close();
    }

    /**
     * 更新用车方式
     *
     * @param connection
     */
    private void UpdateEntrustTransCode(Connection connection,
                                        String transCode, String SubNo, String SubSeq) throws Exception {

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.UpdateEntrustTransCode");
        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setString(1, transCode);
        psta.setString(2, SubNo);
        psta.setString(3, SubSeq);
        psta.addBatch();
        psta.executeBatch();
        psta.close();
    }

    /**
     * 查询产线
     *
     * @return
     */
    public CoreReturnObject doQueryPlineCode(String plineCode) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmMchSourcApp.doQueryPlineCode");

        sql += " AND T.PROCESS_CODE IN ('D','E','F','G')  ORDER BY T.PLINE_NAME ASC";
        return this.getData(sql);
    }

    /**
     * 找离线库存
     *
     * @param ResultNo
     * @param Process
     * @return
     * @throws Exception
     */
    public CoreReturnObject QueryOfflineMatNo(String SubNo, String SubSeq,
                                              String ResultNo, String Process) throws Exception {
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoD",
                    new Object[]{Paras[0], Paras[1], Paras[2]});

        } else if (Process.equals("E")) {
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoE",
                    new Object[]{ResultNo, ResultNo});

        } else if (Process.equals("F")) {

            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoF",
                    new Object[]{ResultNo, ResultNo});
        } else if (Process.equals("G")) {
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoG",
                    new Object[]{ResultNo, ResultNo});
        } else if (Process.equals("H")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 2) {
                throw new Exception("数据异常");
            }

            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoH",
                    new Object[]{Paras[0], Paras[1], Paras[0], Paras[1]});
        } else if (Process.equals("BC")) {

            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNo",
                    new Object[]{SubNo, SubSeq});
        } else if (Process.equals("ZC")) {

            return this.getDataBySqlID("frmEntrust.QueryZcMatNo", new Object[]{
                    SubNo, SubSeq});
        } else {
            throw new Exception("不支持该工序废品");
        }
    }

    /**
     * 找离线库存
     *
     * @param HeatPlanId
     * @param ResultNo
     * @param Process
     * @return
     * @throws Exception
     */
    public CoreReturnObject QueryOfflineMatNo(String HeatPlanId,
                                              String ResultNo, String Process) throws Exception {
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoD",
                    new Object[]{Paras[0], Paras[1], Paras[2]});

        } else if (Process.equals("E")) {
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoE",
                    new Object[]{ResultNo, ResultNo});

        } else if (Process.equals("F")) {

            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoF",
                    new Object[]{ResultNo, ResultNo});
        } else if (Process.equals("G")) {
            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoG",
                    new Object[]{ResultNo, ResultNo});
        } else if (Process.equals("H")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 2) {
                throw new Exception("数据异常");
            }

            return this.getDataBySqlID("frmEntrust.QueryOfflineMatNoH",
                    new Object[]{Paras[0], Paras[1], Paras[0], Paras[1]});
        } else {
            throw new Exception("不支持该工序废品");
        }
    }

    /**
     * 获取新批号
     *
     * @param connection
     * @param JudgeStove
     * @param ProcessCode
     * @return
     * @throws SQLException
     */
    public String GetNewBatchNo(Connection connection, String JudgeStove,
                                String ProcessCode) throws SQLException {

        String BatchNo = "";
        if (ProcessCode.equals("D")) {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.GetNewBatchNoD");// 查询是否离线
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setString(1, JudgeStove.split("-")[0]);
            psta.setString(2, JudgeStove);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                BatchNo = String.valueOf(rs.getString("BATCH_NO"));
            }
            rs.close();
            psta.close();
        }
        if (ProcessCode.equals("E")) {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.GetNewBatchNoE");// 查询是否离线
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setString(1, JudgeStove.split("-")[0]);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                BatchNo = String.valueOf(rs.getString("BATCH_NO"));
            }
            rs.close();
            psta.close();
        }
        if (ProcessCode.equals("F")) {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.GetNewBatchNoF");// 查询是否离线
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setString(1, JudgeStove.split("-")[0]);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                BatchNo = String.valueOf(rs.getString("BATCH_NO"));
            }
            rs.close();
            psta.close();
        }
        if (ProcessCode.equals("G")) {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.GetNewBatchNoG");// 查询是否离线
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setString(1, JudgeStove.split("-")[0]);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                BatchNo = String.valueOf(rs.getString("BATCH_NO"));
            }
            rs.close();
            psta.close();
        }
        return BatchNo;
    }

    /**
     * 更新报告地址
     *
     * @param Path
     * @param ResultNo
     * @return
     */
    public CoreReturnObject UpdatePath(String Path, String ResultNo) {
        ArrayList<String> SqlId = new ArrayList<String>();
        ArrayList<Object[]> Para = new ArrayList<Object[]>();
        SqlId.add("FrmCrackDetectResult.UpdatePath");
        SqlId.add("frmEntrust.UpdatePath");
        Para.add(new Object[]{Path, ResultNo});
        Para.add(new Object[]{Path, ResultNo});
        return this.setDataById(SqlId, Para);
    }

    /**
     * 更新报告地址
     *
     * @param Path
     * @return
     */
    public CoreReturnObject UpdateEntrutPath(String Path, String SubNo,
                                             String SubSeq) {
        ArrayList<String> SqlId = new ArrayList<String>();
        ArrayList<Object[]> Para = new ArrayList<Object[]>();
        SqlId.add("frmEntrust.UpdateEntrutPath");
        Para.add(new Object[]{Path, SubNo, SubSeq});
        return this.setDataById(SqlId, Para);
    }

    /**
     * 更新批号
     *
     * @param connection
     * @param HeatPlanID
     * @param ResultNo
     * @param JudgeStove
     * @param BatchNo
     * @param NewBatchNo
     * @param Process
     * @param Num
     * @throws Exception
     */
    public void UpdatePortBatchNo(Connection connection, String HeatPlanID,
                                  String ResultNo, String JudgeStove, String BatchNo,
                                  String NewBatchNo, String Process, String Num) throws Exception {
        List<OfflineResultEntity> OfflineResultEntity = null;
        if (Process.equals("D")) {
            String[] Paras = ResultNo.split("_");

            if (Paras.length != 3) {
                throw new Exception("数据异常");
            }

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdatePortBatchNoD");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, NewBatchNo);
            psta.setObject(2, JudgeStove);
            psta.setObject(3, BatchNo);
            psta.setObject(4, Paras[1]);
            psta.setObject(5, Num);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("E")) {
            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdatePortBatchNoE");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, NewBatchNo);
            psta.setObject(2, HeatPlanID);
            psta.setObject(3, BatchNo);
            psta.setObject(4, Num);
            psta.addBatch();
            psta.executeBatch();
            psta.close();

        } else if (Process.equals("F")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdatePortBatchNoF");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, NewBatchNo);
            psta.setObject(2, HeatPlanID);
            psta.setObject(3, BatchNo);
            psta.setObject(4, ResultNo);
            psta.setObject(5, Num);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        } else if (Process.equals("G")) {

            String sqlMatNo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdatePortBatchNoG");// 查询新增物料信息
            PreparedStatement psta = connection.prepareStatement(sqlMatNo);

            psta.setObject(1, NewBatchNo);
            psta.setObject(2, HeatPlanID);
            psta.setObject(3, BatchNo);
            psta.setObject(4, ResultNo);
            psta.setObject(5, Num);
            psta.addBatch();
            psta.executeBatch();
            psta.close();
        }
    }

    /**
     * 调整项目
     *
     * @param SubNo
     * @param Memo
     * @param ProjectStrs
     * @param Operator
     * @return
     */
    public CoreReturnObject UpdateProject(String SubNo, String Memo,
                                          ArrayList<String> ProjectStrs, String Operator, String No) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        SimpleDateFormat matter1 = new SimpleDateFormat("yyMMdd");

        try {
            connection.setAutoCommit(false); //

            String sqlAddProject = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.AddApplyProject2");
            PreparedStatement patAddProject = connection
                    .prepareStatement(sqlAddProject);


            String sqlDeleteProject = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.DeleteApplyProject");
            PreparedStatement patDeleteProject = connection
                    .prepareStatement(sqlDeleteProject);
            patDeleteProject.setObject(1, SubNo);
            patDeleteProject.addBatch();
            patDeleteProject.executeBatch();

            List<HttEntrustEntity> HttEntrustEntitys = GetHttEntrustEntity(
                    connection, SubNo);
            if (HttEntrustEntitys == null || HttEntrustEntitys.size() <= 0) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.get(0).getSubcontractLog().equals("")
                    || HttEntrustEntitys.get(0).getSubcontractLog().equals(
                    "null")) {
                throw new Exception("未申请委外,请确认!");
            }

            boolean isExitsPackage = false;
            boolean isExitsNonePackage = false;

            for (int i = 0; i < ProjectStrs.size(); i++) {
                HttEntrustProjectEntity Project = EntityTool
                        .getEntityByJSONStr(ProjectStrs.get(i),
                                HttEntrustProjectEntity.class);

                if (Project.getProjectCode().startsWith("702205")) {
                    isExitsPackage = true;
                } else {
                    isExitsNonePackage = true;
                }

                patAddProject.setObject(1, Project.getProjectCode());
                patAddProject.setObject(2, Project.getProjectName());
                patAddProject.setObject(3, Project.getProjectStatus());
                patAddProject.setObject(4, Project.getProjectMemo());
                patAddProject.setObject(5, Project.getProjectFlag());
                patAddProject.setObject(6, Project.getProjectType());
                patAddProject.setObject(7, Project.getProjectMemoOrgin());
                patAddProject.setObject(8, Project.getProjectTypeOrgin());
                patAddProject.setObject(9, Project.getPayDepartmentCode());
                patAddProject.setObject(10, Project.getPayDepartmentName());
                patAddProject.setObject(11, SubNo);
                patAddProject.addBatch();

            }

            if (isExitsPackage && isExitsNonePackage) {
                throw new Exception("钢管包装项目不能与非钢管包装项目同时委托!");
            }

            patAddProject.executeBatch();


            for (int i = 0; i < HttEntrustEntitys.size(); i++) {

                HttEntrustEntity Entity = HttEntrustEntitys.get(i);

                if (Entity.getSubcontractLog().equals("50")
                        || HttEntrustEntitys.get(i).getSubcontractLog().equals(
                        "60")) {
                    throw new Exception("已经回报审核,无法调整项目!");
                }

                UpdateEntrustStatus(connection, SubNo, "", Entity.getSubcontractPlineCode(),
                        "", "", Operator, No, Memo);

            }


            core.setV_errMsg("调整成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 查询价格
     *
     * @param ProjectType
     * @param isValid
     * @return
     */
    public CoreReturnObject doQueryPrice(String ProjectType, String isValid) {
        return this.getDataBySqlID("frmEntrust.doQueryPrice", new Object[]{
                ProjectType, isValid});
    }

    /**
     * 查询项目可选备注
     *
     * @param ProjectCode
     * @return
     */
    public CoreReturnObject doQueryApplyMemo(String ProjectCode) {
        return this.getDataBySqlID("frmEntrust.doQueryApplyMemo",
                new Object[]{ProjectCode});
    }

    /**
     * 增加价格信息
     *
     * @param EntityStr
     * @param MemoStrs
     * @return
     */
    public CoreReturnObject doAddPrice(String EntityStr,
                                       ArrayList<String> MemoStrs) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            HttEntrustPriceEntity Entity = EntityTool.getEntityByJSONStr(
                    EntityStr, HttEntrustPriceEntity.class);

            int Count = 0;
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryExists");
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setObject(1, Entity.getProjectCode());
            psta.setObject(2, Entity.getSteelcode());
            psta.setObject(3, Entity.getSpecCode());
            psta.setObject(4, Entity.getModelCode());
            psta.setObject(5, "");
            ResultSet rs1 = psta.executeQuery();
            if (rs1.next()) {
                Count = rs1.getInt("COUNT");
            }
            rs1.close();
            psta.close();

            if (Count > 0) {
                core.setV_errMsg("存在相同的委托项,相同扣型,钢级,规格数据, 请确认");
                return core;
            }

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doAddPrice");
            sqlAddProcess = com.steering.common.EntityTool.fillSqlByEntity(
                    sqlAddProcess, Entity);
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);
            patAddProcess.addBatch();
            patAddProcess.executeBatch();

            String sqlDelete = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.deleteApplyMemo");
            PreparedStatement patDelete = connection
                    .prepareStatement(sqlDelete);
            patDelete.setObject(1, Entity.getProjectCode());
            patDelete.addBatch();
            patDelete.executeBatch();

            String sqlAddMemo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.addApplyMemo");
            PreparedStatement patAddMemo = connection
                    .prepareStatement(sqlAddMemo);

            for (int i = 0; i < MemoStrs.size(); i++) {
                HttEntrustApplymemoEntity memo = EntityTool.getEntityByJSONStr(
                        EntityStr, HttEntrustApplymemoEntity.class);
                patAddMemo.setObject(1, memo.getProjectCode());
                patAddMemo.setObject(2, memo.getProjectName());
                patAddMemo.setObject(3, memo.getProjectMemo());
                patAddMemo.setObject(4, memo.getSeq());
                patAddMemo.addBatch();
            }
            patAddMemo.executeBatch();

            core.setV_errMsg("新增成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 更新价格信息
     *
     * @param EntityStr
     * @param MemoStrs
     * @return
     */
    public CoreReturnObject doUpdatePrice(String EntityStr,
                                          ArrayList<String> MemoStrs) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            HttEntrustPriceEntity Entity = EntityTool.getEntityByJSONStr(
                    EntityStr, HttEntrustPriceEntity.class);

            int Count = 0;
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryExists");
            PreparedStatement psta = connection.prepareStatement(sql);
            psta.setObject(1, Entity.getProjectCode());
            psta.setObject(2, Entity.getSteelcode());
            psta.setObject(3, Entity.getSpecCode());
            psta.setObject(4, Entity.getModelCode());
            psta.setObject(5, Entity.getId());
            ResultSet rs1 = psta.executeQuery();
            if (rs1.next()) {
                Count = rs1.getInt("COUNT");
            }
            rs1.close();
            psta.close();

            if (Count > 0) {
                core.setV_errMsg("存在相同的委托项,相同扣型,钢级,规格数据, 请确认");
                return core;
            }

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doUpdatePrice");
            sqlAddProcess = com.steering.common.EntityTool.fillSqlByEntity(
                    sqlAddProcess, Entity);
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);
            patAddProcess.addBatch();
            patAddProcess.executeBatch();

            String sqlDelete = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.deleteApplyMemo");
            PreparedStatement patDelete = connection
                    .prepareStatement(sqlDelete);
            patDelete.setObject(1, Entity.getProjectCode());
            patDelete.addBatch();
            patDelete.executeBatch();

            String sqlAddMemo = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.addApplyMemo");
            PreparedStatement patAddMemo = connection
                    .prepareStatement(sqlAddMemo);

            for (int i = 0; i < MemoStrs.size(); i++) {
                HttEntrustApplymemoEntity memo = EntityTool.getEntityByJSONStr(
                        MemoStrs.get(i), HttEntrustApplymemoEntity.class);
                patAddMemo.setObject(1, Entity.getProjectCode());
                patAddMemo.setObject(2, Entity.getProjectName());
                patAddMemo.setObject(3, memo.getProjectMemo());
                patAddMemo.setObject(4, memo.getSeq());
                patAddMemo.addBatch();
            }
            patAddMemo.executeBatch();

            core.setV_errMsg("修改成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 删除价格信息
     *
     * @param EntityStr
     * @return
     */
    public CoreReturnObject doDeletePrice(String EntityStr) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            HttEntrustPriceEntity Entity = EntityTool.getEntityByJSONStr(
                    EntityStr, HttEntrustPriceEntity.class);

            String sqlAddProcess = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doDeletePrice");
            PreparedStatement patAddProcess = connection
                    .prepareStatement(sqlAddProcess);
            patAddProcess.setObject(1, "0");
            patAddProcess.setObject(2, Entity.getDeleteName());
            patAddProcess.setObject(3, Entity.getId());
            patAddProcess.addBatch();
            patAddProcess.executeBatch();

            core.setV_errMsg("作废成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    public CoreReturnObject GetMaxReportNo() {
        return getDataBySqlID("frmEntrust.GetMaxReportNo", new Object[]{});
    }

    public HttEntrustProjectEntity GetProject(Connection con, String SubNo,
                                              String SubSeq, String ProjectCode) throws SQLException {
        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.GetProject");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, SubNo);
        ps.setObject(2, SubSeq);
        ps.setObject(3, ProjectCode);
        ResultSet rs = ps.executeQuery();
        List<HttEntrustProjectEntity> HttEntrustProjectEntitys = EntityTool
                .getEntitysByRs(rs, HttEntrustProjectEntity.class);
        rs.close();
        ps.close();
        if (HttEntrustProjectEntitys == null
                || HttEntrustProjectEntitys.size() == 0) {
            return null;
        } else {
            for (HttEntrustProjectEntity HttEntrustProjectEntity : HttEntrustProjectEntitys) {
                QualityDesignTool.nullConverNullString(HttEntrustProjectEntity);
            }
            return HttEntrustProjectEntitys.get(0);
        }
    }


    public CoreReturnObject doQuerBal(String BalYearMonth, String[] plinCodes) {
        return doQuerBal(BalYearMonth, plinCodes, null);
    }

    public CoreReturnObject doQuerBal(String BalYearMonth, String[] plinCodes, String[] item) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQuerBal");

        String Where = "";
        if (plinCodes.length <= 0) {
            Where += " AND 1<>1";

        } else {
            Where += CoreConverter.toSqlConditionString(
                    "M.SUBCONTRACT_PLINE_CODE", plinCodes);

        }
        if (item != null && item.length > 0) {
            Where +=
                    CoreConverter.toSqlNotLikeConditionString("P.PROJECT_CODE", item);
        }
        sql = sql.replace("#PLINECODE#", Where);


        return this.getData(sql, new Object[]{BalYearMonth});

    }

    public CoreReturnObject doQuerUnBal(String[] plinCodes) {

        return doQuerUnBal(plinCodes, null);
    }

    public CoreReturnObject doQuerUnBal(String[] plinCodes, String[] item) {

        String sql = CoreXmlSqlParsersFactory.getSql("frmEntrust.doQuerUnBal");

        String Where = "";
        if (plinCodes.length <= 0) {
            Where += " AND 1<>1";

        } else {
            Where += CoreConverter.toSqlConditionString(
                    "M.SUBCONTRACT_PLINE_CODE", plinCodes);

        }

        if (item != null && item.length > 0) {
            Where +=
                    CoreConverter.toSqlNotLikeConditionString("P.PROJECT_CODE", item);
        }

        sql = sql.replace("#PLINECODE#", Where);

        return this.getData(sql, new Object[]{});

    }

    public CoreReturnObject doUpdateSettle(ArrayList<String> UpdateDatas) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); //

            String sqlupdate = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doUpdateSettle");// 修改委托表状态
            PreparedStatement patupdate = connection
                    .prepareStatement(sqlupdate);

            for (int i = 0; i < UpdateDatas.size(); i++) {
                String[] paras = UpdateDatas.get(i).split(",", -1);

                HttEntrustProjectEntity Entity = GetProject(connection,
                        paras[0], paras[1], paras[2]);
                if (Entity.getProjectStatus().equals("10")) {
                    throw new Exception("已结算的数据无法修改");
                }

                patupdate.setObject(1, paras[3]);
                patupdate.setObject(2, paras[4]);
                patupdate.setObject(3, paras[4]);
                patupdate.setObject(4, paras[5]);
                patupdate.setObject(5, paras[6]);
                patupdate.setObject(6, paras[0]);
                patupdate.setObject(7, paras[1]);
                patupdate.setObject(8, paras[2]);
                patupdate.addBatch();
            }
            patupdate.executeBatch();

            core.setV_errMsg("修改成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    public CoreReturnObject Settle(ArrayList<String> UpdateDatas) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); //

            String sqlupdate = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doUpdateSettle2");// 修改委托表状态
            PreparedStatement patupdate = connection
                    .prepareStatement(sqlupdate);

            for (int i = 0; i < UpdateDatas.size(); i++) {
                String[] paras = UpdateDatas.get(i).split(",", -1);

                HttEntrustProjectEntity Entity = GetProject(connection,
                        paras[0], paras[1], paras[2]);
                if (Entity.getProjectStatus().equals("10")) {
                    continue;
                }

                patupdate.setObject(1, paras[3]);
                patupdate.setObject(2, paras[4]);
                patupdate.setObject(3, paras[4]);
                patupdate.setObject(4, paras[5]);
                patupdate.setObject(5, paras[6]);
                patupdate.setObject(6, paras[7]);
                patupdate.setObject(7, paras[8]);
                patupdate.setObject(8, paras[9]);
                patupdate.setObject(9, paras[10]);
                patupdate.setObject(10, paras[0]);
                patupdate.setObject(11, paras[1]);
                patupdate.setObject(12, paras[2]);
                patupdate.addBatch();
            }
            patupdate.executeBatch();

            core.setV_errMsg("结算成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    public CoreReturnObject CancelSettle(ArrayList<String> UpdateDatas) {
        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM",
                Locale.CHINA);
        Date now = new Date();
        String systime = dateFormat.format(now);

        try {
            connection.setAutoCommit(false); //

            String sqlupdate = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.doUpdateSettle3");// 修改委托表状态
            PreparedStatement patupdate = connection
                    .prepareStatement(sqlupdate);

            for (int i = 0; i < UpdateDatas.size(); i++) {
                String[] paras = UpdateDatas.get(i).split(",", -1);

                HttEntrustProjectEntity Entity = GetProject(connection,
                        paras[0], paras[1], paras[2]);
                if (!Entity.getProjectStatus().equals("10")) {
                    continue;
                }

                if (!systime.equals(Entity.getBalYearMonth())) {
                    throw new Exception("只允许撤销当月结算");
                }

                patupdate.setObject(1, paras[3]);
                patupdate.setObject(2, paras[4]);
                patupdate.setObject(3, paras[4]);
                patupdate.setObject(4, paras[5]);
                patupdate.setObject(5, paras[6]);
                patupdate.setObject(6, paras[0]);
                patupdate.setObject(7, paras[1]);
                patupdate.setObject(8, paras[2]);
                patupdate.addBatch();
            }
            patupdate.executeBatch();

            core.setV_errMsg("撤销结算成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 开始生产
     *
     * @param Step
     * @param Name
     * @return
     */
    public CoreReturnObject Start(String SubNo, String Seq, String Step,
                                  String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

			/*
			 * String sqlAddProcess = CoreXmlSqlParsersFactory
			 * .getSql("frmEntrust.AddProcess"); PreparedStatement patAddProcess
			 * = connection.prepareStatement(sqlAddProcess);
			 */
            String sqlUpdateStatus = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.UpdateEntrustStatus6");
            PreparedStatement psUpdateStatus = connection
                    .prepareStatement(sqlUpdateStatus);

            if (SubNo.equals("")) {
                throw new Exception("未申请委外,请确认!");
            }

            HttEntrustEntity HttEntrustEntitys = GetHttEntrustEntity(
                    connection, SubNo, Seq);
            if (HttEntrustEntitys == null) {
                throw new Exception("数据异常, 找不到委托数据，请刷新数据");
            }

            if (HttEntrustEntitys.getSubcontractLog().equals("")) {
                throw new Exception("未申请委外,请确认!");
            }

            String Status = "";
            String Info = "";

            // 开始生产
            if (Step.equals("0")) {

                if (HttEntrustEntitys == null) {
                    throw new Exception("数据异常, 找不到委托数据，请刷新数据");
                }

                if (HttEntrustEntitys.getSubcontractLog().equals("")
                        || HttEntrustEntitys.getSubcontractLog().equals("null")) {
                    throw new Exception("未申请委外,请确认!");
                }

                if (HttEntrustEntitys.getSubcontractLog().equals("30")
                        || HttEntrustEntitys.getSubcontractLog().equals("40")
                        || HttEntrustEntitys.getSubcontractLog().equals("50")
                        || HttEntrustEntitys.getSubcontractLog().equals("60")) {
                    throw new Exception("已回报,无法标记已生产!");
                }

                if (HttEntrustEntitys.getSubcontractTarget().equals("0")) {

                    if (!HttEntrustEntitys.getSubcontractLog().equals("24")
                            && !HttEntrustEntitys.getSubcontractLog().equals(
                            "30")) {
                        throw new Exception("已撤销审核,标记已生产!");
                    }
                } else {
                    if (!HttEntrustEntitys.getSubcontractLog().equals("10")
                            && !HttEntrustEntitys.getSubcontractLog().equals(
                            "30")) {
                        throw new Exception("已撤销审核,标记已生产!");
                    }
                }

                Info = "开始生产";
                Status = "29";

            } else if (Step.equals("1")) {
                if (!HttEntrustEntitys.getSubcontractLog().equals("29")) {
                    throw new Exception("不是已生产状态不可以撤销已生产!");
                }
                Info = "撤销开始生产";
                if (HttEntrustEntitys.getSubcontractTarget().equals("0")) {
                    Status = "24";

                } else {
                    Status = "10";
                }

            }

            psUpdateStatus.setObject(1, Status);
            psUpdateStatus.setObject(2, SubNo);
            psUpdateStatus.setObject(3, Seq);
            psUpdateStatus.addBatch();
            psUpdateStatus.executeBatch();
            // endregion

			/*
			 * patAddProcess.setObject(1,SubNo);
			 * patAddProcess.setObject(2,SubNo);
			 * patAddProcess.setObject(3,Info); patAddProcess.setObject(4,Name);
			 * patAddProcess.setObject(5,"");
			 * patAddProcess.setObject(6,HttEntrustEntitys.getSubcontractLog());
			 * patAddProcess.setObject(7,Status); patAddProcess.addBatch();
			 *
			 * patAddProcess.executeBatch();
			 */

            core.setV_errMsg("成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 下发
     */
    public CoreReturnObject Down(String flag, String SubNo, String Seq) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            String sqlUpdateStatus = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.Down");
            PreparedStatement psUpdateStatus = connection
                    .prepareStatement(sqlUpdateStatus);

            psUpdateStatus.setObject(1, flag);
            psUpdateStatus.setObject(2, SubNo);
            psUpdateStatus.setObject(3, Seq);
            psUpdateStatus.addBatch();
            psUpdateStatus.executeBatch();

            core.setV_errMsg("成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;

    }

    /**
     * 委托流程
     *
     * @param SubNos
     * @param ApprovalNo
     * @param CurrentStatus
     * @param ApprovalType
     * @param Note
     * @param Name
     * @return
     */
    public CoreReturnObject Approval(String SubNos, String ApprovalNo,
                                     String CurrentStatus, String ApprovalType, String Note, String Name) {

        CoreReturnObject core = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务

            core.setV_errMsg("操作成功！");
            core.setResult(1);
            connection.commit();
        } catch (Exception e) {
            core.setV_errMsg(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e2) {
            }
        }
        return core;
    }

    /**
     * 获取接箍离线库存 --- 接箍未写离线编号 只能通过炉批组 按前几条数据更新
     *
     * @return
     * @throws Exception
     */
    private String GetJGOfflieMatEntity(Connection connection,
                                        String JudgeStoveNo, String BatchNo, String GroupNo, String Count)
            throws Exception {
        List<HttEntrustEntity> HttEntrustEntity = null;
        String MatNo = "";

        String sqlMatNo = CoreXmlSqlParsersFactory
                .getSql("frmEntrust.GetJGOfflieMatEntity");

        PreparedStatement psta = connection.prepareStatement(sqlMatNo);
        psta.setObject(1, JudgeStoveNo);
        psta.setObject(2, BatchNo);
        psta.setObject(3, GroupNo);
        psta.setObject(4, Count);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            MatNo = rs.getString("MAT_NO");

        }

        rs.close();
        psta.close();
        return MatNo;
    }

    /**
     * 返线交库
     *
     * @param parm  1
     * @param parm1
     * @return
     */
    public CoreReturnObject DoReturn(String parm, ArrayList<String> parm1) {
        CoreReturnObject cor = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PhosphateResultService pho = new PhosphateResultService();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String systime = dateFormat.format(now);
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        String isCpjg = "0"; // 是否有成品加工项目
        String proNum = ""; // 磷化个数
        String woId = ""; // 工单号
        String heatPlanNo = ""; // 炉计划ID
        String returnFlag = ""; // 返库标识
        try {
            con.setAutoCommit(false); // 取消自动提交事务
            String[] array = {"0", "0", "1"};
            ArrayList<Object> list1 = new ArrayList<Object>();
            ArrayList<Object> resultList = new ArrayList<Object>(Arrays
                    .asList(array));
            Collections.addAll(resultList, array);

            String strResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.updateHttEntrustResult");// 更新委外实绩返库标识
            PreparedStatement pstaResult = con.prepareStatement(strResult);

            HttEntrustResultEntity jgOffline = EntityTool.getEntityByJSONStr(
                    parm, HttEntrustResultEntity.class);
            PhosphateResult result = new PhosphateResult();

            sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryHttEntrustResult");// 查询委托实绩
            psta = con.prepareStatement(sql);
            psta.setString(1, jgOffline.getSubcontractNo());
            psta.setString(2, jgOffline.getResultNo());
            rs = psta.executeQuery();
            if (rs.next()) {
                isCpjg = rs.getString("isCpjg");
                returnFlag = rs.getString("RETURN_FLAG");
                woId = rs.getString("WO_ID");
                heatPlanNo = rs.getString("HEAT_PLAN_NO");
            }
            rs.close();
            psta.close();
            if (isCpjg.equals("0")) {
                cor.setV_errMsg("此炉没有成口加工项目，不能返线交库!");
                return cor;
            }
            if (returnFlag.equals("1")) {
                cor.setV_errMsg("已返线交库，不能重复返线交库!");
                return cor;
            }
            if (woId.equals("")) {
                cor.setV_errMsg("未找到工单号，不能返线交库!");
                return cor;
            }
            result.setWoId(woId);
            result.setPlineCode(parm1.get(0));
            result.setColUser(parm1.get(1));
            result.setColShft(parm1.get(2));
            result.setColGroup(parm1.get(3));
            result.setColCount(jgOffline.getProNum());// 磷化个数
            result.setSprayCount(jgOffline.getProNum());
            result.setCreateTime(systime);
            result.setRemark("返线交库");
            result.setPlanNo(heatPlanNo);
            cor = pho.addPhosphateResult(con, cor, result, list1, "700310",
                    "700311", resultList, "0", woId, "0"); // 新增磷化检测实绩交库
            if (!cor.getV_errMsg().equals("")) {
                return cor;
            }

            // 更新委外实绩返库标识
            pstaResult.setObject(1, "1");
            pstaResult.setObject(2, jgOffline.getSubcontractNo());
            pstaResult.setObject(3, jgOffline.getResultNo());
            pstaResult.addBatch();
            pstaResult.executeBatch();

            cor.setV_errMsg("返库成功！");
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (con != null) {
                try {
                    cor.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }
        return cor;
    }

    /**
     * 撤销返库
     *
     * @param parm
     * @param parm1
     * @return
     */
    public CoreReturnObject DoReturnBack(String parm, ArrayList<String> parm1) {
        CoreReturnObject cor = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PhosphateResultService pho = new PhosphateResultService();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String systime = dateFormat.format(now);
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        String isCpjg = "0"; // 是否有成品加工项目
        String proNum = ""; // 磷化个数
        String woId = ""; // 工单号
        String returnFlag = ""; // 返库标识
        String resultNo = ""; // 磷化实绩编号
        try {
            con.setAutoCommit(false); // 取消自动提交事务
            String strResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.updateHttEntrustResult");// 更新委外实绩返库标识
            PreparedStatement pstaResult = con.prepareStatement(strResult);

            HttEntrustResultEntity jgOffline = EntityTool.getEntityByJSONStr(
                    parm, HttEntrustResultEntity.class);

            sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryHttEntrustResult");// 查询委托实绩
            psta = con.prepareStatement(sql);
            psta.setString(1, jgOffline.getSubcontractNo());
            psta.setString(2, jgOffline.getResultNo());
            rs = psta.executeQuery();
            if (rs.next()) {
                isCpjg = rs.getString("isCpjg");
                returnFlag = rs.getString("RETURN_FLAG");
                woId = rs.getString("WO_ID");
            }
            rs.close();
            psta.close();
            if (isCpjg.equals("0")) {
                cor.setV_errMsg("此炉没有成口加工项目，不能撤销返线交库!");
                return cor;
            }
            if (returnFlag.equals("0")) {
                cor.setV_errMsg("未返线交库，不能撤销返线交库!");
                return cor;
            }
            sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryCouplingPhosphateResult");// 查询返库的磷化实绩
            psta = con.prepareStatement(sql);
            psta.setString(1, woId);
            psta.setString(2, jgOffline.getProNum());
            rs = psta.executeQuery();
            if (rs.next()) {
                resultNo = rs.getString("RESULT_NO");
            }
            rs.close();
            psta.close();
            ArrayList<Object> list = new ArrayList<Object>();
            ArrayList<Object> list1 = new ArrayList<Object>();
            list.add(resultNo);
            list.add(jgOffline.getProNum());
            list1.add(list);

            cor = pho.deletePhosphateResult(con, cor, list1, woId); // 删除磷化检测实绩交库
            if (!cor.getV_errMsg().equals("")) {
                return cor;
            }

            // 更新委外实绩返库标识
            pstaResult.setObject(1, "0");
            pstaResult.setObject(2, jgOffline.getSubcontractNo());
            pstaResult.setObject(3, jgOffline.getResultNo());
            pstaResult.addBatch();
            pstaResult.executeBatch();

            cor.setV_errMsg("撤销返库成功！");
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (con != null) {
                try {
                    cor.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }
        return cor;
    }

    /**
     * 拆分接箍外委单
     *
     * @param parm
     * @param parm1
     * @return
     */
    public CoreReturnObject Split(String parm, ArrayList<String> parm1) {
        CoreReturnObject cor = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        String subcontractLog = ""; //委托单状态

        String proNum = parm1.get(3); // 拆分个数
        try {
            con.setAutoCommit(false); // 取消自动提交事务
            String strResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.Split");// 拆分接箍外委单
            PreparedStatement pstaResult = con.prepareStatement(strResult);

            HttEntrustEntity jgOffline = EntityTool.getEntityByJSONStr(
                    parm, HttEntrustEntity.class);

            sql = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.QueryHttEntrust");// 查询通用委托单信息
            psta = con.prepareStatement(sql);
            psta.setString(1, jgOffline.getSubcontractNo());
            psta.setString(2, jgOffline.getSubcontractNoSeq());
            rs = psta.executeQuery();
            if (rs.next()) {
                subcontractLog = rs.getString("SUBCONTRACT_LOG");
            }
            rs.close();
            psta.close();
            if (Integer.parseInt(subcontractLog) > 30) {
                cor.setV_errMsg("回报完毕的委托单不能拆分!");
                return cor;
            }

            // 拆分接箍外委单
            pstaResult.setObject(1, jgOffline.getSubcontractNo());
            pstaResult.setObject(2, jgOffline.getSubcontractNoSeq());
            pstaResult.setObject(3, proNum);
            pstaResult.addBatch();
            pstaResult.executeBatch();

            cor.setV_errMsg("拆分成功！");
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (con != null) {
                try {
                    cor.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }
        return cor;
    }

    /**
     * 撤销拆分接箍外委单
     *
     * @param parm
     * @return
     */
    public CoreReturnObject CancelSplit(String parm) {
        CoreReturnObject cor = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;

        try {
            con.setAutoCommit(false); // 取消自动提交事务
            String strResult = CoreXmlSqlParsersFactory
                    .getSql("frmEntrust.CancelSplit");// 撤销拆分接箍外委单
            PreparedStatement pstaResult = con.prepareStatement(strResult);
            HttEntrustEntity jgOffline = EntityTool.getEntityByJSONStr(
                    parm, HttEntrustEntity.class);
            // 撤销拆分接箍外委单
            pstaResult.setObject(1, jgOffline.getSubcontractNo());
            pstaResult.setObject(2, jgOffline.getSubcontractNoSeq());
            pstaResult.setObject(3, jgOffline.getSubcontractNum());
            pstaResult.setObject(4, jgOffline.getSubcontractWt());
            pstaResult.addBatch();
            pstaResult.executeBatch();

            cor.setV_errMsg("撤销拆分成功！");
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (con != null) {
                try {
                    cor.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }
        return cor;
    }

}
