package com.steering.pss.plnsaleord.orderManage;

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

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

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.orderManage.entity.SlmOrdDesignBomEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderDbkSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderJgxSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderRclSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderZgSEntity;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;

/**
 * BOM界面
 * @author peng
 */
public class FrmBomConfirm extends DBCommon {

    /**
     * 查询钢种及钢种索引码
     * @param weight
     * @return
     */
    public CoreReturnObject getQueryGrade(String[] groupCic) {
        CoreReturnObject cro = null;
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmBomConfirm.getQueryGrade");
        // 去除数组中的空格
        List<String> tmp = new ArrayList<String>();
        for (String str : groupCic) {
            if (str != null && str.length() != 0) {
                tmp.add(str.trim());
            }
        }
        groupCic = tmp.toArray(new String[0]);
        if (groupCic == null || groupCic.length == 0) {
            sql += " AND T.CIC =''";
        }
        sql += CoreConverter.toSqlConditionString("T.CIC", groupCic);
        cro = this.getData(sql);
        return cro;
    }

    /**
     * 查询交货行BOM
     * @param ordLnDlyPk
     * @return
     */
    public CoreReturnObject getBomByOrdLnDlyPk(String ordLnDlyPk) {
        return this.getDataBySqlID("FrmBomConfirm.getBomByOrdLnDlyPk",
                new Object[] { ordLnDlyPk });
    }
    /**
     *查询投入产出是否禁用
     * @return
     */
    public CoreReturnObject changeZgInOutMate(String plineCode,String inmateNo,String outMateNO) {
        return this.getDataBySqlID("FrmBomConfirm.changeZgInOutMate",
                new Object[] { plineCode,inmateNo,outMateNO });
    }
    /**
     * 查询管坯直径的代码
     * @param specName
     * @return
     */
    public CoreReturnObject getZgPlanInfo(String proPlanId, String gxPlanNo) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmBomConfirm.getZgPlanInfo");
        sql += " AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
        Object[] params = new Object[] { proPlanId, gxPlanNo };
        return this.getData(sql, params);
    }

    /**
     * 查询管坯直径的代码
     * @param specName
     * @return
     */
    public CoreReturnObject getSpecBySpecName(String specName) {
        return this.getDataBySqlID("FrmBomConfirm.getSpecBySpecName",
                new Object[] { specName });
    }

    /**
     * 通过轧制订单编号与PK查询轧制的工序合同
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getPlanOrderInfo(String ordLnDlyPk, String proPlanId) {
        return this.getDataBySqlID("FrmBomConfirm.getPlanOrderInfo",
                new Object[] { ordLnDlyPk, proPlanId });
    }

    /**
     * 通过轧制订单编号查询镦拔扩信息
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getPlineEByProPlanId(String proPlanId) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineEByProPlanId",
                new Object[] { proPlanId });
    }

    /**
     * 通过轧制订单编号查询热处理信息
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getPlineFByProPlanId(String proPlanId) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineFByProPlanId",
                new Object[] { proPlanId });
    }

    /**
     * 通过轧制订单编号查询加工信息
     * @param proPlanId
     * @return
     */
    public CoreReturnObject getPlineGByProPlanId(String proPlanId) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineGByProPlanId",
                new Object[] { proPlanId });
    }

    /**
     * 查询轧管产线
     * @param inMaterialNo 投入物料
     * @param outMaterialNo 产出物料
     * @param designKey 工艺主键
     * @param mscPline 制程
     * @return
     */
    public CoreReturnObject getPlineD(String inMaterialNo,
            String outMaterialNo, String designKey, String mscPline) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineD", new Object[] {
                inMaterialNo, outMaterialNo, designKey, mscPline });
    }

    /**
     * 查询镦拔扩产线
     * @param inMaterialNo 投入物料
     * @param outMaterialNo 产出物料
     * @param designKey 工艺主键
     * @param mscPline 制程
     * @return
     */
    public CoreReturnObject getPlineE(String inMaterialNo,
            String outMaterialNo, String designKey, String mscPline) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineE", new Object[] {
                inMaterialNo, outMaterialNo, designKey, mscPline });
    }

    /**
     * 查询热处理产线
     * @param inMaterialNo 投入物料
     * @param outMaterialNo 产出物料
     * @param designKey 工艺主键
     * @param mscPline 制程
     * @return
     */
    public CoreReturnObject getPlineF(String inMaterialNo,
            String outMaterialNo, String designKey, String mscPline) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineF", new Object[] {
                inMaterialNo, outMaterialNo, designKey, mscPline });
    }

    /**
     * 查询加工产线
     * @param inMaterialNo 投入物料
     * @param outMaterialNo 产出物料
     * @param designKey 工艺主键
     * @param mscPline 制程
     * @return
     */
    public CoreReturnObject getPlineG(String inMaterialNo,
            String outMaterialNo, String designKey, String mscPline) {
        return this.getDataBySqlID("FrmBomConfirm.getPlineG", new Object[] {
                inMaterialNo, outMaterialNo, designKey, mscPline });
    }

    /**
     * 通过产线与管坯规格查询孔型
     * @param plineCode 产线
     * @param month 轧管年月
     * @return
     */
    public CoreReturnObject getPassCodeByPlineAndSpec(String plineCode,
            String specCode) {
        return this.getDataBySqlID("FrmBomConfirm.getPassCodeByPlineAndSpec",
                new Object[] { plineCode, specCode });
    }

    /**
     * 通过产线与轧管年月查询孔型计划
     * @param plineCode 产线
     * @param month 轧管年月
     * @return
     */
    public CoreReturnObject getPassCodeByPlineAndMonth(String plineCode,
            String month) {
        return this.getDataBySqlID("FrmBomConfirm.getPassCodeByPlineAndMonth",
                new Object[] { plineCode, month });
    }

    /**
     * 查询芯棒
     * @param plineCode 产线
     * @param passCode 孔型
     * @param dimater 外径
     * @param height 壁厚
     * @return
     */
    public CoreReturnObject getDiameterMandrel(String plineCode,
            String passCode, String dimater, String height) {
        return this.getDataBySqlID("FrmBomConfirm.getDiameterMandrel",
                new Object[] { plineCode, passCode, dimater, dimater, height,
                        height });
    }

    /**
     * 修改钢种/管坯规格
     * @param bom
     * @param plineCode
     * @param plineName
     * @param specName
     * @param passCode
     * @param dimaterManderl
     * @param proPlanId
     * @param gxPlanNo
     * @return
     */
    public CoreReturnObject changeZgPlan(String bom, String plineCode,
            String plineName, String specName, String passCode,
            String passName, String dimaterManderl, String proPlanId,
            String gxPlanNo, String cic, String casTyte, String plineCodeZz,
            String plineNameZz) {
        CoreReturnObject core = new CoreReturnObject();
        core.setResult(false);
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            SlmOrdDesignBomEntity bomEntity = PlnHelper.getEntityData(con,
                    new String[] { bom }, "FrmBomConfirm.getBomByBom",
                    SlmOrdDesignBomEntity.class);
            if (bomEntity == null) {
                core.setV_errMsg("数据异常,请刷新数据!");
                return core;
            }
            String wholeBacklog = bomEntity.getWholeBacklog();
            if (wholeBacklog.contains("E")) {
                List<PlnOrderDbkSEntity> dbkList = PlnHelper.getEntityDatas(
                        con, new String[] { proPlanId },
                        "FrmBomConfirm.getPlineEByProPlanId",
                        PlnOrderDbkSEntity.class);
                if (dbkList != null && dbkList.size() > 0) {
                    for (PlnOrderDbkSEntity entity : dbkList) {
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateDbkMaterial",
                                new String[] { bomEntity.getEInMaterialNo(),
                                        bomEntity.getEInMaterialDesc(),
                                        bomEntity.getEOutMaterialNo(),
                                        bomEntity.getEOutMaterialDesc(),
                                        bomEntity.getMsc(),
                                        bomEntity.getMscPline(),
                                        bomEntity.getBom(),
                                        bomEntity.getWholeBacklogDesc(),
                                        entity.getProPlanId(),
                                        entity.getGxPlanNo() });
                        // 修改BOM
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateDbkBom", new String[] {
                                        bom, entity.getProPlanId() });
                    }
                }
                else {
                    core.setV_errMsg("数据异常,请刷新数据!");
                    con.rollback();
                    return core;
                }
            }

            if (wholeBacklog.contains("F")) {
                List<PlnOrderRclSEntity> rclList = PlnHelper.getEntityDatas(
                        con, new String[] { proPlanId },
                        "FrmBomConfirm.getPlineFByProPlanId",
                        PlnOrderRclSEntity.class);
                if (rclList != null && rclList.size() > 0) {
                    for (PlnOrderRclSEntity entity : rclList) {
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateRclMaterial",
                                new String[] { bomEntity.getFInMaterialNo(),
                                        bomEntity.getFInMaterialDesc(),
                                        bomEntity.getFOutMaterialNo(),
                                        bomEntity.getFOutMaterialDesc(),
                                        bomEntity.getMsc(),
                                        bomEntity.getMscPline(),
                                        bomEntity.getBom(),
                                        bomEntity.getWholeBacklogDesc(),
                                        entity.getProPlanId(),
                                        entity.getGxPlanNo() });
                        // 修改BOM
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateRclBom", new String[] {
                                        bom, entity.getProPlanId() });
                    }
                }
                else {
                    core.setV_errMsg("数据异常,请刷新数据!");
                    con.rollback();
                    return core;
                }
            }

            if (wholeBacklog.contains("G")) {
                List<PlnOrderJgxSEntity> jgxList = PlnHelper.getEntityDatas(
                        con, new String[] { proPlanId },
                        "FrmBomConfirm.getPlineGByProPlanId",
                        PlnOrderJgxSEntity.class);
                if (jgxList != null && jgxList.size() > 0) {
                    for (PlnOrderJgxSEntity entity : jgxList) {
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateJgxMaterial",
                                new String[] { bomEntity.getIInMaterialNo(),
                                        bomEntity.getIInMaterialDesc(),
                                        bomEntity.getIOutMaterialNo(),
                                        bomEntity.getIOutMaterialDesc(),
                                        bomEntity.getMsc(),
                                        bomEntity.getMscPline(),
                                        bomEntity.getBom(),
                                        bomEntity.getWholeBacklogDesc(),
                                        entity.getProPlanId(),
                                        entity.getGxPlanNo() });
                        // 修改BOM
                        PlnHelper.deleteOrUpdate(con,
                                "FrmBomConfirm.updateJgxBom", new String[] {
                                        bom, entity.getProPlanId() });
                    }
                }
                else {
//                    core.setV_errMsg("数据异常,请刷新数据!");
//                    con.rollback();
//                    return core;
                }
            }
            // 修改轧管信息
            List<PlnOrderZgSEntity> zgList = PlnHelper.getEntityDatas(con,
                    new String[] { proPlanId, gxPlanNo },
                    "FrmBomConfirm.getZgPlanInfo",
                    " AND T.PRO_PLAN_ID = ? AND T.GX_PLAN_NO=?",
                    PlnOrderZgSEntity.class);
            if (zgList == null) {
                core.setV_errMsg("数据异常,请刷新数据!");
                con.rollback();
                return core;
            }

            for (PlnOrderZgSEntity zgEntity : zgList) {
            	//TZH 24.8.27 取消坯料需求申报的处理
//                if (!zgEntity.getGpreqId().equals("")) {
//                    core.setV_errMsg("选择的轧管订单：" + zgEntity.getProPlanId() + "/"
//                            + zgEntity.getGxPlanNo() + ",已生成管坯需求,请撤销管坯需求！");
//                    con.rollback();
//                    return core;
//                }
                // 修改工序合同BOM
                PlnHelper.deleteOrUpdate(con, "FrmBomConfirm.updateZgBom",
                        new String[] { bom, zgEntity.getProPlanId() });
                // 修改排产耗时表BOM
                PlnHelper
                        .deleteOrUpdate(con, "FrmBomConfirm.updateZgSBom",
                                new String[] { bom, bomEntity.getMsc(),
                                        bomEntity.getMscPline(),
                                        bomEntity.getWholeBacklogDesc(),
                                        zgEntity.getProPlanId(),
                                        zgEntity.getGxPlanNo() });
                // 如果是本轧管订单,可修改产线
                if (!casTyte.equals("")) {
                    // 修改轧管排产表自炼,CIC
                    String sqlupdate = CoreXmlSqlParsersFactory
                            .getSql("FrmBomConfirm.updateOutsFl");
                    PreparedStatement psta = con.prepareStatement(sqlupdate);
                    psta.setObject(1, casTyte);
                    psta.setObject(2, zgEntity.getProPlanId());
                    psta.setObject(3, zgEntity.getGxPlanNo());
                    psta.executeUpdate();
                    psta.close();
                }
                String isPlanOk = "";
                String issuedMan = "";
                String issuedTime = "";
                String lastUndownMan = "";
                String lastUndownTime = "";
                String ifStoveIssued = "";
                String stoveIssuedTime = "";
                String stoveIssuedMan = "";
                String zyBatchId = "";
                if (zgEntity.getGxPlanNo().equals(gxPlanNo)) {
                    // 如果产线不致，将会改变订单的产线
                    String gxProSeq = "";
                    if (!zgEntity.getPlineCode().equals(plineCode)) {
                        ProducHelperBean bean = new ProducHelperBean();
                        gxProSeq = String.valueOf(bean.getMaxGxProSeq(con,
                                plineCode, "D", zgEntity.getProMonth()));
                        // 调整产线之前顺序调整
                        bean.seqIncrease(con, zgEntity.getPlineCode(), Integer
                                .parseInt(zgEntity.getGxProSeq()), -1, -1, "D");
                        // 调整产线之后顺序调整
                        bean.seqIncrease(con, plineCode, Integer
                                .parseInt(gxProSeq), -1, 1, "D");

                        isPlanOk = "0";
                        issuedMan = "";
                        issuedTime = "";
                        lastUndownMan = "";
                        lastUndownTime = "";
                        ifStoveIssued = "";
                        stoveIssuedTime = "";
                        stoveIssuedMan = "";
                        zyBatchId = "";
                    }
                    else {
                        gxProSeq = zgEntity.getGxProSeq();
                        isPlanOk = zgEntity.getIsPlanOk();
                        issuedMan = zgEntity.getIssuedMan();
                        issuedTime = zgEntity.getIssuedTime();
                        lastUndownMan = zgEntity.getLastUndownMan();
                        lastUndownTime = zgEntity.getLastUndownTime();
                        ifStoveIssued = zgEntity.getIfStoveIssued();
                        stoveIssuedTime = zgEntity.getStoveIssuedTime();
                        stoveIssuedMan = zgEntity.getStoveIssuedMan();
                        zyBatchId = zgEntity.getZyBatchId();

                        if (!issuedTime.equals("")) {
                            issuedTime = issuedTime.substring(0, 19);
                        }
                        if (!lastUndownTime.equals("")) {
                            lastUndownTime = lastUndownTime.substring(0, 19);
                        }
                        if (!stoveIssuedTime.equals("")) {
                            stoveIssuedTime = stoveIssuedTime.substring(0, 19);
                        }
                    }
                    PlnHelper.deleteOrUpdate(con,
                            "FrmBomConfirm.updateZgMaterial1", new String[] {
                                    bomEntity.getGradecode(),
                                    bomEntity.getGradename(), specName,
                                    bomEntity.getDInMaterialNo(),
                                    bomEntity.getDInMaterialDesc(),
                                    bomEntity.getDOutMaterialNo(),
                                    bomEntity.getDOutMaterialDesc(), plineCode,
                                    plineName, gxProSeq, passCode, passName,
                                    dimaterManderl, cic, isPlanOk, issuedMan,
                                    issuedTime, lastUndownMan, lastUndownTime,
                                    ifStoveIssued, stoveIssuedTime,
                                    stoveIssuedMan, zyBatchId,plineCodeZz,plineNameZz, proPlanId,
                                    gxPlanNo });

                }
                else {
                    // 不是本轧管订单，而是拆分出的订单，则不能修改产线
                    PlnHelper.deleteOrUpdate(con,
                            "FrmBomConfirm.updateZgMaterial", new String[] {
                                    bomEntity.getGradecode(),
                                    bomEntity.getGradename(), specName,
                                    bomEntity.getDInMaterialNo(),
                                    bomEntity.getDInMaterialDesc(),
                                    bomEntity.getDOutMaterialNo(),
                                    bomEntity.getDOutMaterialDesc(),
                                    zgEntity.getPlineCode(),
                                    zgEntity.getPlineName(),
                                    zgEntity.getGxProSeq(), passCode, passName,
                                    dimaterManderl, cic,plineCodeZz,plineNameZz, proPlanId, gxPlanNo });
                }
                // // 修改提报表
                // String sqlupdate = CoreXmlSqlParsersFactory
                // .getSql("CorePlnZgMStoGp.updatplnSaleord");
                // PreparedStatement psta = con.prepareStatement(sqlupdate);
                // psta.setObject(1,casTyte );
                // psta.setObject(2, zgEntity.getOrdLnDlyPk());
                // psta.executeUpdate();
                // psta.close();
            }

            // psta.executeUpdate();
            // // 修改排产分解表排产年月
            // String sqlupdate = CoreXmlSqlParsersFactory
            // .getSql("CoreConfirmCraft.updateRollMonth");
            // PreparedStatement psta = con.prepareStatement(sqlupdate);
            // psta.setObject(1, zgSentity.getProMonth());
            // psta.setObject(2, zgSentity.getOrdLnDlyPk());
            // psta.setObject(3, zgSentity.getPlnDivideId());
            // psta.executeUpdate();

            // 修改工序合同的BOM
            core.setV_errMsg("修改成功!");
            core.setResult(true);
            con.commit();
        }
        catch (SQLException sqle) {
            try {
                con.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            core.setV_errCode(-1);
            core.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // catch (Exception e) {
        // e.printStackTrace();
        // try {
        // con.rollback();
        // }
        // catch (SQLException e1) {
        // e1.printStackTrace();
        // }
        // }
        return core;
    }
}
