package com.steering.pss.plnsaleord.jggxpln;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import net.sf.json.JSONObject;

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

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.jggxpln.model.MatZcMEntity;
import com.steering.pss.plnsaleord.jggxpln.model.PlnGxJgMEntity;
import com.steering.pss.plnsaleord.jggxpln.model.PlnZyJgEntity;
import com.steering.pss.plnsaleord.jggxpln.model.PlnZyJgReadyEntity;
import com.steering.pss.plnsaleord.order.CorePlnOrdJgDjDeal;

/**
 * 接箍作业工单计划
 * @author xiaohai
 * @date 2016-06-15
 */
public class CoreJgMPlnZy extends DBCommon {
    /**
     * 查询接箍产线
     * @return
     */
    public CoreReturnObject getJgPine() {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory.getSql("CoreJgMPlnZy.getJgPine");
        cro = this.getData(sql);
        return cro;
    }

    /**
     * 查询工序订单订单号
     * @return
     */
    public CoreReturnObject queryJgGxMNo() {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreJgMPlnZy.queryJgGxMNo");
        return cro;
    }

    /**
     * 查询接箍产线
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getPlnGxJgMStatus(String proPlanId, String jgGroupId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.getPlnGxJgMStatus");
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询接箍订单信息
     * @param params
     * @return
     */
    public CoreReturnObject queryGxJgM(ArrayList<String> params) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory.getSql("CoreJgMPlnZy.queryGxJgM");
        cro = this.getData(sql, params.toArray());
        return cro;
    }

    /**
     * 查询接箍作业计划
     * @param params
     * @return
     */
    public CoreReturnObject queryPlnZyJg(String proPlanId, String jgGroupId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.queryPlnZyJg");
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询接箍对应备料码
     * @param codeJg
     * @param custAlphaNo
     * @param alphaCode
     * @return
     */
    public CoreReturnObject getPlnJgMBlCode(String codeJg, String custAlphaNo,
            String alphaCode) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.getPlnJgMBlCode");
        cro = this
                .getData(sql, new Object[] { codeJg, custAlphaNo, alphaCode });
        return cro;
    }

    /**
     * 查询接箍订单产线
     * @param codeJg
     * @param codeBl
     * @return
     */
    public CoreReturnObject getPlnJgMPine(String codeJg, String codeBl) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.getPlnJgMPine");
        sql += " ORDER BY T.PRD_RATE DESC, T.WASTE_RATE ASC";
        cro = this.getData(sql, new Object[] { codeBl, codeJg });
        return cro;
    }

    /**
     * 更新接箍订单
     * @param list
     * @return
     */
    public CoreReturnObject doModifyJgM(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updateJgMBlPl");
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            for (String jgMStr : list) {
                PreparedStatement ps = null;
                JSONObject json = JSONObject.fromObject(jgMStr);
                PlnGxJgMEntity jgGxM = (PlnGxJgMEntity) JSONObject.toBean(json,
                        PlnGxJgMEntity.class);
                String[] blMaterial = null;

                blMaterial = CorePlnOrdJgDjDeal.getBlMaterial(conn,
                        jgGxM.getCodeJgBl());
                if (blMaterial != null) {
                    jgGxM.setBlWlId(blMaterial[0]);
                    jgGxM.setBlWlDesc(blMaterial[1]);
                }

                // 接箍订单属性明细表回写备料码
                CoreJgMBlOrd.updateJgMPropBl(conn, jgGxM.getCodeJgBl(),
                        jgGxM.getProPlanId());

                ps = conn.prepareStatement(sql);
                ps.setObject(1, jgGxM.getCodeJgBl());
                ps.setObject(2, jgGxM.getBlWlId());
                ps.setObject(3, jgGxM.getBlWlDesc());
                ps.setObject(4, jgGxM.getPlineCode());
                ps.setObject(5, jgGxM.getPlineName());
                ps.setObject(6, jgGxM.getProPlanId());
                ps.executeUpdate();
                ps.close();
                conn.commit();
            }
            cro.setResult("操作成功！");
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 查询基础信息表
     * @param sortCode
     * @return
     */
    public CoreReturnObject queryBaseSort(String sortCode) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreJgMPlnZy.queryBaseSort",
                new Object[] { sortCode });
        return cro;
    }

    /**
     * 获取接箍订单备料需求号
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getJgMBlReq(String proPlanId) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreJgMPlnZy.getJgMBlReq",
                new Object[] { proPlanId });
        return cro;
    }

    /**
     * 查询接箍订单分组备料已出库长度
     * @param proPlanId
     * @param jgGroupId
     * @return
     */
    public CoreReturnObject queryPlnPropLenSum(String proPlanId,
            String jgGroupId) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreJgMPlnZy.queryPlnPropLenSum",
                new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询接箍订单分组备料已出库长度
     * @param proPlanId
     * @param jgGroupId
     * @param zyPlanId
     * @return
     */
    public CoreReturnObject queryPlnPropLenSum(String proPlanId,
            String jgGroupId, String zyPlanId) {
        CoreReturnObject cro = null;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.queryPlnPropLenSum");
        sql += " AND T.COUPCUT_BATCH_ID != '" + zyPlanId + "'";
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询接箍订单接箍料炉批
     * @param proPlanId
     * @return
     */
    public CoreReturnObject selectJgMStoverBatch(String proPlanId,
            String jgGroupId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectJgMStoverBatch");
        sql += " AND T.ACT_DIMATER > J.MIN_D_CP AND T.ACT_HEIGHT < J.MAX_D_CP"
                + " GROUP BY T.JUDGE_STOVE_NO, T.BATCH_NO, T.BATCH_GROUD_NO";
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询接箍订单接箍料炉批
     * @param proPlanId
     * @param jgMBlReq
     * @return
     */
    public CoreReturnObject selectJgMStoverBatch(String proPlanId,
            String jgGroupId, String jgMBlReq) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectJgMStoverBatch");
        sql += " AND T.REQ_BL_ID = '" + jgMBlReq + "'";
        sql += " GROUP BY T.JUDGE_STOVE_NO, T.BATCH_NO, T.BATCH_GROUD_NO";
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询炉次计划接箍料炉批
     * @param zyPlanId
     * @return
     */
    public CoreReturnObject selectJgMBatchGroupModify(String zyPlanId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectJgMBatchGroupModify");
        sql += " AND T.ACT_DIMATER > J.MIN_D_CP AND T.ACT_HEIGHT < J.MAX_D_CP"
                + " GROUP BY T.JUDGE_STOVE_NO, T.BATCH_NO, T.BATCH_GROUD_NO";
        cro = this.getData(sql, new Object[] { zyPlanId });
        return cro;
    }

    /**
     * 查询炉次计划接箍料炉批
     * @param zyPlanId
     * @param jgMBlReq
     * @return
     */
    public CoreReturnObject selectJgMBatchGroupModify(String zyPlanId,
            String jgMBlReq) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectJgMBatchGroupModify");
        sql += " AND T.REQ_BL_ID = '" + jgMBlReq + "'";
        sql += " GROUP BY T.JUDGE_STOVE_NO, T.BATCH_NO, T.BATCH_GROUD_NO";
        cro = this.getData(sql, new Object[] { zyPlanId });
        return cro;
    }

    /**
     * 查询钢管生产物料主表
     * @param proPlanId
     * @return
     */
    public CoreReturnObject selectMatZcM(String proPlanId, String jgGroupId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectMatZcM");
        sql += " AND T.ACT_DIMATER > J.MIN_D_CP AND T.ACT_HEIGHT < J.MAX_D_CP";
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 查询钢管生产物料主表
     * @param proPlanId
     * @param jgMBlReq
     * @return
     */
    public CoreReturnObject selectMatZcM(String proPlanId, String jgGroupId,
            String jgMBlReq) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.selectMatZcM");
        sql += " AND T.REQ_BL_ID = '" + jgMBlReq + "'";
        cro = this.getData(sql, new Object[] { proPlanId, jgGroupId });
        return cro;
    }

    /**
     * 接箍订单出库，作业批次
     * @param list
     * @return
     */
    public CoreReturnObject outBound(ArrayList<PlnZyJgEntity> list,
            String proPlanId, String jgGroupId) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            String message = "";
            String reqBlId = "";
            PreparedStatement pst = null;
            ResultSet rst = null;
            int groupNum = 0;
            double groupWt = 0;
            double lenJg = 0;

            int matchNumBl = 0;// 接箍料利库支数
            double matchWtBl = 0;// 接箍料利库重量
            int batchedNum = 0;// 炉计划投料支数
            double batchedWt = 0;// 炉计划投料重量

            String demandDetection = "";// 探伤要求（408401）
            String demandBonderizing = "";// 磷化镀铜要求（408402）
            String demandCopper = "";// 压印喷标
            String demandBlast = "";// 喷砂要求
            String sqlUpMat = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updateMatZgM");
            String sqlUpProp = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.udpdateGxJgPropBatch");
            String sqlAddZy = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.addPlnZyJg");
            String sqlAddZyReady = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.addPlnZyJgReady");
            String sqlQ = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.getPlnGxJgMStatus");

            pst = conn.prepareStatement(sqlQ);
            pst.setObject(1, proPlanId);
            pst.setObject(2, jgGroupId);
            rst = pst.executeQuery();
            if (!rst.next()) {
                message = "未找到该接箍订单分组。";
                cro.setResult(message);
                return cro;
            }
            lenJg = rst.getDouble("LENGTH_JG");
            if (lenJg <= 0.00001) {
                message = "订单接箍长度未知。";
                cro.setResult(message);
                return cro;
            }
            if (rst.getString("DEMAND_DETECTION") != null) {
                demandDetection = rst.getString("DEMAND_DETECTION");
            }
            if (rst.getString("DEMAND_BONDERIZING") != null) {
                demandBonderizing = rst.getString("DEMAND_BONDERIZING");
            }
            if (rst.getString("DEMAND_COPPER") != null) {
                demandCopper = rst.getString("DEMAND_COPPER");
            }
            if (rst.getString("DEMAND_BLAST") != null) {
                demandBlast = rst.getString("DEMAND_BLAST");
            }
            matchNumBl = rst.getInt("MATCHNUM_BL");// 接箍料利库支数
            matchWtBl = rst.getDouble("MATCHWT_BL");// 接箍料利库重量
            batchedNum = rst.getInt("BATCHED_NUM");// 炉计划投料支数
            batchedWt = rst.getDouble("BATCHED_WT");// 炉计划投料重量
            rst.close();
            pst.close();

            sqlQ = CoreXmlSqlParsersFactory.getSql("CoreJgMPlnZy.getJgMBlReq");
            pst = conn.prepareStatement(sqlQ);
            pst.setObject(1, proPlanId);
            rst = pst.executeQuery();
            if (rst.next()) {
                if (rst.getString("REQ_BL_ID") != null) {
                    reqBlId = rst.getString("REQ_BL_ID");
                }
            }
            rst.close();
            pst.close();

            for (PlnZyJgEntity zyJgEntity : list) {
                int matNum = 0;
                int planNum = 0;
                double planWt = 0;
                int numJg = 0;
                String sqlAdd = "";
                String zyPlanId = "";
                String matNo = "";// 其中一支材料号
                PreparedStatement psta = null;
                ResultSet rsta = null;
                PlnZyJgReadyEntity zyJgReadyEntity = new PlnZyJgReadyEntity();
                ArrayList<MatZcMEntity> listMatZc = new ArrayList<MatZcMEntity>();
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreJgMPlnZy.queryPlnZyJg");

                matNum = Integer.parseInt(zyJgEntity.getPlanBlNum());
                if (matNum <= 0) {
                    continue;
                }

                zyPlanId = getZyJgPlanId(conn);
                if (zyPlanId.trim().equals("")) {
                    message = "炉作业计划号生产出错。";
                    try {
                        conn.rollback();
                    }
                    catch (SQLException e) {
                        e.printStackTrace();
                    }
                    cro.setResult(message);
                    return cro;
                }

                // 查询有无此炉批组，已经组炉
                psta = conn.prepareStatement(sql);
                psta.setObject(1, proPlanId);
                psta.setObject(2, jgGroupId);
                rsta = psta.executeQuery();
                while (rsta.next()) {
                    if (rsta.getString("JUDGE_STOVE_NO") != null
                            && rsta.getString("BATCH_NO") != null
                            && rsta.getString("BATCH_GROUD_NO") != null
                            && rsta.getString("JUDGE_STOVE_NO").equals(
                                    zyJgEntity.getJudgeStoveNo())
                            && rsta.getString("BATCH_NO").equals(
                                    zyJgEntity.getBatchNo())
                            && rsta.getString("BATCH_GROUD_NO").equals(
                                    zyJgEntity.getBatchGroudNo())) {
                        message = "炉号:" + zyJgEntity.getJudgeStoveNo() + " 批号："
                                + zyJgEntity.getBatchNo() + " 组号："
                                + zyJgEntity.getBatchGroudNo()
                                + "的炉作业计划已存在，请刷新数据。";
                        try {
                            conn.rollback();
                        }
                        catch (SQLException e) {
                            e.printStackTrace();
                        }
                        cro.setResult(message);
                        return cro;
                    }
                }
                rsta.close();
                psta.close();

                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreJgMPlnZy.selectGroupMatZcM");
                if (reqBlId.trim().equals("")) {
                    sql += " AND T.ACT_DIMATER > J.MIN_D_CP AND T.ACT_HEIGHT < J.MAX_D_CP";
                }
                else {
                    sql += " AND T.REQ_BL_ID = '" + reqBlId + "'";
                }
                sql += " ORDER BY T.MAT_NO ASC";
                psta = conn.prepareStatement(sql);
                psta.setObject(1, proPlanId);
                psta.setObject(2, zyJgEntity.getJudgeStoveNo());
                psta.setObject(3, zyJgEntity.getBatchNo());
                psta.setObject(4, zyJgEntity.getBatchGroudNo());
                rsta = psta.executeQuery();
                listMatZc = EntityTool.getEntitysByRs(rsta, MatZcMEntity.class);
                if (listMatZc == null || listMatZc.size() == 0) {
                    message = "炉号:" + zyJgEntity.getJudgeStoveNo() + " 批号："
                            + zyJgEntity.getBatchNo() + " 组号："
                            + zyJgEntity.getBatchGroudNo() + "下没有合适的材料。";
                    try {
                        conn.rollback();
                    }
                    catch (SQLException e) {
                        e.printStackTrace();
                    }
                    cro.setResult(message);
                    return cro;
                }
                matNo = listMatZc.get(0).getMatNo();
                for (MatZcMEntity matZcMEntity : listMatZc) {
                    PreparedStatement ps = null;
                    double actLen = 0;
                    int matNumJg = 0;
                    String sqlUp = "";

                    // 到指定支数跳出
                    if (planNum >= matNum) {
                        break;
                    }
                    actLen = Double.parseDouble(matZcMEntity.getActLen());
                    if (actLen * 1000 < lenJg) {
                        continue;
                    }
                    planWt += Double.parseDouble(matZcMEntity.getActWeight());
                    planNum += 1;

                    matNumJg = (int) Math.floor(actLen * 1000 / lenJg);
                    numJg += matNumJg;

                    // 出库操作
                    matZcMEntity.setMatStatus("80150103");
                    matZcMEntity.setProOrderId(proPlanId);
                    matZcMEntity.setGxPlanNo(jgGroupId);
                    matZcMEntity.setIfBatchedJg("1");
                    matZcMEntity.setCoupcutBatchId(zyPlanId);

                    sqlUp = EntityTool.fillSqlByEntity(sqlUpMat, matZcMEntity);
                    ps = conn.prepareStatement(sqlUp);
                    ps.executeUpdate();
                    ps.close();
                }
                rsta.close();
                psta.close();

                groupNum += planNum;
                groupWt += planWt;

                zyJgEntity.setZyPlanId(zyPlanId);
                zyJgEntity.setPlanJgNum(String.valueOf(numJg));
                zyJgEntity.setPlanBlNum(String.valueOf(planNum));
                zyJgEntity.setPlanBlWt(String.valueOf(planWt));
                zyJgEntity.setPlanCutNum(String.valueOf(numJg));
                zyJgEntity.setIfNeedCjg("0");
                zyJgEntity.setPlanCjgNum(String.valueOf(0));
                zyJgEntity.setPlanLatheNum(String.valueOf(numJg));

                zyJgReadyEntity.setProPlanId(proPlanId);
                zyJgReadyEntity.setJgGroupId(jgGroupId);
                zyJgReadyEntity.setJudgeStoveNo(zyJgEntity.getJudgeStoveNo());
                zyJgReadyEntity.setBatchNo(zyJgEntity.getBatchNo());
                zyJgReadyEntity.setBatchGroudNo(zyJgEntity.getBatchGroudNo());
                zyJgReadyEntity.setReqBlId(reqBlId);
                if (reqBlId.trim().equals("")) {
                    zyJgReadyEntity.setIfMatchOdd("1");
                }
                else {
                    zyJgReadyEntity.setIfMatchOdd("0");
                }
                zyJgReadyEntity.setIfDoHeatPlan("1");
                zyJgReadyEntity.setAllotNum(String.valueOf(planNum));
                zyJgReadyEntity.setAllotWt(String.valueOf(planWt));
                                
                // 探伤
                if (demandDetection.trim().equals("40840101")) {
                    zyJgEntity.setPlanDetectNum(String.valueOf(numJg));
                }
                else {
                    zyJgEntity.setPlanDetectNum(String.valueOf(0));
                }

                // 磷化镀铜
                if (demandBonderizing.trim().equals("40840201")) {
                    // 磷化
                    zyJgEntity.setCoatType("磷化");
                    zyJgEntity.setIfPhosphating("1");
                    zyJgEntity.setPlanPhosNum(String.valueOf(numJg));
                }
                else {
                    zyJgEntity.setIfPhosphating("0");
                    zyJgEntity.setPlanPhosNum(String.valueOf(0));
                }

                // 磷化镀铜
                if (demandBonderizing.trim().equals("40840202")) {
                    // 镀铜
                    zyJgEntity.setCoatType("镀铜");
                    zyJgEntity.setIfPlateCu("1");
                    zyJgEntity.setPlanPltcuNum(String.valueOf(numJg));
                }
                else {
                    zyJgEntity.setIfPlateCu("0");
                    zyJgEntity.setPlanPltcuNum(String.valueOf(0));
                }

                // 压印、喷标
                if (demandCopper.trim().equals("40840303")) {
                    zyJgEntity.setIfImpress("1");
                    zyJgEntity.setPlanImpressNum(String.valueOf(numJg));
                    zyJgEntity.setIfCopper("1");
                    zyJgEntity.setPlanCopperNum(String.valueOf(numJg));
                }
                else if (demandCopper.trim().equals("40840302")) {
                    zyJgEntity.setIfImpress("0");
                    zyJgEntity.setPlanImpressNum(String.valueOf(0));
                    zyJgEntity.setIfCopper("1");
                    zyJgEntity.setPlanCopperNum(String.valueOf(numJg));
                }
                else if (demandCopper.trim().equals("40840301")) {
                    zyJgEntity.setIfImpress("1");
                    zyJgEntity.setPlanImpressNum(String.valueOf(numJg));
                    zyJgEntity.setIfCopper("0");
                    zyJgEntity.setPlanCopperNum(String.valueOf(0));
                }
                else {
                    zyJgEntity.setIfImpress("0");
                    zyJgEntity.setPlanImpressNum(String.valueOf(0));
                    zyJgEntity.setIfCopper("0");
                    zyJgEntity.setPlanCopperNum(String.valueOf(0));
                }

                // 喷砂
                if (demandBlast.trim().equals("40840401")) {
                    zyJgEntity.setIfBlast("1");
                    zyJgEntity.setPlanBlastNum(String.valueOf(numJg));
                }
                else {
                    zyJgEntity.setIfBlast("0");
                    zyJgEntity.setPlanBlastNum(String.valueOf(0));
                }

                // 新增接箍炉炉次计划：
                sqlAdd = EntityTool.fillSqlByEntity(sqlAddZy, zyJgEntity);
                psta = conn.prepareStatement(sqlAdd);
                psta.setObject(1, matNo);
                psta.setObject(2, proPlanId);
                psta.setObject(3, jgGroupId);
                psta.executeUpdate();
                psta.close();
                
                sqlAdd = EntityTool.fillSqlByEntity(sqlAddZyReady,
                        zyJgReadyEntity);
                psta = conn.prepareStatement(sqlAdd);
                psta.setObject(1, matNo);
                psta.setObject(2, proPlanId);
                psta.setObject(3, jgGroupId);
                psta.executeUpdate();
                psta.close();
            }

            if (!reqBlId.trim().equals("")) {
                batchedNum += groupNum;
                batchedWt += groupWt;
            }
            else {
                matchNumBl += groupNum;
                matchWtBl += groupWt;
                batchedNum += groupNum;
                batchedWt += groupWt;
            }

            // 回写出库支数
            pst = conn.prepareStatement(sqlUpProp);
            pst.setObject(1, matchWtBl);
            pst.setObject(2, matchNumBl);
            pst.setObject(3, batchedWt);
            pst.setObject(4, batchedNum);
            pst.setObject(5, proPlanId);
            pst.setObject(6, jgGroupId);
            pst.executeUpdate();
            pst.close();

            cro.setResult("组炉成功！");
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 生成接箍炉作业批次号
     * @param conn
     * @return
     * @throws SQLException
     */
    public static String getZyJgPlanId(Connection conn) throws SQLException {
        String planId = "";
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreJgMPlnZy.getZyJgPlanId");
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        if (rs.next()) {
            if (rs.getString("ZY_PLAN_ID") != null) {
                planId = rs.getString("ZY_PLAN_ID");
            }
        }
        rs.close();
        ps.close();
        return planId;
    }

    /**
     * 取消炉次计划：
     * @param list
     * @return
     */
    public CoreReturnObject canCelJgZy(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            ArrayList<String> message = new ArrayList<String>(0);
            String sqlUpMat = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updateMatZgM");
            String sqlUpProp = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.udpdateGxJgPropBatch");
            String sqlDelZy = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.deleteZyJg");
            String sqlDelZyReady = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.deleteZyJgReady");
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            for (String zyPlanId : list) {
                PreparedStatement ps = null;
                ResultSet rs = null;
                PlnZyJgEntity zyJgEntity = null;
                double addBatchWt = 0;
                int addBatchNum = 0;
                double addMatchWt = 0;
                int addMatchNum = 0;
                String sqlJgProp = CoreXmlSqlParsersFactory
                        .getSql("CoreJgMPlnZy.getPlnGxJgMStatus");
                String sqlMat = CoreXmlSqlParsersFactory
                        .getSql("CoreJgMPlnZy.selectJgZyMat");
                String sqlQ = CoreXmlSqlParsersFactory
                        .getSql("CoreJgMPlnZy.selectJgZyStatus");

                ps = conn.prepareStatement(sqlQ);
                ps.setObject(1, zyPlanId);
                rs = ps.executeQuery();
                zyJgEntity = EntityTool.getEntityByRs(rs, PlnZyJgEntity.class);
                if (zyJgEntity == null) {
                    message.add("未找到炉次计划：" + zyPlanId + "。");
                    continue;
                }
                if (!zyJgEntity.getZyPlanStatus().trim().equals("0")) {
                    message.add("炉次计划：" + zyPlanId + "不在计划状态。");
                    continue;
                }
                rs.close();
                ps.close();

                ps = conn.prepareStatement(sqlMat);
                ps.setObject(1, zyPlanId);
                ps.setObject(2, zyJgEntity.getProPlanId());
                ps.setObject(3, zyJgEntity.getJgGroupId());
                rs = ps.executeQuery();
                while (rs.next()) {
                    String sqlUp = "";
                    PreparedStatement pst = null;
                    MatZcMEntity matZcMEntity = new MatZcMEntity();
                    addBatchNum++;
                    addBatchWt += rs.getDouble("ACT_WEIGHT");

                    if (rs.getString("REQ_BL_ID") == null
                            || rs.getString("REQ_BL_ID").trim().equals("")) {
                        addMatchNum++;
                        addMatchWt += rs.getDouble("ACT_WEIGHT");
                    }

                    // 清楚出库标识
                    matZcMEntity.setMatNo(rs.getString("MAT_NO"));
                    matZcMEntity.setMatStatus("80150102");
                    matZcMEntity.setProOrderId("");
                    matZcMEntity.setGxPlanNo("");
                    matZcMEntity.setIfBatchedJg("0");
                    matZcMEntity.setCoupcutBatchId("");

                    sqlUp = EntityTool.fillSqlByEntity(sqlUpMat, matZcMEntity);
                    pst = conn.prepareStatement(sqlUp);
                    pst.executeUpdate();
                    pst.close();
                }
                rs.close();
                ps.close();

                ps = conn.prepareStatement(sqlJgProp);
                ps.setObject(1, zyJgEntity.getProPlanId());
                ps.setObject(2, zyJgEntity.getJgGroupId());
                rs = ps.executeQuery();
                if (rs.next()) {
                    PreparedStatement pst = null;
                    int matchNumBl = rs.getInt("MATCHNUM_BL");// 接箍料利库支数
                    double matchWtBl = rs.getDouble("MATCHWT_BL");// 接箍料利库重量
                    int batchedNum = rs.getInt("BATCHED_NUM");// 炉计划投料支数
                    double batchedWt = rs.getDouble("BATCHED_WT");// 炉计划投料重量

                    matchNumBl -= addMatchNum;
                    matchWtBl -= addMatchWt;
                    batchedNum -= addBatchNum;
                    batchedWt -= addBatchWt;

                    // 回写出库支数
                    pst = conn.prepareStatement(sqlUpProp);
                    pst.setObject(1, matchWtBl);
                    pst.setObject(2, matchNumBl);
                    pst.setObject(3, batchedWt);
                    pst.setObject(4, batchedNum);
                    pst.setObject(5, zyJgEntity.getProPlanId());
                    pst.setObject(6, zyJgEntity.getJgGroupId());
                    pst.executeUpdate();
                    pst.close();
                }
                rs.close();
                ps.close();

                // 删除炉次计划：
                ps = conn.prepareStatement(sqlDelZy);
                ps.setObject(1, zyJgEntity.getZyPlanId());
                ps.executeUpdate();
                ps.close();

                // 删除接箍炉计划预排表
                ps = conn.prepareStatement(sqlDelZyReady);
                ps.setObject(1, zyJgEntity.getJudgeStoveNo());
                ps.setObject(2, zyJgEntity.getBatchNo());
                ps.setObject(3, zyJgEntity.getBatchGroudNo());
                ps.executeUpdate();
                ps.close();

                conn.commit();
            }
            if (message.size() > 0) {
                cro.setResult(list.size() - message.size() + "条工单撤销成功，"
                        + message.size() + "条工单撤销失败。\n" + message.get(0));
            }
            else {
                cro.setResult(list.size() + "条工单撤销成功，0条工单撤销失败。");
            }
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 炉次计划查询
     * @param zyPlanId
     * @return
     */
    public CoreReturnObject selectJgZyStatus(String zyPlanId) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreJgMPlnZy.selectJgZyStatus",
                new Object[] { zyPlanId });
        return cro;
    }

    /**
     * 修改炉次计划
     * @param zyJgEntity
     * @return
     */
    public CoreReturnObject modifyZy(PlnZyJgEntity zyJgEntity) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            PreparedStatement ps = null;
            ResultSet rs = null;
            PlnZyJgEntity zyJgStatusEntity = null;
            String sqlMat = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.selectJgZyMat");
            String sqlUpMat = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updateMatZgM");
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.selectJgZyStatus");
            String sqlUpProp = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.udpdateGxJgPropBatch");
            String sqlQ = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.getPlnGxJgMStatus");
            String sqlUpdateZy = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updatePlnZyJg");
            String sqlUpZyReady = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.updatePlnZyJgReady");

            double addBatchWt = 0;
            int addBatchNum = 0;
            double addMatchWt = 0;
            int addMatchNum = 0;

            double reduceBatchWt = 0;
            int reduceBatchNum = 0;
            double reduceMatchWt = 0;
            int reduceMatchNum = 0;

            double lenJg = 0;
            int matchNumBl = 0;// 接箍料利库支数
            double matchWtBl = 0;// 接箍料利库重量
            int batchedNum = 0;// 炉计划投料支数
            double batchedWt = 0;// 炉计划投料重量
            int numJg = 0;
            String reqBlId = "";
            String sqlUpZy = "";

            ArrayList<MatZcMEntity> listMatZc = new ArrayList<MatZcMEntity>();
            int modifyNum = Integer.parseInt(zyJgEntity.getPlanBlNum());

            ps = conn.prepareStatement(sql);
            ps.setObject(1, zyJgEntity.getZyPlanId());
            rs = ps.executeQuery();
            zyJgStatusEntity = EntityTool
                    .getEntityByRs(rs, PlnZyJgEntity.class);
            if (zyJgStatusEntity == null) {
                cro.setResult("未找到作业计划：" + zyJgEntity.getZyPlanId() + "，请刷新数据。");
                return cro;
            }
            rs.close();
            ps.close();

            if (zyJgStatusEntity.getZyPlanStatus().compareTo("2") > 0) {
                cro.setResult("作业计划：" + zyJgEntity.getZyPlanId() + "已经生产完毕了。");
                return cro;
            }
            if (zyJgStatusEntity.getZyPlanStatus().equals("2")) {
                if (zyJgStatusEntity.getPlanBlNum().compareTo(
                        zyJgEntity.getPlanBlNum()) >= 0) {
                    cro.setResult("作业计划：" + zyJgEntity.getZyPlanId()
                            + "已经在生产中，只能追加组炉支数。");
                    return cro;
                }
            }

            // 查询接箍订单分组
            ps = conn.prepareStatement(sqlQ);
            ps.setObject(1, zyJgStatusEntity.getProPlanId());
            ps.setObject(2, zyJgStatusEntity.getJgGroupId());
            rs = ps.executeQuery();
            if (!rs.next()) {
                cro.setResult("未找到炉次计划对应的接箍订单分组。");
                return cro;
            }
            lenJg = rs.getDouble("LENGTH_JG");
            if (lenJg <= 0.00001) {
                cro.setResult("订单接箍长度未知。");
                return cro;
            }
            matchNumBl = rs.getInt("MATCHNUM_BL");// 接箍料利库支数
            matchWtBl = rs.getDouble("MATCHWT_BL");// 接箍料利库重量
            batchedNum = rs.getInt("BATCHED_NUM");// 炉计划投料支数
            batchedWt = rs.getDouble("BATCHED_WT");// 炉计划投料重量
            rs.close();
            ps.close();

            // 查询接箍订单有没有做备料需求
            sql = CoreXmlSqlParsersFactory.getSql("CoreJgMPlnZy.getJgMBlReq");
            ps = conn.prepareStatement(sql);
            ps.setObject(1, zyJgStatusEntity.getProPlanId());
            rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getString("REQ_BL_ID") != null) {
                    reqBlId = rs.getString("REQ_BL_ID");
                }
            }
            rs.close();
            ps.close();

            // 清楚之前的出库
            ps = conn.prepareStatement(sqlMat);
            ps.setObject(1, zyJgStatusEntity.getZyPlanId());
            ps.setObject(2, zyJgStatusEntity.getProPlanId());
            ps.setObject(3, zyJgStatusEntity.getJgGroupId());
            rs = ps.executeQuery();
            while (rs.next()) {
                String sqlUp = "";
                PreparedStatement pst = null;
                MatZcMEntity matZcMEntity = new MatZcMEntity();
                reduceBatchNum++;
                reduceBatchWt += rs.getDouble("ACT_WEIGHT");

                if (rs.getString("REQ_BL_ID") == null
                        || rs.getString("REQ_BL_ID").trim().equals("")) {
                    reduceMatchNum++;
                    reduceMatchWt += rs.getDouble("ACT_WEIGHT");
                }

                // 清楚出库标识
                matZcMEntity.setMatNo(rs.getString("MAT_NO"));
                matZcMEntity.setMatStatus("80150102");
                matZcMEntity.setProOrderId("");
                matZcMEntity.setGxPlanNo("");
                matZcMEntity.setIfBatchedJg("0");
                matZcMEntity.setCoupcutBatchId("");

                sqlUp = EntityTool.fillSqlByEntity(sqlUpMat, matZcMEntity);
                pst = conn.prepareStatement(sqlUp);
                pst.executeUpdate();
                pst.close();
            }
            rs.close();
            ps.close();

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreJgMPlnZy.selectGroupMatZcM");
            if (reqBlId.trim().equals("")) {
                sql += " AND T.ACT_DIMATER > J.MIN_D_CP AND T.ACT_HEIGHT < J.MAX_D_CP";
            }
            else {
                sql += " AND T.REQ_BL_ID = '" + reqBlId + "'";
            }
            sql += " ORDER BY T.MAT_NO ASC";
            ps = conn.prepareStatement(sql);
            ps.setObject(1, zyJgStatusEntity.getProPlanId());
            ps.setObject(2, zyJgStatusEntity.getJudgeStoveNo());
            ps.setObject(3, zyJgStatusEntity.getBatchNo());
            ps.setObject(4, zyJgStatusEntity.getBatchGroudNo());
            rs = ps.executeQuery();
            listMatZc = EntityTool.getEntitysByRs(rs, MatZcMEntity.class);
            if (listMatZc == null || listMatZc.size() == 0) {
                try {
                    conn.rollback();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
                cro.setResult("炉号:" + zyJgStatusEntity.getJudgeStoveNo() + " 批号："
                        + zyJgStatusEntity.getBatchNo() + " 组号："
                        + zyJgStatusEntity.getBatchGroudNo() + "下没有合适的材料。");
                return cro;
            }
            rs.close();
            ps.close();

            for (MatZcMEntity matZcMEntity : listMatZc) {
                PreparedStatement pst = null;
                double actLen = 0;
                int matNumJg = 0;
                String sqlUp = "";
                // 到指定支数跳出
                if (addBatchNum >= modifyNum) {
                    break;
                }

                actLen = Double.parseDouble(matZcMEntity.getActLen());
                if (actLen * 1000 < lenJg) {
                    continue;
                }
                addBatchNum++;
                addBatchWt += Double.parseDouble(matZcMEntity.getActWeight());

                if (reqBlId.trim().equals("")) {
                    addMatchNum++;
                    addMatchWt += Double.parseDouble(matZcMEntity
                            .getActWeight());
                }

                matNumJg = (int) Math.floor(actLen * 1000 / lenJg);
                numJg += matNumJg;

                // 出库操作
                matZcMEntity.setMatStatus("80150103");
                matZcMEntity.setProOrderId(zyJgStatusEntity.getProPlanId());
                matZcMEntity.setGxPlanNo(zyJgStatusEntity.getJgGroupId());
                matZcMEntity.setIfBatchedJg("1");
                matZcMEntity.setCoupcutBatchId(zyJgStatusEntity.getZyPlanId());

                sqlUp = EntityTool.fillSqlByEntity(sqlUpMat, matZcMEntity);
                pst = conn.prepareStatement(sqlUp);
                pst.executeUpdate();
                pst.close();
            }

            // 回写出库支数
            matchNumBl = matchNumBl - reduceMatchNum + addMatchNum;
            matchWtBl = matchWtBl - reduceMatchWt + addMatchWt;
            batchedNum = batchedNum - reduceBatchNum + addBatchNum;
            batchedWt = batchedWt - reduceBatchWt + addBatchWt;
            ps = conn.prepareStatement(sqlUpProp);
            ps.setObject(1, matchWtBl);
            ps.setObject(2, matchNumBl);
            ps.setObject(3, batchedWt);
            ps.setObject(4, batchedNum);
            ps.setObject(5, zyJgStatusEntity.getProPlanId());
            ps.setObject(6, zyJgStatusEntity.getJgGroupId());
            ps.executeUpdate();
            ps.close();

            zyJgEntity.setPlanJgNum(String.valueOf(numJg));
            zyJgEntity.setPlanLatheNum(String.valueOf(numJg));
            zyJgEntity.setPlanCutNum(String.valueOf(numJg));
            zyJgEntity.setPlanBlNum(String.valueOf(addBatchNum));
            zyJgEntity.setPlanBlWt(String.valueOf(addBatchWt));

            sqlUpdateZy = sqlUpdateZy.replaceAll("'#PLAN_JG_NUM#'",
                    String.valueOf(numJg));
            sqlUpZy = EntityTool.fillSqlByEntity(sqlUpdateZy, zyJgEntity);
            ps = conn.prepareStatement(sqlUpZy);
            ps.executeUpdate();
            ps.close();
            
            //回写预排表支数
            ps = conn.prepareStatement(sqlUpZyReady);
            ps.setObject(1, addBatchNum);
            ps.setObject(2, addBatchWt);
            ps.setObject(3, zyJgStatusEntity.getJudgeStoveNo());
            ps.setObject(4, zyJgStatusEntity.getBatchNo());
            ps.setObject(5, zyJgStatusEntity.getBatchGroudNo());
            ps.executeUpdate();
            ps.close();

            cro.setResult("修改成功！");
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

}