package com.steering.pss.plnsaleord.order;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

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.lenthCal.PlnZglenthCal;
import com.steering.pss.plnsaleord.ordAmCal.PlnProcCal;
import com.steering.pss.plnsaleord.order.model.PlnDbkInOutInfoEntity;
import com.steering.pss.plnsaleord.order.model.PlnOrdInfo;
import com.steering.pss.plnsaleord.order.model.PlnSaleordProcEntity;
import com.steering.pss.plnsaleord.order.baseMethod.CoreOrderStdSic;

/**
 * @author xiaohai
 */
public class CoreCalculateDbk extends DBCommon {
    /**
     * 查询变径类型对应产线
     * @param bjType
     * @return object
     */
    public CoreReturnObject selectBjPine(String bjType) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreCalculateDbk.selectBjPine",
                new Object[] { bjType });
        return cro;
    }

    /**
     * 查询
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return object
     */
    public CoreReturnObject queryPlnOrdInfo(String ordLnDlyPk,
            String plnDivideId) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreCalculateDbk.queryPlnOrdInfo",
                new Object[] { ordLnDlyPk, plnDivideId });
        return cro;
    }

    /**
     * 保存轧制转移长度
     * @param list
     * @return
     */
    public CoreReturnObject saveLenRoll(ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreCalculateDbk.saveLenRoll");
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        for (PlnSaleordProcEntity procEntity : list) {
            String sqlUp = EntityTool.fillSqlByEntity(sql, procEntity);
            sqllist.add(sqlUp);
            params.add(new Object[] {});
        }
        cro = this.setData(sqllist, params);
        return cro;
    }

    /**
     * 镦拔扩确认
     * @param list
     * @return
     */
    public CoreReturnObject confirmDbk(ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            PreparedStatement ps = null;
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCalculateDbk.setConfirmDbk");
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            for (PlnSaleordProcEntity procEntity : list) {
                String sqlUp = EntityTool.fillSqlByEntity(sql, procEntity);
                ps = conn.prepareStatement(sqlUp);
                ps.executeUpdate();
                ps.close();
            }
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 查询镦拔扩投入产出信息
     * @param list
     * @return
     */
    public CoreReturnObject getDbkInoutInf(ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            PreparedStatement ps = null;
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCalculateDbk.getOrdDbkInfo");
            ArrayList<PlnDbkInOutInfoEntity> resultList = new ArrayList<PlnDbkInOutInfoEntity>();
            for (PlnSaleordProcEntity procEntity : list) {
                ps = conn.prepareStatement(sql);
                ps.setObject(1, procEntity.getOrdLnDlyPk());
                ps.setObject(2, procEntity.getPlnDivideId());
                ResultSet rs = ps.executeQuery();

                PlnDbkInOutInfoEntity inOutInfo = EntityTool.getEntityByRs(rs,
                        PlnDbkInOutInfoEntity.class);
                if (inOutInfo != null) {
                    String[] message = new String[1];
                    PlnOrdInfo ordInfo = new PlnOrdInfo();
                    ordInfo.setOrdLnDlyPk(procEntity.getOrdLnDlyPk());
                    ordInfo.setPlnDivideId(procEntity.getPlnDivideId());
                    ordInfo.setAimoutdiameter(Double.parseDouble(inOutInfo
                            .getAimOutdiameter()));
                    ordInfo.setAimwallthick(Double.parseDouble(inOutInfo
                            .getAimWallthick()));
                    double lenDbkMax = 0;// 镦拔扩原料上限
                    double lenDbkMin = 0;// 镦拔扩原料下限
                  
                    if (inOutInfo.getRatioDbk() != null
                            && !inOutInfo.getRatioDbk().equals("")) {
                        double lenScope = Double.parseDouble(inOutInfo
                                .getLenScope()) / 100;
                        // 长度加严
                        double lenDbkCalMax = Double.parseDouble(inOutInfo
                                .getLenDbkCalMax())
                                - 0.5
                                * lenScope
                                * (Double.parseDouble(inOutInfo
                                        .getLenDbkCalMax()) - Double
                                        .parseDouble(inOutInfo
                                                .getLenDbkCalMin()));
                        double lenDbkCalMin = Double.parseDouble(inOutInfo
                                .getLenDbkCalMin())
                                + 0.5
                                * lenScope
                                * (Double.parseDouble(inOutInfo
                                        .getLenDbkCalMax()) - Double
                                        .parseDouble(inOutInfo
                                                .getLenDbkCalMin()));
                        lenDbkMax = (lenDbkCalMax + (Double
                                .parseDouble(inOutInfo.getLenCutheadDbk()) + Double
                                .parseDouble(inOutInfo.getLenCutendDbk())) / 1000)
                                * Double.parseDouble(inOutInfo.getRatioDbk());
                        lenDbkMin = (lenDbkCalMin + (Double
                                .parseDouble(inOutInfo.getLenCutheadDbk()) + Double
                                .parseDouble(inOutInfo.getLenCutendDbk())) / 1000)
                                * Double.parseDouble(inOutInfo.getRatioDbk());
                    }
                    if (!getDbkInOutAmount(conn, ordInfo, inOutInfo, message)) {
                        cro.setV_errMsg(inOutInfo.getOrderNoSeq() + message[0]);
                    }
                    inOutInfo.setLenDbkMax(String.valueOf(new BigDecimal(
                            lenDbkMax).setScale(2, RoundingMode.HALF_UP)
                            .doubleValue()));
                    inOutInfo.setLenDbkMin(String.valueOf(new BigDecimal(
                            lenDbkMin).setScale(2, RoundingMode.HALF_UP)
                            .doubleValue()));

                    double lenDbkZyMin = 0;
                    double lenDbkZyMax = 0;
                    double LenZgCalMin = 0;
                    double LenZgCalMax = 0;
                    double RatioDbk = 1;
                    if (inOutInfo.getLenZgCalMin() != null
                            && !inOutInfo.getLenZgCalMin().equals("")) {
                        LenZgCalMin = Double.parseDouble(inOutInfo
                                .getLenZgCalMin());
                    }
                    if (inOutInfo.getLenZgCalMax() != null
                            && !inOutInfo.getLenZgCalMax().equals("")) {
                        LenZgCalMax = Double.parseDouble(inOutInfo
                                .getLenZgCalMax());
                    }
                    if (inOutInfo.getRatioDbk() != null
                            && !inOutInfo.getRatioDbk().equals("")) {
                        RatioDbk = Double.parseDouble(inOutInfo.getRatioDbk());
                    }

                    lenDbkZyMin = LenZgCalMin * RatioDbk;
                    lenDbkZyMax = LenZgCalMax * RatioDbk;
                    // lenDbkZyMin =
                    // Double.parseDouble(inOutInfo.getLengthmin())
                    // + 0.5
                    // * lenScope
                    // * (Double.parseDouble(inOutInfo.getLengthmax()) - Double
                    // .parseDouble(inOutInfo.getLengthmin()));
                    // lenDbkZyMax =
                    // Double.parseDouble(inOutInfo.getLengthmax())
                    // - 0.5
                    // * lenScope
                    // * (Double.parseDouble(inOutInfo.getLengthmax()) - Double
                    // .parseDouble(inOutInfo.getLengthmin()));
                    inOutInfo.setLenDbkZyMax(String.valueOf(new BigDecimal(
                            lenDbkZyMax).setScale(2, RoundingMode.HALF_UP)
                            .doubleValue()));
                    inOutInfo.setLenDbkZyMin(String.valueOf(new BigDecimal(
                            lenDbkZyMin).setScale(2, RoundingMode.HALF_UP)
                            .doubleValue()));

                    /*
                     * 计算轧制转移长度上下限 LenZgCalEntiy lanCalEntity = new
                     * LenZgCalEntiy();
                     * lanCalEntity.setLenMax(rs.getDouble("LENGTHMAX"));
                     * lanCalEntity.setLenMin(rs.getDouble("LENGTHMIN"));
                     * lanCalEntity.setDiameter(rs.getDouble("OUTDIAMETER"));
                     * lanCalEntity.setHeight(rs.getDouble("WALLTHICK"));
                     * lanCalEntity.setDiameterZg(rs.getDouble("DIMATER"));
                     * lanCalEntity.setHeightZg(rs.getDouble("HEIGHT"));
                     * lanCalEntity.setCheckJVal(rs.getDouble("CHECK_J_VAL"));
                     * lanCalEntity
                     * .setInspectLen(rs.getDouble("INSPECTION_VALUE"));
                     * lanCalEntity.setLenDc(inOutInfo.getLenDc());
                     * lanCalEntity.setDbkCut(inOutInfo.getDbkCut()); if
                     * (rs.getString("MODEL_DESC") != null) {
                     * lanCalEntity.setModelDesc(rs.getString("MODEL_DESC")); }
                     * double lenZgMax =
                     * PlnZglenthCal.lenZgCalMax(lanCalEntity); double lenZgMin
                     * = PlnZglenthCal.lenZgCalMin(lanCalEntity);
                     * java.text.DecimalFormat df = new java.text.DecimalFormat(
                     * "#0.000"); inOutInfo.setLenZgCalMax(df.format(lenZgMax));
                     * inOutInfo.setLenZgCalMin(df.format(lenZgMin));
                     */

                    resultList.add(inOutInfo);
                }
                rs.close();
                ps.close();
            }
            cro.setResult(EntityTool.getGsonByEntity(resultList));
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 查询镦拔扩投入产出信息
     * @param list
     * @return
     */
    public CoreReturnObject recalculation(ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            PreparedStatement ps = null;
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreCalculateDbk.getOrdDbkInfo");
            ArrayList<PlnDbkInOutInfoEntity> resultList = new ArrayList<PlnDbkInOutInfoEntity>();
            for (PlnSaleordProcEntity procEntity : list) {
                ps = conn.prepareStatement(sql);
                ps.setObject(1, procEntity.getOrdLnDlyPk());
                ps.setObject(2, procEntity.getPlnDivideId());
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    if (!rs.getString("PLANSTATUS").equals("已接收")) {
                        cro.setV_errMsg("合同:" + procEntity.getOrderNo()
                                + ",不是已接收状态。");
                        return cro;
                    }
                }
                else {
                    cro.setV_errMsg("未找到合同:" + procEntity.getOrderNo());
                    return cro;
                }
                rs.close();
                ps.close();
                //
                // double lenDbkMax = 0;// 镦拔扩原料上限
                // double lenDbkMin = 0;// 镦拔扩原料下限
                // if (procEntity.getRatioDbk() != null
                // && !procEntity.getRatioDbk().equals("")) {
                // lenDbkMax = (Double.parseDouble(procEntity
                // .getLenDbkCalMax()) + (Double
                // .parseDouble(procEntity.getLenCutheadDbk()) + Double
                // .parseDouble(procEntity.getLenCutendDbk())) / 1000)
                // * Double.parseDouble(procEntity.getRatioDbk());
                // lenDbkMin = (Double.parseDouble(procEntity
                // .getLenDbkCalMin()) + (Double
                // .parseDouble(procEntity.getLenCutheadDbk()) + Double
                // .parseDouble(procEntity.getLenCutendDbk())) / 1000)
                // * Double.parseDouble(procEntity.getRatioDbk());
                // }
                // procEntity.setLenRollMax(String.valueOf(new BigDecimal(
                // lenDbkMax).setScale(2, RoundingMode.HALF_UP)
                // .doubleValue()));
                // procEntity.setLenRollMin(String.valueOf(new BigDecimal(
                // lenDbkMin).setScale(2, RoundingMode.HALF_UP)
                // .doubleValue()));

                // 修改排产分解表镦拔扩切头尾
                String sqlpdate = EntityTool.fillSqlByEntity(
                        CoreXmlSqlParsersFactory
                                .getSql("CoreCalculateDbk.updateDbkCut"),
                        procEntity);
                ps = conn.prepareStatement(sqlpdate);
                ps.executeUpdate();
                ps.close();
//               //判定基础数据是否存在切头尾，存在不修改，否则修改基础数据
//                String 
            }
            cro.setV_errMsg("重算成功!");
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 镦拔扩投入产出
     * @param conn
     * @param ordInfo
     * @param inOutInfo
     * @param errMessage
     * @return
     * @throws SQLException
     */
    public boolean getDbkInOutAmount(Connection conn, PlnOrdInfo ordInfo,
            PlnDbkInOutInfoEntity inOutInfo, String[] errMessage)
            throws SQLException {
        PreparedStatement psta = null;
        String groupJgx = "";
        String groupRcl = "";
        // 查询合同信息
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.querySaleProcStatus");
        psta = conn.prepareStatement(sql);
        psta.setString(1, ordInfo.getOrdLnDlyPk());
        psta.setString(2, ordInfo.getPlnDivideId());
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            double planMainWt = rs.getDouble("PLAN_P_MAIN");
            ordInfo.setPlanWtD(rs.getDouble("PLAN_WT_D"));
            ordInfo.setPlanNumD(rs.getInt("PLAN_NUM_D"));
            if (planMainWt == 0) {
                return true;
            }
            if (planMainWt < 0) {
                errMessage[0] = "下发计划量必须大于零。";
                return false;
            }
            if (rs.getString("INDEX_SEQ") == null) {
                errMessage[0] = "未找到制程索引号。";
                return false;
            }
            if (rs.getString("DESGIN_KEY") == null) {
                errMessage[0] = "未找到质量设计。";
                return false;
            }
            if (rs.getString("BOM") == null) {
                errMessage[0] = "未找到BOM号。";
                return false;
            }
            ordInfo.setDesginKey(rs.getString("DESGIN_KEY"));
            ordInfo.setIndexSeq(rs.getString("INDEX_SEQ"));
            ordInfo.setBom(rs.getString("BOM"));
            ordInfo.setOutdiameter(rs.getDouble("OUTDIAMETER"));
            ordInfo.setWallthick(rs.getDouble("WALLTHICK"));
            ordInfo.setAimLenRoll(rs.getDouble("AIM_LEN_ROLL"));
            ordInfo.setwJ(rs.getDouble("WEIGHT_PER_M"));
            ordInfo.setLengthmax(rs.getDouble("LENGTHMAX"));
            ordInfo.setLengthmin(rs.getDouble("LENGTHMIN"));
            ordInfo.setSiglLen(rs.getDouble("SIGL_LEN"));
            ordInfo.setShortest(rs.getDouble("SHORTEST"));
            ordInfo.setCheckJVal(rs.getDouble("CHECK_J_VAL"));
            ordInfo.setAddInspect(rs.getDouble("INSPECTION_VALUE"));
            if (rs.getString("SHRT_STOVE") != null) {
                ordInfo.setShrtStove(rs.getString("SHRT_STOVE"));
            }
            if (rs.getString("PRDCR_NO") != null) {
                ordInfo.setPrdcrNo(rs.getString("PRDCR_NO"));
            }
            if (rs.getString("GROUP_ROLL") != null) {
                ordInfo.setPlineD(rs.getString("GROUP_ROLL"));
            }
            if (rs.getString("MODEL_DESC") != null) {
                ordInfo.setModelDesc(rs.getString("MODEL_DESC"));
            }
            if (rs.getString("GROUP_JGX") != null) {
                groupJgx = rs.getString("GROUP_JGX");
            }
            if (rs.getString("GROUP_RCL") != null) {
                groupRcl = rs.getString("GROUP_RCL");
            }
        }
        else {
            errMessage[0] = "未找到合同信息。";
            return false;
        }
        rs.close();
        psta.close();

        // 查询制程
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryDesginMscpl");
        psta = conn.prepareStatement(sql);
        psta.setString(1, ordInfo.getDesginKey());
        psta.setString(2, ordInfo.getIndexSeq());
        rs = psta.executeQuery();
        if (rs.next()) {
            if (rs.getString("WHOLE_BACKLOG") == null) {
                errMessage[0] = "未找到制程经过工序点。";
                return false;
            }
            ordInfo.setWholeBacklog(rs.getString("WHOLE_BACKLOG"));
        }
        else {
            errMessage[0] = "未找到制程信息。";
            return false;
        }
        rs.close();
        psta.close();

        // 经过工序倒推
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryMscplPrc");
        psta = conn.prepareStatement(sql);
        psta.setString(1, ordInfo.getDesginKey());
        psta.setString(2, ordInfo.getIndexSeq());
        rs = psta.executeQuery();
        while (rs.next()) {
            if (rs.getString("PROCESS_CODE") == null) {
                errMessage[0] = "工序点代码为空。";
                return false;
            }
            if (rs.getString("PROCESS_CODE").trim().equals("G")) {
                if (!addJgxPrcOrder(groupJgx, ordInfo, conn)) {
                    errMessage[0] = ordInfo.getErrMessage();
                    return false;
                }
            }
            if (rs.getString("PROCESS_CODE").trim().equals("F")) {
                if (!addRclPrcOrder(groupRcl, ordInfo, conn)) {
                    errMessage[0] = ordInfo.getErrMessage();
                    return false;
                }
            }
            if (rs.getString("PROCESS_CODE").trim().equals("E")) {
                java.text.DecimalFormat df = new java.text.DecimalFormat(
                        "#0.000");
                inOutInfo.setOutWtDbk(df.format(ordInfo.getPlanWtD()));
                inOutInfo.setOutNumDbk(String.valueOf(ordInfo.getPlanNumD()));
                if (!addDbkPrcOrder(inOutInfo, ordInfo, conn)) {
                    errMessage[0] = ordInfo.getErrMessage();
                    return false;
                }
                inOutInfo.setInWtDbk(df.format(ordInfo.getPlanWtD()));
                inOutInfo.setInNumDbk(String.valueOf(ordInfo.getPlanNumD()));
            }
        }
        rs.close();
        psta.close();
        return true;
    }

    /**
     * 加工投料量
     * @param gourpJgx
     * @param ordInfo
     * @param conn
     * @return
     * @throws SQLException
     */
    private boolean addJgxPrcOrder(String gourpJgx, PlnOrdInfo ordInfo,
            Connection conn) throws SQLException {
        double addDbk = 0;// 拔扩加长（mm）
        int addNum = 0;// 加投支数
        String inMaterialNo = "";
        String outMaterialNo = "";
        double addlenZgRule = 0;// 轧管加长原则（mm）

        PreparedStatement ps = null;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryDesginBomI");
        ps = conn.prepareStatement(sql);
        ps.setString(1, ordInfo.getBom());
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            inMaterialNo = rs.getString("IN_MATERIAL_NO");
            outMaterialNo = rs.getString("OUT_MATERIAL_NO");
        }
        rs.close();
        ps.close();

        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryDesginBom");
        ps = conn.prepareStatement(sql);
        ps.setString(1, ordInfo.getBom());
        rs = ps.executeQuery();
        if (rs.next()) {
            double outdiameterIn = rs.getDouble("DIMATER");
            double wallthickIn = rs.getDouble("HEIGHT");
            String eInMaterialNo = "";
            String eOutMaterialNo = "";
            if (rs.getString("E_IN_MATERIAL_NO") != null) {
                eInMaterialNo = rs.getString("E_IN_MATERIAL_NO");
            }
            if (rs.getString("E_OUT_MATERIAL_NO") != null) {
                eOutMaterialNo = rs.getString("E_OUT_MATERIAL_NO");
            }
            String[] dbkAdd = PlnZglenthCal.addLenDbk(conn, eInMaterialNo,
                    eOutMaterialNo, ordInfo.getDesginKey(), ordInfo
                            .getIndexSeq());
            // dbkpline = String.valueOf(dbkAdd[2]);
            // String sqldbk = CoreXmlSqlParsersFactory
            // .getSql("CorePlnProcessOrd.queryBasePlineD");
            // PreparedStatement psta = conn.prepareStatement(sqldbk);
            // psta.setObject(1, dbkpline);
            // ResultSet result = psta.executeQuery();
            // if (result.next()) {
            // buringRateDbk = result.getDouble("BURNOUT_RATE");
            // }
            // result.close();
            // psta.close();
            double x = 1;
            if (wallthickIn != 0 && outdiameterIn != 0) {
                x = ordInfo.getWallthick()
                        * (ordInfo.getOutdiameter() - ordInfo.getWallthick())
                        / (wallthickIn * (outdiameterIn - wallthickIn));
            }
            addDbk = Double.parseDouble(dbkAdd[0]) * x;
        }
        rs.close();
        ps.close();

        // 成材率
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryBaseMaterialIPl");
        ps = conn.prepareStatement(sql);
        ps.setString(1, inMaterialNo);
        ps.setString(2, outMaterialNo);
        ps.setString(3, ordInfo.getDesginKey());
        ps.setString(4, ordInfo.getIndexSeq());
        ps.setString(5, gourpJgx);
        rs = ps.executeQuery();
        if (rs.next()) {
            addNum = rs.getInt("WASTE_RATE");
        }
        rs.close();
        ps.close();

        addlenZgRule = PlnZglenthCal.addLenZgRule(ordInfo.getLengthmax(),
                ordInfo.getLengthmin(), ordInfo.getModelDesc());// 轧管加长原则(mm)

        ordInfo.setPlanWtD(PlnProcCal.ordJgxInventory(ordInfo.getPlanWtD(),
                ordInfo.getPlanNumD(), addNum, ordInfo.getAimLenRoll(), ordInfo
                        .getwJ(), addDbk, addlenZgRule));
        ordInfo.setPlanNumD(addNum + ordInfo.getPlanNumD());
        return true;
    }

    /**
     * 热处理投料量
     * @param groupRcl
     * @param ordInfo
     * @param conn
     * @return
     * @throws SQLException
     */
    private boolean addRclPrcOrder(String groupRcl, PlnOrdInfo ordInfo,
            Connection conn) throws SQLException {
        PreparedStatement ps = null;
        double addDbk = 0;// 拔扩加长（mm）
        int addNum = 0;// 加投支数
        double buringRate = 0;// 烧损率（%）
        double addlenInspect = ordInfo.getAddInspect();// 盲区切长（mm）
        String inMaterialNo = "";
        String outMaterialNo = "";

        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryDesginBom");
        ps = conn.prepareStatement(sql);
        ps.setString(1, ordInfo.getBom());
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            double outdiameterIn = rs.getDouble("DIMATER");
            double wallthickIn = rs.getDouble("HEIGHT");
            double x = 1;
            String eInMaterialNo = "";
            String eOutMaterialNo = "";
            if (rs.getString("E_IN_MATERIAL_NO") != null) {
                eInMaterialNo = rs.getString("E_IN_MATERIAL_NO");
            }
            if (rs.getString("E_OUT_MATERIAL_NO") != null) {
                eOutMaterialNo = rs.getString("E_OUT_MATERIAL_NO");
            }
            String[] dbkAdd = PlnZglenthCal.addLenDbk(conn, eInMaterialNo,
                    eOutMaterialNo, ordInfo.getDesginKey(), ordInfo
                            .getIndexSeq());
            if (wallthickIn != 0 && outdiameterIn != 0) {
                x = ordInfo.getWallthick()
                        * (ordInfo.getOutdiameter() - ordInfo.getWallthick())
                        / (wallthickIn * (outdiameterIn - wallthickIn));
            }
            addDbk = Double.parseDouble(dbkAdd[0]) * x;
            if (rs.getString("F_IN_MATERIAL_NO") != null) {
                inMaterialNo = rs.getString("F_IN_MATERIAL_NO");
            }
            if (rs.getString("F_IN_MATERIAL_NO") != null) {
                outMaterialNo = rs.getString("F_OUT_MATERIAL_NO");
            }
        }
        rs.close();
        ps.close();

        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryBasePlineD");
        ps = conn.prepareStatement(sql);
        ps.setString(1, ordInfo.getPlineD());
        rs = ps.executeQuery();
        if (rs.next()) {
            buringRate = rs.getDouble("BURNOUT_RATE");
        }
        rs.close();
        ps.close();

        // 成材率
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryBaseMaterialFPl");
        ps = conn.prepareStatement(sql);
        ps.setString(1, inMaterialNo);
        ps.setString(2, outMaterialNo);
        ps.setString(3, ordInfo.getDesginKey());
        ps.setString(4, ordInfo.getIndexSeq());
        ps.setString(5, groupRcl);
        rs = ps.executeQuery();
        if (rs.next()) {
            addNum = rs.getInt("WASTE_RATE");
        }
        rs.close();
        ps.close();

        ordInfo.setPlanWtD(PlnProcCal.ordRclInventory(ordInfo.getPlanWtD(),
                ordInfo.getPlanNumD(), addNum, ordInfo.getAimLenRoll(), ordInfo
                        .getwJ(), addDbk, addlenInspect, buringRate));

        ordInfo.setPlanNumD(ordInfo.getPlanNumD() + addNum);
        return true;
    }

    /**
     * 镦拔扩投料量
     * @param ordInfo
     * @param conn
     * @return
     * @throws SQLException
     */
    private boolean addDbkPrcOrder(PlnDbkInOutInfoEntity inOutInfo,
            PlnOrdInfo ordInfo, Connection conn) throws SQLException {
        PreparedStatement ps = null;
        int addNum = 0;// 加投支数
        double cutHeadEnd = 0;// 镦拔扩切头未（mm）
        double addLenDc = 0;// 镦粗加长
        double buringRate = 0;// 烧损率（%）
        String inMaterialNo = "";
        String outMaterialNo = "";
        double outdiameterDbk = 0;// 墩拔扩外径
        double wallthickDbk = 0;// 墩拔扩壁厚
        double outdiameterIn = 0;// 墩拔扩原料外径
        double wallthickIn = 0;// 墩拔扩原料壁厚
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryDesginBom");
        ps = conn.prepareStatement(sql);
        ps.setString(1, ordInfo.getBom());
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            inMaterialNo = rs.getString("E_IN_MATERIAL_NO");
            outMaterialNo = rs.getString("E_OUT_MATERIAL_NO");
            outdiameterDbk = rs.getDouble("DIMATERDBK");
            wallthickDbk = rs.getDouble("HEIGHTDBK");
            outdiameterIn = rs.getDouble("DIMATER");
            wallthickIn = rs.getDouble("HEIGHT");
        }
        rs.close();
        ps.close();

        // sql = CoreXmlSqlParsersFactory
        // .getSql("CorePlnProcessOrd.queryBasePlineD");
        // ps = conn.prepareStatement(sql);
        // ps.setString(1, ordInfo.getPlineD());
        // rs = ps.executeQuery();
        // if (rs.next()) {
        // buringRate = rs.getDouble("BURNOUT_RATE");
        // }
        // rs.close();
        // ps.close();

        String cutHead = "";
        String cutEnd = "";
        // 变径类型

        String plineCode = "";
        // if (inOutInfo.getBjType().equals("旋扩")) {
        // plineCode = "C018";
        // }
        // else if (inOutInfo.getBjType().equals("热扩")) {
        // plineCode = "C070";
        // }
        // else if (inOutInfo.getBjType().equals("镦粗")) {
        // plineCode = "C021";
        // }
        // else if (inOutInfo.getBjType().equals("冷轧")) {
        // plineCode = "C013";
        // }
        // else if (inOutInfo.getBjType().equals("冷拔")) {
        // plineCode = "C014";
        // }
        // 成材率
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcessOrd.queryBaseMaterialEPl");
        ps = conn.prepareStatement(sql);
        ps.setString(1, inMaterialNo);
        ps.setString(2, outMaterialNo);
        // ps.setString(3, plineCode);
        ps.setString(3, ordInfo.getDesginKey());
        ps.setString(4, ordInfo.getIndexSeq());
        rs = ps.executeQuery();
        if (rs.next()) {
            addLenDc = rs.getDouble("UPSETTING_LENGTH");
            cutHead = rs.getString("CROP_HEAD");
            cutEnd = rs.getString("CROP_END");
            // }
            plineCode = rs.getString("PLINE_CODE");
            // // 默认值
            // if (plineCode.trim().equals("C021")
            // || plineCode.trim().equals("C067")) {
            // if (addLenDc == 0) {
            // addLenDc = CoreOrdBase.addDbkDefault(plineCode);
            // }
            // }
            // else {
            // if (cutHeadEnd == 0) {
            // cutHeadEnd = CoreOrdBase.addDbkDefault(plineCode);
            // }
            // }

            String sqldbk = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcessOrd.queryBasePlineD");
            PreparedStatement psta = conn.prepareStatement(sqldbk);
            psta.setObject(1, plineCode);
            ResultSet result = psta.executeQuery();
            if (result.next()) {
                buringRate = result.getDouble("BURNOUT_RATE");
            }
            result.close();
            psta.close();
            // inOutInfo.setLenDc(String.valueOf(addLenDc));
            // inOutInfo.setDbkCut(String.valueOf(cutHeadEnd));
            addNum = rs.getInt("WASTE_RATE");
        }
        rs.close();
        ps.close();

        // String processCodeC = "";
        // sql = CoreXmlSqlParsersFactory
        // .getSql("CorePlnZgMStoGp.selectMscPlProc");
        // ps = conn.prepareStatement(sql);
        // ps.setObject(1, ordInfo.getDesginKey());
        // ps.setObject(2, ordInfo.getIndexSeq());
        // ps.setObject(3, "E");
        // ResultSet rsta = ps.executeQuery();
        // if (rsta.next()) {
        // if (rsta.getString("PROCESS_CODE_C") == null) {
        // ordInfo.setErrCode(-1);
        // ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
        // + "未找到镦拔扩二级工序。");
        // return false;
        // }
        // else {
        // processCodeC = rsta.getString("PROCESS_CODE_C");
        // }
        // }
        // rsta.close();
        // ps.close();
        //
        // // 镦粗
        // if (processCodeC.equals("B008") && addLenDc == 0) {
        // ordInfo.setErrCode(-1);
        // ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
        // + "镦粗加长为空,请维护基础数据。");
        // return false;
        // }
        // else if (cutHeadEnd < 0) {
        // ordInfo.setErrCode(-1);
        // ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
        // + "拔扩切头尾之和小于零,请确认基础数据。");
        // return false;
        // }
        // else if (cutHead == null || cutHead.equals("")) {
        // ordInfo.setErrCode(-1);
        // ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
        // + "拔扩切头为空,请维护基础数据。");
        // return false;
        // }
        // else if (cutEnd == null || cutEnd.equals("")) {
        // ordInfo.setErrCode(-1);
        // ordInfo.setErrMessage(ordInfo.getErrMessage() + "\r\n"
        // + "拔扩切尾为空,请维护基础数据。");
        // return false;
        // }
        if (cutHead == null) {
            cutHead = "";
        }
        if (cutEnd == null) {
            cutEnd = "";
        }
        if (inOutInfo.getLenCutheadDbk().equals("")) {
            inOutInfo.setLenCutheadDbk(cutHead);
        }
        if (inOutInfo.getLenCutendDbk().equals("")) {
            inOutInfo.setLenCutendDbk(cutEnd);
        }
        if (inOutInfo.getLenLongerDbk().equals("")) {
            inOutInfo.setLenLongerDbk(String.valueOf(addLenDc));
        }
        if (!inOutInfo.getLenCutheadDbk().equals("")
                && !inOutInfo.getLenCutendDbk().equals("")) {
            cutHeadEnd = Double.parseDouble(inOutInfo.getLenCutendDbk())
                    + Double.parseDouble(inOutInfo.getLenCutendDbk());
        }
        if (!inOutInfo.getLenCutheadDbk().equals("")
                && inOutInfo.getLenCutendDbk().equals("")) {
            cutHeadEnd = Double.parseDouble(inOutInfo.getLenCutendDbk()) + 0;
        }
        if (inOutInfo.getLenCutheadDbk().equals("")
                && !inOutInfo.getLenCutendDbk().equals("")) {
            cutHeadEnd = 0 + Double.parseDouble(inOutInfo.getLenCutendDbk());
        }
        double x = 1;
        double wallLower = 0;
        double wallUpper = 0;
        // 获取交货标准壁厚公差
        CoreOrderStdSic stdTolerance = new CoreOrderStdSic();
        Double[] stdTole = null;
        stdTole = stdTolerance.getStdTole(ordInfo.getDesginKey(), ordInfo
                .getOutdiameter(), ordInfo.getWallthick());
        if (stdTole != null) {
            wallLower = stdTole[1] * 100 / ordInfo.getWallthick();
            wallUpper = stdTole[0] * 100 / ordInfo.getWallthick();
        }
        double outdiamMax = 0;
        double outdiamMin = 0;
        // 获取交货标准外径公差
        stdTolerance = new CoreOrderStdSic();
        Double[] stdToleD = null;
        stdToleD = stdTolerance.getStdOutD(ordInfo.getDesginKey(), ordInfo
                .getOutdiameter(), ordInfo.getWallthick());
        if (stdToleD != null) {
            outdiamMax = stdToleD[0];
            outdiamMin = stdToleD[1];
        }

        double cpAimwallthick = 0;
        double bh = 0;
        // new BigDecimal(ordInfo.getWallthick()
        // + (wallLower + wallUpper) / 2).setScale(2,
        // RoundingMode.HALF_UP).doubleValue();
        // 1+（iif(交货壁厚上限-下限>25，25-2*下限，上限-下限））/200

        if (wallUpper - wallLower > 25) {
            bh = 25 + 2 * wallLower;
        }
        else {
            bh = wallUpper + wallLower;
        }
        bh = 1 + bh / 200;
        cpAimwallthick = ordInfo.getWallthick() * bh;
        // double cpAimOutdiam = new BigDecimal(ordInfo.getOutdiameter()
        // + (outdiamMax + outdiamMin) / 2).setScale(2,
        // RoundingMode.HALF_UP).doubleValue();

        if (wallthickIn != 0 && outdiameterIn != 0) {
            // 外径壁厚 变化率
            x = PlnZglenthCal.getDhChangeRate(ordInfo.getOutdiameter(),
                    cpAimwallthick, ordInfo.getAimoutdiameter(), ordInfo
                            .getAimwallthick(), buringRate);
            // x = PlnZglenthCal.getDhChangeRate(ordInfo.getOutdiameter(),
            // ordInfo
            // .getWallthick(), outdiameterIn, wallthickIn, buringRate);
        }
        inOutInfo.setRatioDbk(String.valueOf(new BigDecimal(x).setScale(3,
                RoundingMode.HALF_UP).doubleValue()));
        inOutInfo.setBurning(String.valueOf(new BigDecimal(buringRate / 100)
                .setScale(2, RoundingMode.HALF_UP).doubleValue()));
        ordInfo.setPlanWtD(PlnProcCal.ordDbkInventory(ordInfo.getPlanWtD(),
                ordInfo.getPlanNumD(), addNum, cutHeadEnd, ordInfo
                        .getAimLenRoll(), ordInfo.getwJ(), buringRate));

        ordInfo.setPlanNumD(ordInfo.getPlanNumD() + addNum);
        return true;
    }

    /**
     * 实现3舍4进
     * @param d
     * @return
     */
    public static double intThe(double d) {
        double i = 0;
        i = d + 0.001;
        BigDecimal bg = new BigDecimal(i).setScale(2, RoundingMode.HALF_UP);
        return bg.doubleValue();
    }
}