package com.steering.pss.plnsaleord.order.baseMethod;

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

import CoreFS.SA08.CoreXmlSqlParsersFactory;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.ordAmCal.PlnProducCal;
import com.steering.pss.plnsaleord.ordAmCal.model.InOrdParamEntity;
import com.steering.pss.plnsaleord.ordAmCal.model.OutOrdParamEntity;
import com.steering.pss.plnsaleord.order.CoreOrdLinePrdcrLst;
import com.steering.pss.plnsaleord.order.CorePlnProcessOrd;
import com.steering.pss.plnsaleord.order.model.CoreTolerOfNkParam;
import com.steering.pss.plnsaleord.order.model.PlnSaleordProcEntity;

/**
 * 工序调整重算下发量
 * @author xiaohai
 */
public class CorePlnProcAdjust extends DBCommon {
    /**
     * 错误信息
     */
    private String errMessage = "";

    /**
     * 新增交货行拆分合同
     * @param conn
     * @param name 创建人
     * @param ordLnDlyPk 原交货行pk
     * @param plnDivideId 原交货行排产流水号
     * @param craftSeq 工艺序号
     * @param mscPline 制程索引号
     * @param bom BOM号
     * @param dPline 轧管产线代码
     * @param planTotLenD 分配保总长（m）
     * @throws SQLException
     * @throws
     */
    public boolean addPrcOrder(Connection conn, String name, String ordLnDlyPk,
            String _plnDivideId, String craftSeq, String mscPline, String bom,
            String dPline, double planTotLenD, String orderNoSeq,
            String orderSource) throws SQLException {
        PlnSaleordProcEntity ordProcEntity = new PlnSaleordProcEntity();
        PreparedStatement ps = null;

        // _start 计算合同量
        InOrdParamEntity inOrdParam = new InOrdParamEntity();
        String desginKey = "";
        String dInMaterialNo = "";
        String dOutMaterialNo = "";
        String eInMaterialNo = "";
        String eOutMaterialNo = "";
        String prdcrPro = "";// 监制工序
        String codeJg = "";
        String sicZg = "";// 轧管内控标准索引
        double cutMax = 0;// 最大分切数
        double tubeEndRatio = 0;// 管端系数
        if (ordLnDlyPk.length() <= 3) {
            this.errMessage = "交货行pk有误。";
            return false;
        }
        String ordLnPk = ordLnDlyPk.substring(0, ordLnDlyPk.length() - 3);

        // 分配保总长
        if (planTotLenD <= 0) {
            this.errMessage = "分配保总长必须大于零。";
            return false;
        }
        inOrdParam.setOrderQty(planTotLenD);
        inOrdParam.setOrderUnit("米");
        inOrdParam.setTotlength(planTotLenD);
        inOrdParam.setTotlengthUnit("米");
        inOrdParam.setWeightType(-1);
        inOrdParam.setPutRate(1);

        // 查询工艺质量设计
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.getOrdLnCraftDesgin");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.setObject(2, craftSeq);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            if (rs.getString("DESGIN_KEY") != null) {
                desginKey = rs.getString("DESGIN_KEY");
            }
            if (rs.getString("CRAFT_NAME") != null) {
                ordProcEntity.setCraftFileMan(rs.getString("CRAFT_NAME"));
            }
            if (rs.getString("CRAFT_NO") != null) {
                ordProcEntity.setCraftFileNo(rs.getString("CRAFT_NO"));
            }
            if (rs.getString("CRAFT_NO_V") != null) {
                ordProcEntity.setCraftNoV(rs.getString("CRAFT_NO_V"));
            }
        }
        rs.close();
        ps.close();

        // /查询轧管内控壁厚公差标准索引号
        boolean bl = false;
        boolean isGpOrd = true;// 是否管坯合同
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.queryMscPlPrc");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, desginKey);
        ps.setObject(2, mscPline);
        rs = ps.executeQuery();
        while (rs.next()) {
            bl = true;
            if (rs.getString("WHOLE_BACKLOG") != null) {
                ordProcEntity.setProcessSeq(rs.getString("WHOLE_BACKLOG"));
            }

            if (rs.getString("PROCESS_CODE") != null
                    && rs.getString("PROCESS_CODE").trim().equals("E")) {
                ordProcEntity.setBjType(rs.getString("PROCESS_DESC_C"));
            }

            if (rs.getString("PROCESS_CODE") != null
                    && rs.getString("PROCESS_CODE").trim().equals("D")) {
                isGpOrd = false;
                if (rs.getString("SIC") != null) {
                    sicZg = rs.getString("SIC");
                }
            }
        }
        rs.close();
        ps.close();

        if (!bl) {
            this.errMessage = "未找到制程工序点信息。";
            return false;
        }

        // 查询BOM轧管规格，坯料规格，轧管、镦拔扩投入产出物料编码
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.getBomZgSpecInf");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, bom);
        rs = ps.executeQuery();
        if (rs.next()) {
            String outPlMaterialNo = "";// 管坯编码
            List<Double> dimianPl = new ArrayList<Double>();
            dimianPl.add(rs.getDouble("SPEC_BILT"));
            inOrdParam.setDiameterZg(rs.getDouble("DIMATER"));
            inOrdParam.setHeightZg(rs.getDouble("HEIGHT"));
            inOrdParam.setDiameterPl(dimianPl);
            if (rs.getString("DIMATER") != null) {
                ordProcEntity.setDimaterYlg(rs.getString("DIMATER"));
            }
            if (rs.getString("HEIGHT") != null) {
                ordProcEntity.setHeightYlg(rs.getString("HEIGHT"));
            }
            if (rs.getString("GRADECODE") != null) {
                ordProcEntity.setGradecode(rs.getString("GRADECODE"));
            }
            if (rs.getString("D_PLINE") != null) {
                ordProcEntity.setGroupRollAll(rs.getString("D_PLINE"));
            }

            if (rs.getString("D_IN_MATERIAL_NO") != null) {
                dInMaterialNo = rs.getString("D_IN_MATERIAL_NO");
                outPlMaterialNo = dInMaterialNo;
            }
            else if (rs.getString("C_OUT_MATERIAL_NO") != null) {
                outPlMaterialNo = rs.getString("C_OUT_MATERIAL_NO");
            }
            else if (rs.getString("B_OUT_MATERIAL_NO") != null) {
                outPlMaterialNo = rs.getString("B_OUT_MATERIAL_NO");
            }
            else if (rs.getString("A_OUT_MATERIAL_NO") != null) {
                outPlMaterialNo = rs.getString("A_OUT_MATERIAL_NO");
            }
            ordProcEntity.setStuffProperty(CoreOrdBase
                    .stuffProperty(outPlMaterialNo));

            if (rs.getString("D_OUT_MATERIAL_NO") != null) {
                dOutMaterialNo = rs.getString("D_OUT_MATERIAL_NO");
            }
            if (rs.getString("E_IN_MATERIAL_NO") != null) {
                eInMaterialNo = rs.getString("E_IN_MATERIAL_NO");
                ordProcEntity.setEInMaterialNo(eInMaterialNo);
            }
            if (rs.getString("E_IN_MATERIAL_DESC") != null) {
                ordProcEntity.setEInMaterialDesc(rs
                        .getString("E_IN_MATERIAL_DESC"));
            }
            if (rs.getString("E_OUT_MATERIAL_NO") != null) {
                eOutMaterialNo = rs.getString("E_OUT_MATERIAL_NO");
            }
        }
        else {
            this.errMessage = "未找到对应BOM信息。";
            return false;
        }
        rs.close();
        ps.close();

        // 查询交货行信息
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.getPlnSaleOrdInf");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, ordLnDlyPk);
        ps.setObject(2, _plnDivideId);
        rs = ps.executeQuery();
        if (rs.next()) {
            if (rs.getDouble("PLAN_TOT_LEN_D") != 0) {
                double orderQtyD = 0;
                orderQtyD = rs.getDouble("ORDER_QTY_D") * planTotLenD
                        / rs.getDouble("PLAN_TOT_LEN_D");
                ordProcEntity.setOrderQtyD(String.valueOf(orderQtyD));
            }

            inOrdParam.setLengthMax(rs.getDouble("LENGTHMAX"));
            inOrdParam.setLengthMin(rs.getDouble("LENGTHMIN"));
            inOrdParam.setOutdiameter(rs.getDouble("OUTDIAMETER"));
            inOrdParam.setWallthick(rs.getDouble("WALLTHICK"));
            if (rs.getString("MODEL_DESC") != null) {
                inOrdParam.setModelDesc(rs.getString("MODEL_DESC"));
            }
            inOrdParam.setDelvryRangeMax(rs.getDouble("DELVRY_RANGE_MAX"));
            inOrdParam.setDelvryRangeMin(rs.getDouble("DELVRY_RANGE_MIN"));
            if (rs.getString("DELVRY_RANGE_TPE") != null
                    && rs.getString("DELVRY_RANGE_TPE").trim().equals("绝对值")) {
                inOrdParam.setDelvryRangeTpe(2);
            }
            else {
                inOrdParam.setDelvryRangeTpe(1);
            }
            inOrdParam.setSigllen(rs.getDouble("SIGL_LEN"));
            inOrdParam.setFootmin(rs.getDouble("SHORTEST"));
            if (rs.getDouble("SHRT_LEN_RATO") > 0) {
                inOrdParam.setShrtStove(true);
            }
            else {
                inOrdParam.setShrtStove(false);
            }
            inOrdParam.setInspectLen(rs.getDouble("INSPECTION_VALUE"));
            if (rs.getString("CODE_JG") != null) {
                codeJg = rs.getString("CODE_JG");
            }

            // 获取交货标准壁厚公差
            CoreOrderStdSic stdTolerance = new CoreOrderStdSic();
            Double[] stdTole = stdTolerance.getStdTole(desginKey, rs
                    .getDouble("OUTDIAMETER"), rs.getDouble("WALLTHICK"));
            if (stdTole != null) {
                inOrdParam.setStdWallthickMax(stdTole[0]);
                inOrdParam.setStdWallthickMin(stdTole[1]);
            }
            if (rs.getString("PRDCR_NO") != null
                    && !rs.getString("PRDCR_NO").equals("")) {
                prdcrPro = CoreOrdLinePrdcrLst.getOrdPrdcrpro(conn, rs
                        .getString("PRDCR_NO"), dPline);
            }
            inOrdParam.setAvgLenMin(rs.getDouble("AVG_LEN_MIN"));
        }
        else {
            this.errMessage = "未找到对应交货行信息。";
            return false;
        }
        rs.close();
        ps.close();

        // _start 非管坯的合同计算
        if (!isGpOrd) {
            // 查询接箍信息
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcAdjust.getComMscJg");
            ps = conn.prepareStatement(sql);
            ps.setObject(1, codeJg);
            rs = ps.executeQuery();
            if (rs.next()) {
                inOrdParam.setWeightJg(rs.getDouble("WEIGHT_JG"));
                inOrdParam.setCheckJVal(rs.getDouble("CHECK_J_VAL"));
            }
            rs.close();
            ps.close();
           
            // 查询轧管工序切头尾
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcAdjust.getMaterialDPl");
            PreparedStatement psta = conn.prepareStatement(sql);
            psta.setObject(1, dInMaterialNo);
            psta.setObject(2, dOutMaterialNo);
            psta.setObject(3, dPline);
            ResultSet result = psta.executeQuery();
            if (result.next()) {
                double cutHeadEnd = result.getDouble("CROP_END")
                        + result.getDouble("CROP_HEAD");
                tubeEndRatio = result.getDouble("TUBE_END_RATIO");
                cutMax = result.getDouble("DBL_LEN_MAX");
                // 切头尾默认1000mm
                if (cutHeadEnd == 0) {
                    cutHeadEnd = 1000;
                }
                inOrdParam.setCutHeadEnd(cutHeadEnd);
            }

            // 查询轧管产线基础信息
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcAdjust.getZgBasePline");
            psta = conn.prepareStatement(sql);
            psta.setObject(1, dPline);
            result = psta.executeQuery();
            if (result.next()) {
                inOrdParam.setLengthColdbed(result.getDouble("LENGTH_COLDBED"));
                inOrdParam
                        .setLengthMaxRing(result.getDouble("LENGTH_MAX_RING"));
                inOrdParam.setBurnoutRate(result.getDouble("BURNOUT_RATE"));
                inOrdParam.setPlineWallthick(result.getDouble("TOLERANCE_ZONE")
                        * inOrdParam.getWallthick() / 100);
                inOrdParam.setToleranceZone(result.getDouble("TOLERANCE_ZONE"));
                inOrdParam.setLengthMinTube(result.getDouble("LENGTH_MIN_TUBE"));
                inOrdParam.setLengthMaxTube(result.getDouble("LENGTH_MAX_TUBE"));
            }
            result.close();
            psta.close();

            // 查询镦拔扩工序加长
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcAdjust.getMaterialEPl");
            psta = conn.prepareStatement(sql);
            psta.setObject(1, eInMaterialNo);
            psta.setObject(2, eOutMaterialNo);
            psta.setObject(3, desginKey);
            psta.setObject(4, mscPline);
            result = psta.executeQuery();
            if (result.next()) {
                double cutHeadEnd = result.getDouble("CROP_END")
                        + result.getDouble("CROP_HEAD");
                double lenDc = result.getDouble("UPSETTING_LENGTH");
                double burnoutRate = result.getDouble("BURNOUT_RATE");
                String plineCode = result.getString("PLINE_CODE");
                // 默认值
                if (plineCode.trim().equals("C021")
                        || plineCode.trim().equals("C067")) {
                    if (lenDc == 0) {
                        lenDc = CoreOrdBase.addDbkDefault(plineCode);
                    }
                }
                else {
                    if (cutHeadEnd == 0) {
                        cutHeadEnd = CoreOrdBase.addDbkDefault(plineCode);
                    }
                }
                inOrdParam.setBurnoutDbk(burnoutRate);
                inOrdParam.setAddLengthDbk(cutHeadEnd);
                inOrdParam.setAddLengthDc(lenDc);
            }
            result.close();
            psta.close();

            // 轧管内控壁厚公差
            CoreTolerOfNk tolerOfNk = new CoreTolerOfNk();
            CoreTolerOfNkParam nkParam = new CoreTolerOfNkParam();
            nkParam.setBias_code("404019");
            nkParam.setOutdiameter(inOrdParam.getOutdiameter());
            nkParam.setWallthick(inOrdParam.getWallthick());
            nkParam.setSic(sicZg);
            nkParam.setLengthmax(inOrdParam.getLengthMax());
            nkParam.setLengthmin(inOrdParam.getLengthMin());
            nkParam = tolerOfNk.queryTolerance(nkParam,desginKey,mscPline,"1");
            if (nkParam != null) {
                double wallUpper = nkParam.getWallUpper();
                double wallLower = nkParam.getWallLower();
                double percentUp = 0;
                double percentLp = 0;
                if (wallUpper == 0 && wallLower == 0) {
                    wallUpper = inOrdParam.getStdWallthickMax();
                    wallLower = inOrdParam.getStdWallthickMin();
                }
                inOrdParam.setNkWallthickMax(wallUpper);
                inOrdParam.setNkWallthickMin(wallLower);
                if (inOrdParam.getWallthick() != 0) {
                    percentUp = 100 * wallUpper / inOrdParam.getWallthick();
                    percentLp = 100 * wallLower / inOrdParam.getWallthick();
                }
                ordProcEntity.setHeightNkMax(String.valueOf(percentUp));
                ordProcEntity.setHeightNkMin(String.valueOf(percentLp));
            }
            // 轧管内控外径公差
            nkParam.setBias_code("404012");
            nkParam.setOutdiameter(inOrdParam.getOutdiameter());
            nkParam.setWallthick(inOrdParam.getWallthick());
            nkParam.setSic(sicZg);
            nkParam.setLengthmax(inOrdParam.getLengthMax());
            nkParam.setLengthmin(inOrdParam.getLengthMin());
            nkParam = tolerOfNk.queryToleranceAim(nkParam,desginKey,mscPline,"1");
            if (nkParam != null) {
                double aimUpper = nkParam.getAimUpper();
                double aimLower = nkParam.getAimLower();
//                double percentUp = 0;
//                double percentLp = 0;
                if (aimUpper == 0 && aimLower == 0) {
                    aimUpper = inOrdParam.getOutdOrdMax();
                    aimLower = inOrdParam.getOutdOrdMin();
                }
                inOrdParam.setNkAimthickMax(aimUpper);
                inOrdParam.setNkAimthickMin(aimLower);
//                if (inOrdParam.getOutdiameter() != 0) {
//                    percentUp = 100 * aimUpper / inOrdParam.getOutdiameter();
//                    percentLp = 100 * aimLower / inOrdParam.getOutdiameter();
//                }
//                ordProcEntity.geth(String.valueOf(percentUp));
//                ordProcEntity.setHeightNkMin(String.valueOf(percentLp));
            }
            inOrdParam.setCutMax(cutMax);
            inOrdParam.setTubeEndRatio(tubeEndRatio);
            inOrdParam.setOrdLnDlyPk(ordLnDlyPk);
            OutOrdParamEntity outEntity = PlnProducCal.calculate(conn,inOrdParam);
            if (outEntity.getErrCode() == -1) {
                this.errMessage = outEntity.getErrMessage();
                return false;
            }
            ordProcEntity
                    .setWeightPerM(String.valueOf(outEntity.getWeightMi()));
            ordProcEntity.setPlanWtD(String.valueOf(outEntity.getWeightInA()));
            ordProcEntity.setPlanNumD(String.valueOf(outEntity.getPlanNum()));
            ordProcEntity
                    .setAimLenEnd(String.valueOf(outEntity.getAimLength()));
            ordProcEntity.setAimLenRoll(String.valueOf(outEntity
                    .getAimlengthZg()));
            ordProcEntity.setPlanPMain(String.valueOf(outEntity.getWeightPc()));
            ordProcEntity.setPlanTotLenD(String.valueOf(outEntity
                    .getAimLength()
                    * outEntity.getPlanNum()));
            ordProcEntity.setTotLenOneP(String.valueOf(outEntity
                    .getTotLenOneP()));
            ordProcEntity.setCutNumP(String.valueOf(outEntity.getCutNumP()));
            ordProcEntity.setAimWallthick(String.valueOf(outEntity
                    .getAimWallthick()));
            ordProcEntity.setRollLength(String.valueOf(outEntity
                    .getRollLength()));
            ordProcEntity.setOutdOrdMax(String.valueOf(inOrdParam
                    .getOutdOrdMax()));
            ordProcEntity.setOutdOrdMin(String.valueOf(inOrdParam
                    .getOutdOrdMin()));
            ordProcEntity.setAimOutdiameter(String.valueOf(outEntity.getAimOutdiameter()));
            ordProcEntity.setFeedRate(String.valueOf(outEntity.getFeedRate()));
            ordProcEntity.setCoefficient(String.valueOf(outEntity.getCoefficient()));
            ordProcEntity.setCoefficientMin(String.valueOf(outEntity.getCoefficientMin()));
            ordProcEntity.setPlanPMainMin(String.valueOf(outEntity.getPlanPMainMin()));
            ordProcEntity.setWeightKzM(String.valueOf(outEntity.getWeightKzM()));
            ordProcEntity.setAimWtEnd(String.valueOf(outEntity.getAimWtEnd()));
        }
        else {
            this.errMessage = "管坯合同不允许拆分！";
            return false;
        }
        // _end
        // _end

        // 查询制程适用钢种
        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.getMscPlineGrade");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, desginKey);
        ps.setObject(2, mscPline);
        rs = ps.executeQuery();
        if (rs.next()) {
            if (rs.getString("GRADENAMEALL") != null) {
                ordProcEntity.setGradecodeAll(rs.getString("GRADENAMEALL"));
            }
        }
        rs.close();
        ps.close();

        sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnProcAdjust.getProcDivideId");
        ps = conn.prepareStatement(sql);
        ps.setObject(1, ordLnDlyPk);
        rs = ps.executeQuery();
        if (rs.next()) {
            String plnDivideId = "";
            CorePlnProcessOrd prcOrder = new CorePlnProcessOrd();
            if (rs.getString("PLN_DIVIDE_ID") != null) {
                plnDivideId = rs.getString("PLN_DIVIDE_ID");
            }
            ordProcEntity.setOrdLnDlyPk(ordLnDlyPk);
            ordProcEntity.setPlnDivideId(plnDivideId);
            ordProcEntity.setCraftSeq(craftSeq);
            ordProcEntity.setIndexSeq(mscPline);
            ordProcEntity.setBom(bom);
            ordProcEntity.setGroupRoll(dPline);
            ordProcEntity.setIssuedMan(name);
            ordProcEntity.setIssuedMan(name);
            ordProcEntity.setPrdcrpro(prdcrPro);
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnProcAdjust.addProcOrd");

            String sqlAdd = EntityTool.fillSqlByEntity(sql, ordProcEntity);
            ps = conn.prepareStatement(sqlAdd);
            ps.setObject(1, _plnDivideId);
            ps.executeUpdate();

            String versionNo = "";
            /*
             * versionNo = CorePlnGxOrdM.getSendVersionNo(conn);
             * CorePlnGxOrdM.addIussedVersion(conn, versionNo, name);
             */
            if (!prcOrder.addPrcOrder(conn, name, ordLnDlyPk, plnDivideId,
                    versionNo,orderNoSeq,orderSource)) {
                this.errMessage = prcOrder.getErrMessage();
                return false;
            }
        }
        else {
            return false;
        }
        rs.close();
        ps.close();
        return true;
    }

    /**
     * 错误信息
     * @return the errMessage
     */
    public String getErrMessage() {
        return errMessage;
    }
}