package com.steering.pss.plnsaleord.processOrder;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.order.CorePlnProcessOrd;
import com.steering.pss.plnsaleord.order.baseMethod.CoreOrdBase;
import com.steering.pss.plnsaleord.order.baseMethod.CorePlnProcAdjust;
import com.steering.pss.plnsaleord.order.model.CraftOrdDesignMscPlEntityO;
import com.steering.pss.plnsaleord.order.model.SlmOrdDesignBomEntity;
import com.steering.pss.plnsaleord.processOrder.entity.MscPlineChangeEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnSaleordProcEntity;

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

/**
 * 工序合同
 * @author Administrator
 */
public class CoreProcessOrder extends DBCommon {
    /**
     * 查询销售合同
     * @param params
     * @return CoreReturnObject
     */
    public CoreReturnObject queryOrderInfo(String orderNo, String beginTime,
            String endTime, String isFinish) {
        List<String> params = new ArrayList<String>();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryOrderInfo");
        if (orderNo.length() > 0) {
            params.add(orderNo);
            sql += "  AND (T1.ORDER_NO || '/' || T1.ORDER_SEQ) LIKE '%' || NLS_UPPER(?) || '%'";
        }
        if (beginTime.length() > 0 && endTime.length() > 0) {
            params.add(beginTime);
            params.add(endTime);
            sql += " AND T1.ISSUED_TIME BETWEEN TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') AND  TO_DATE(?,'YYYY-MM-DD HH24:MI:SS')";
        }
        if (isFinish.equals("1")) {
            sql += " AND (T1.PLANSTATUS IN ('2', '3') OR "
                    + "(T1.PLANSTATUS IN ('4', '5') AND "
                    + "TO_DATE(T1.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        else if (isFinish.equals("2")) {
            sql += " AND (T1.PLANSTATUS IN ('2', '3', '4') OR "
                    + "(T1.PLANSTATUS IN ('5') AND "
                    + "TO_DATE(T1.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        sql += " ORDER BY T1.ORDER_NO,T1.ORDER_SEQ,T1.DELIVERY_NO";
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询铸造工序
     * @param params
     * @return
     */
    public CoreReturnObject queryGP(ArrayList<String> params) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryGP");
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询轧管工序
     * @param params
     * @return
     */
    public CoreReturnObject queryZG(ArrayList<String> params) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryZG");
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询墩拔扩工序
     * @param params
     * @return
     */
    public CoreReturnObject queryDBK(ArrayList<String> params) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryDBK");
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询热处理工序
     * @param params
     * @return
     */
    public CoreReturnObject queryRCL(ArrayList<String> params) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryRCL");
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询加工工序
     * @param params
     * @return
     */
    public CoreReturnObject queryJG(ArrayList<String> params) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.queryJG");
        return this.getData(sql, params.toArray());
    }

    /**
     * 获取工序成材率
     * @param process 工序
     * @param ordLnDlyPk 交货行主键
     * @param plnDivideId 排产流水号
     * @param planGroupId 联动主号
     * @return CoreReturnObject
     */
    public CoreReturnObject getGetRate(String process, String ordLnDlyPk,
            String plnDivideId, String planGroupId) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        String sql = "";
        try {
            String getRate = "1";
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            if (process.equals("B")) {
                // sql =
                // "select t.getrate from pln_order_dz t where t.ord_ln_dly_pk = ?  and t.pln_divide_id = ?  and t.plan_group_id = ?";
            }
            else if (process.equals("C")) {
                sql = "select t.getrate from pln_order_dz t ";
            }
            else if (process.equals("D")) {
                sql = "select t.getrate from pln_order_zg t";
            }
            else if (process.equals("E")) {
                sql = "select t.getrate from pln_order_dbk t ";
            }
            else if (process.equals("F")) {
                sql = "select t.getrate from pln_order_rcl t ";
            }
            else {
                sql = "select t.getrate from pln_order_jgx t ";
            }
            sql += " where t.ord_ln_dly_pk = ?  and t.pln_divide_id = ?  and t.plan_group_id = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setObject(1, ordLnDlyPk);
            ps.setObject(2, plnDivideId);
            ps.setObject(3, planGroupId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                getRate = rs.getString(1);
            }
            rs.close();
            ps.close();
            core.setV_errMsg(getRate);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return core;
    }

    /**
     * 保存修改下发
     * @param beginProcEntity
     * @param addProcEntitys
     * @param processCode
     * @param isUseNewCraft
     * @return
     * @throws ParseException
     */
    public CoreReturnObject saveChangeProc(String beginProcStr,
            ArrayList<MscPlineChangeEntity> addProcEntitys, String processCode,
            Boolean isUseNewCraft, String orderNoSeq, String orderSource) {
        CoreReturnObject cro = new CoreReturnObject();
        JSONObject json = JSONObject.fromObject(beginProcStr);
        PlnSaleordProcEntity beginProcEntity = (PlnSaleordProcEntity) JSONObject
                .toBean(json, PlnSaleordProcEntity.class);
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            double planWt = 0;// 原记录合同量
            double planTotLen = 0;// 原记录排产分配总长
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreProcessOrder.queryPlnProcOrd");
            ps = conn.prepareStatement(sql);
            ps.setObject(1, beginProcEntity.getOrdLnDlyPk());
            ps.setObject(2, beginProcEntity.getPlnDivideId());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                PreparedStatement psta = null;
                if (rs.getDouble("PLAN_WT_D") == 0) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("原合同量有误！");
                    return cro;
                }
                if (rs.getDouble("PLAN_TOT_LEN_D") == 0) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("原合同量有误！");
                    return cro;
                }
                planWt = rs.getDouble("PLAN_WT_D");
                planTotLen = rs.getDouble("PLAN_TOT_LEN_D");
                double rate = Double.parseDouble(beginProcEntity.getPlanWtD())
                        / planWt;// 原记录分配比率
                if (!isUseNewCraft) {
                    // 修改原记录
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreProcessOrder.updateBeginProcOrd");
                    String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
                    sqlUp = EntityTool.fillSqlByEntity(sqlUp, beginProcEntity);
                    psta = conn.prepareStatement(sqlUp);
                    psta.executeUpdate();
                    psta.close();

                    // 更新轧管工序合同量
                    updatePlnOrderZg(conn, beginProcEntity.getOrdLnDlyPk(),
                            beginProcEntity.getPlnDivideId(), rate,
                            addProcEntitys.get(0).getCreatName());

                    // 更新镦拔扩工序合同量
                    updatePlnOrderDbk(conn, beginProcEntity.getOrdLnDlyPk(),
                            beginProcEntity.getPlnDivideId(), rate,
                            addProcEntitys.get(0).getCreatName());

                    // 更新热处理工序合同量
                    updatePlnOrderRcl(conn, beginProcEntity.getOrdLnDlyPk(),
                            beginProcEntity.getPlnDivideId(), rate,
                            addProcEntitys.get(0).getCreatName());

                    // 更新加工工序合同量
                    updatePlnOrderJgx(conn, beginProcEntity.getOrdLnDlyPk(),
                            beginProcEntity.getPlnDivideId(), rate,
                            addProcEntitys.get(0).getCreatName());
                }
                else {
                    // 修改原记录
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreProcessOrder.updateBeginProcOrd");
                    String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
                    sqlUp = EntityTool.fillSqlByEntity(sqlUp, beginProcEntity);
                    psta = conn.prepareStatement(sqlUp);
                    psta.executeUpdate();
                    psta.close();

                    MscPlineChangeEntity changeEntity = addProcEntitys.get(0);
                    CorePlnProcessOrd prcOrder = new CorePlnProcessOrd();
                    if (processCode.compareTo("G") >= 0) {
                        // 更新加工工序合同量
                        updatePlnOrderJgx(conn,
                                beginProcEntity.getOrdLnDlyPk(),
                                beginProcEntity.getPlnDivideId(), rate,
                                changeEntity.getCreatName());
                    }
                    else {
                        prcOrder.deletePlnOrderJgx(conn, beginProcEntity
                                .getOrdLnDlyPk(), beginProcEntity
                                .getPlnDivideId(), changeEntity.getCreatName());
                    }

                    if (processCode.compareTo("F") >= 0) {
                        // 更新热处理工序合同量
                        updatePlnOrderRcl(conn,
                                beginProcEntity.getOrdLnDlyPk(),
                                beginProcEntity.getPlnDivideId(), rate,
                                changeEntity.getCreatName());
                    }
                    else {
                        prcOrder.deletePlnOrderRcl(conn, beginProcEntity
                                .getOrdLnDlyPk(), beginProcEntity
                                .getPlnDivideId(), changeEntity.getCreatName());
                    }

                    if (processCode.compareTo("E") >= 0) {
                        // 更新镦拔扩工序合同量
                        updatePlnOrderDbk(conn,
                                beginProcEntity.getOrdLnDlyPk(),
                                beginProcEntity.getPlnDivideId(), rate,
                                changeEntity.getCreatName());
                    }
                    else {
                        prcOrder.deletePlnOrderDbk(conn, beginProcEntity
                                .getOrdLnDlyPk(), beginProcEntity
                                .getPlnDivideId(), changeEntity.getCreatName());
                    }

                    if (processCode.compareTo("D") >= 0) {
                        // 更新轧管工序合同量
                        updatePlnOrderZg(conn, beginProcEntity.getOrdLnDlyPk(),
                                beginProcEntity.getPlnDivideId(), rate,
                                changeEntity.getCreatName());
                    }
                    else {
                        prcOrder.deletePlnOrderZg(conn, beginProcEntity
                                .getOrdLnDlyPk(), beginProcEntity
                                .getPlnDivideId(), changeEntity.getCreatName());
                    }

                    String versionNo = "";
                    /*
                     * versionNo = CorePlnGxOrdM.getSendVersionNo(conn);
                     * CorePlnGxOrdM.addIussedVersion(conn, versionNo,
                     * changeEntity.getCreatName());
                     */
                    if (changeOrdProCraft(conn, beginProcEntity, changeEntity)) {
                        if (prcOrder.addPrcOrder1(conn, changeEntity
                                .getCreatName(), beginProcEntity
                                .getOrdLnDlyPk(), beginProcEntity
                                .getPlnDivideId(), versionNo, processCode,
                                orderNoSeq, orderSource)) {
                            try {
                                conn.rollback();
                            }
                            catch (SQLException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            cro.setV_errCode(-1);
                            cro.setV_errMsg(prcOrder.getErrMessage());
                            return cro;
                        }
                    }
                }
            }
            ps.close();
            rs.close();

            // 新增拆分记录
            CorePlnProcAdjust procAdjust = new CorePlnProcAdjust();
            for (MscPlineChangeEntity changeEntity : addProcEntitys) {
                changeEntity.setPlanTotLenD(changeEntity.getPlanWeightD()
                        * planTotLen / planWt);
                if (!procAdjust.addPrcOrder(conn, changeEntity.getCreatName(),
                        changeEntity.getOrdLnDlyPk(), changeEntity
                                .getPlnDivideId(), changeEntity.getCraftSeq(),
                        changeEntity.getMscPline(), changeEntity.getBom(),
                        changeEntity.getdPline(),
                        changeEntity.getPlanTotLenD(), orderNoSeq, orderSource)) {
                    try {
                        conn.rollback();
                    }
                    catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cro.setV_errCode(-1);
                    cro.setV_errMsg(procAdjust.getErrMessage());
                    return cro;
                }

            }

            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());
            return cro;
        }
        catch (ParseException pe) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(pe.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 ordLnDlyPk
     * @param plnDivideId
     * @param rate
     * @throws SQLException
     */
    public void updatePlnOrderJgx(Connection conn, String ordLnDlyPk,
            String plnDivideId, double rate, String operaMan)
            throws SQLException {
        PreparedStatement psta = null;
        // 更新加工工序合同量
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.selectPlnOrderJgx");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnDlyPk);
        psta.setObject(2, plnDivideId);
        ResultSet rs = psta.executeQuery();
        while (rs.next()) {
            String proOrderNo = rs.getString("PRO_ORDER_NO");
            PreparedStatement ps = null;
            if (rs.getString("PRO_PLAN_ID") != null) {
                String proPlanId = rs.getString("PRO_PLAN_ID");
                double ordWt = rs.getDouble("ORDERWEIGHT");
                int ordNum = rs.getInt("ORDERNUM");
                double inOrdWt = rs.getDouble("IN_WEIGHT");
                int inOrdNum = rs.getInt("IN_NUM");
                double finishWt = rs.getDouble("FINISHWEIGHT");
                double compare = (new BigDecimal(ordWt * rate - finishWt))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (compare < 0) {
                    rate = finishWt / ordWt;
                }
                if ((new BigDecimal(rate))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue() >= 1) {
                    break;
                }

                CorePlnOrdProUseTime.updateOrderJgxS(conn, proPlanId,
                        -(ordWt - ordWt * rate), -(ordNum - (int) Math
                                .ceil(ordNum * rate)));
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreProcessOrder.updatePlnGxJgxM");
                ps = conn.prepareStatement(sql);
                ps.setObject(1, -(ordWt - ordWt * rate));
                ps.setObject(2, -(ordNum - Math.ceil(ordNum * rate)));
                ps.setObject(3, -(inOrdWt - inOrdWt * rate));
                ps.setObject(4, -(inOrdNum - Math.ceil(inOrdNum * rate)));
                ps.setObject(5, operaMan);
                ps.setObject(6, proPlanId);
                ps.executeUpdate();
                ps.close();
            }

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreProcessOrder.updatePlnOrderJgx");
            String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
            ps = conn.prepareStatement(sqlUp);
            ps.setObject(1, proOrderNo);
            ps.executeUpdate();
            ps.close();
        }
        rs.close();
        psta.close();
    }

    /**
     * 更新热处理工序合同
     * @param conn
     * @param ordLnDlyPk
     * @param plnDivideId
     * @param rate
     * @throws SQLException
     */
    public void updatePlnOrderRcl(Connection conn, String ordLnDlyPk,
            String plnDivideId, double rate, String operaMan)
            throws SQLException {
        PreparedStatement psta = null;
        // 更新热处理工序合同量
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.selectPlnOrderRcl");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnDlyPk);
        psta.setObject(2, plnDivideId);
        ResultSet rs = psta.executeQuery();
        while (rs.next()) {
            String proOrderNo = rs.getString("PRO_ORDER_NO");
            PreparedStatement ps = null;

            if (rs.getString("PRO_PLAN_ID") != null) {
                String proPlanId = rs.getString("PRO_PLAN_ID");
                double ordWt = rs.getDouble("ORDERWEIGHT");
                int ordNum = rs.getInt("ORDERNUM");
                double inOrdWt = rs.getDouble("IN_WEIGHT");
                int inOrdNum = rs.getInt("IN_NUM");
                double finishWt = rs.getDouble("FINISHWEIGHT");
                double compare = (new BigDecimal(ordWt * rate - finishWt))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (compare < 0) {
                    rate = finishWt / ordWt;
                }
                if ((new BigDecimal(rate))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue() >= 1) {
                    break;
                }

                CorePlnOrdProUseTime.updateOrderRclS(conn, proPlanId,
                        -(ordWt - ordWt * rate), -(ordNum - (int) Math
                                .ceil(ordNum * rate)));
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreProcessOrder.updatePlnGxRclM");
                ps = conn.prepareStatement(sql);
                ps.setObject(1, -(ordWt - ordWt * rate));
                ps.setObject(2, -(ordNum - Math.ceil(ordNum * rate)));
                ps.setObject(3, -(inOrdWt - inOrdWt * rate));
                ps.setObject(4, -(inOrdNum - Math.ceil(inOrdNum * rate)));
                ps.setObject(5, operaMan);
                ps.setObject(6, proPlanId);
                ps.executeUpdate();
                ps.close();
            }

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreProcessOrder.updatePlnOrderRcl");
            String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
            ps = conn.prepareStatement(sqlUp);
            ps.setObject(1, proOrderNo);
            ps.executeUpdate();
            ps.close();
        }
        rs.close();
        psta.close();
    }

    /**
     * 更新镦拔扩工序合同
     * @param conn
     * @param ordLnDlyPk
     * @param plnDivideId
     * @param rate
     * @throws SQLException
     */
    public void updatePlnOrderDbk(Connection conn, String ordLnDlyPk,
            String plnDivideId, double rate, String operaMan)
            throws SQLException {
        PreparedStatement psta = null;
        // 更新镦拔扩工序合同量
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.selectPlnOrderDbk");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnDlyPk);
        psta.setObject(2, plnDivideId);
        ResultSet rs = psta.executeQuery();
        while (rs.next()) {
            String proOrderNo = rs.getString("PRO_ORDER_NO");
            PreparedStatement ps = null;
            if (rs.getString("PRO_PLAN_ID") != null) {
                String proPlanId = rs.getString("PRO_PLAN_ID");
                double ordWt = rs.getDouble("ORDERWEIGHT");
                int ordNum = rs.getInt("ORDERNUM");
                double inOrdWt = rs.getDouble("IN_WEIGHT");
                int inOrdNum = rs.getInt("IN_NUM");
                double finishWt = rs.getDouble("FINISHWEIGHT");
                double compare = (new BigDecimal(ordWt * rate - finishWt))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (compare < 0) {
                    rate = finishWt / ordWt;
                }
                if ((new BigDecimal(rate))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue() >= 1) {
                    break;
                }

                CorePlnOrdProUseTime.updateOrderDbkS(conn, proPlanId,
                        -(ordWt - ordWt * rate), -(ordNum - (int) Math
                                .ceil(ordNum * rate)));

                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreProcessOrder.updatePlnGxDbkM");
                ps = conn.prepareStatement(sql);
                ps.setObject(1, -(ordWt - ordWt * rate));
                ps.setObject(2, -(ordNum - Math.ceil(ordNum * rate)));
                ps.setObject(3, -(inOrdWt - inOrdWt * rate));
                ps.setObject(4, -(inOrdNum - Math.ceil(inOrdNum * rate)));
                ps.setObject(5, operaMan);
                ps.setObject(6, proPlanId);
                ps.executeUpdate();
                ps.close();
            }

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreProcessOrder.updatePlnOrderDbk");
            String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
            ps = conn.prepareStatement(sqlUp);
            ps.setObject(1, proOrderNo);
            ps.executeUpdate();
            ps.close();
        }
        rs.close();
        psta.close();
    }

    /**
     * 更新轧管工序合同
     * @param conn
     * @param ordLnDlyPk
     * @param plnDivideId
     * @param rate
     * @throws SQLException
     */
    public void updatePlnOrderZg(Connection conn, String ordLnDlyPk,
            String plnDivideId, double rate, String operaMan)
            throws SQLException {
        PreparedStatement psta = null;
        // 更新轧管工序合同量
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreProcessOrder.selectPlnOrderZg");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnDlyPk);
        psta.setObject(2, plnDivideId);
        ResultSet rs = psta.executeQuery();
        while (rs.next()) {
            String proOrderNo = rs.getString("PRO_ORDER_NO");
            PreparedStatement ps = null;
            if (rs.getString("PRO_PLAN_ID") != null) {
                String proPlanId = rs.getString("PRO_PLAN_ID");
                double ordWt = rs.getDouble("ORDERWEIGHT");
                int ordNum = rs.getInt("ORDERNUM");
                double inOrdWt = rs.getDouble("IN_WT");
                int inOrdNum = rs.getInt("IN_NUM");
                double finishWt = rs.getDouble("FINISHWEIGHT");
                double compare = (new BigDecimal(ordWt * rate - finishWt))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                if (compare < 0) {
                    rate = finishWt / ordWt;
                }
                if ((new BigDecimal(rate))
                        .setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue() >= 1) {
                    break;
                }

                CorePlnOrdProUseTime.updateOrderZgS(conn, proPlanId,
                        -(ordWt - ordWt * rate), -(ordNum - (int) Math
                                .ceil(ordNum * rate)));

                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreProcessOrder.updatePlnGxZgM");
                ps = conn.prepareStatement(sql);
                ps.setObject(1, -(ordWt - ordWt * rate));
                ps.setObject(2, -(ordNum - Math.ceil(ordNum * rate)));
                ps.setObject(3, -(inOrdWt - inOrdWt * rate));
                ps.setObject(4, -(inOrdNum - Math.ceil(inOrdNum * rate)));
                ps.setObject(5, operaMan);
                ps.setObject(6, proPlanId);
                ps.executeUpdate();
                ps.close();
            }

            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreProcessOrder.updatePlnOrderZg");
            String sqlUp = sql.replace("#RATE#", String.valueOf(rate));
            ps = conn.prepareStatement(sqlUp);
            ps.setObject(1, proOrderNo);
            ps.executeUpdate();
            ps.close();
        }
        rs.close();
        psta.close();
    }

    /**
     * 修改原排产记录
     * @param changeEntity
     * @return
     * @throws ParseException
     */
    public CoreReturnObject modifyChangeProc(MscPlineChangeEntity changeEntity,
            String orderNoSeq, String orderSource) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            PlnSaleordProcEntity procEntity = new PlnSaleordProcEntity();
            procEntity.setOrdLnDlyPk(changeEntity.getOrdLnDlyPk());
            procEntity.setPlnDivideId(changeEntity.getPlnDivideId());
            if (changeOrdProCraft(conn, procEntity, changeEntity)) {
                CorePlnProcessOrd prcOrder = new CorePlnProcessOrd();
                prcOrder.deletePlnOrderJgx(conn, changeEntity.getOrdLnDlyPk(),
                        changeEntity.getPlnDivideId(), changeEntity
                                .getCreatName());

                prcOrder.deletePlnOrderRcl(conn, changeEntity.getOrdLnDlyPk(),
                        changeEntity.getPlnDivideId(), changeEntity
                                .getCreatName());

                prcOrder.deletePlnOrderDbk(conn, changeEntity.getOrdLnDlyPk(),
                        changeEntity.getPlnDivideId(), changeEntity
                                .getCreatName());

                prcOrder.deletePlnOrderZg(conn, changeEntity.getOrdLnDlyPk(),
                        changeEntity.getPlnDivideId(), changeEntity
                                .getCreatName());

                String versionNo = "";
                /*
                 * versionNo = CorePlnGxOrdM.getSendVersionNo(conn); //新增下发版次记录
                 * CorePlnGxOrdM.addIussedVersion(conn, versionNo,
                 * changeEntity.getCreatName());
                 */
                if (!prcOrder.addPrcOrder(conn, changeEntity.getCreatName(),
                        changeEntity.getOrdLnDlyPk(), changeEntity
                                .getPlnDivideId(), versionNo, orderNoSeq,
                        orderSource)) {
                    try {
                        conn.rollback();
                    }
                    catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    cro.setV_errCode(-1);
                    cro.setV_errMsg(prcOrder.getErrMessage());
                    return cro;
                }
            }
            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());
        }
        catch (ParseException pe) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(pe.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 procEntity
     * @param changeEntity
     * @return
     * @throws SQLException
     */
    public boolean changeOrdProCraft(Connection conn,
            PlnSaleordProcEntity procEntity, MscPlineChangeEntity changeEntity)
            throws SQLException {
        String desginkey = "";
        String outsStlPipeFl = "";// 外购管
        procEntity.setCraftSeq(changeEntity.getCraftSeq());
        procEntity.setIndexSeq(changeEntity.getMscPline());
        procEntity.setBom(changeEntity.getBom());
        procEntity.setGroupRoll(changeEntity.getdPline());
        String[] arr = PlnHelper.getArray(conn,
                "CoreProcessOrder.queryOrdDesgin", new String[] {
                        procEntity.getCraftSeq(), procEntity.getOrdLnDlyPk() },
                new String[] { "DESGIN_KEY", "OUTS_STL_PIPE_FL" });
        if (arr != null) {
            desginkey = arr[0];
            outsStlPipeFl = arr[1];
        }
        else {
            return false;
        }

        String wholeBacklog = "";
        String wholeBacklogDesc = "";
        // 获取制程以及其二级工序
        List<CraftOrdDesignMscPlEntityO> mscPlList = PlnHelper.getEntityDatas(
                conn, new String[] { desginkey, changeEntity.getMscPline() },
                "CoreProcessOrder.queryOrdDesginPl",
                CraftOrdDesignMscPlEntityO.class);
        if (mscPlList != null) {
            for (CraftOrdDesignMscPlEntityO mscPlEntity : mscPlList) {
                procEntity.setProcessSeq(mscPlEntity.getWholeBacklog());
                procEntity.setGradecodeAll(mscPlEntity.getGradename());
                if (mscPlEntity.getProcessCode().equals("E")) {
                    procEntity.setBjType(mscPlEntity.getProcessDescC());
                }
                wholeBacklog = mscPlEntity.getWholeBacklog();
                wholeBacklogDesc = mscPlEntity.getWholeBacklogDesc();
            }
        }
        String abc = CoreOrdBase.getAbc(wholeBacklog, wholeBacklogDesc);
        procEntity.setAbc(abc);
        SlmOrdDesignBomEntity bomEntity = PlnHelper.getEntityData(conn,
                new String[] { changeEntity.getBom() },
                "CoreProcessOrder.qeuryDesginBom", SlmOrdDesignBomEntity.class);
        if (bomEntity != null) {
            procEntity.setStuffProperty(CoreOrdBase.stuffProperty(bomEntity
                    .getDInMaterialNo()));
            procEntity.setGradecode(bomEntity.getGradecode());
            procEntity.setEInMaterialNo(bomEntity.getEInMaterialNo());
            procEntity.setEInMaterialDesc(bomEntity.getEInMaterialDesc());
            procEntity.setDimaterYlg(bomEntity.getDimater());
            procEntity.setHeightYlg(bomEntity.getHeight());
        }
        PlnHelper.deleteOrUpdateByEntity(conn,
                "CoreProcessOrder.updateOrdCraftVersion", procEntity);
        if (procEntity.getProcessSeq().contains("D")
                && !changeEntity.getdPline().trim().equals("C072")
                && !outsStlPipeFl.equals("121903")
                && !outsStlPipeFl.equals("121902")) {
            // 重算合同量
        }
        return true;
    }

    /**
     * 新增补量申请
     * @param process
     * @param ordLnDlyPk
     * @param plnDivideId
     * @param planGroupId
     * @param reqOrdQty
     * @param createName
     * @return
     */
    /*
     * public CoreReturnObject addReqOrder(String process, String ordLnDlyPk,
     * String plnDivideId, String planGroupId, Double reqOrdQty, String
     * createName) { CoreReturnObject cro = new CoreReturnObject(); Connection
     * conn = null; PreparedStatement ps = null; try { conn =
     * this.getDao(CoreConstantData.sysbeanstr).getConnection();
     * conn.setAutoCommit(false); String sqlProcD = CoreXmlSqlParsersFactory
     * .getSql("CoreProcessOrder.getRateOfZgOrd"); String sqlProcE =
     * CoreXmlSqlParsersFactory .getSql("CoreProcessOrder.getRateOfDbkOrd");
     * String sqlProcF = CoreXmlSqlParsersFactory
     * .getSql("CoreProcessOrder.getRateOfRclOrd"); String sql =
     * CoreXmlSqlParsersFactory .getSql("CoreProcessOrder.getProcMscPline");
     * boolean fl = false; double outWeight = reqOrdQty; ps =
     * conn.prepareStatement(sql); ps.setObject(1, ordLnDlyPk); ps.setObject(2,
     * plnDivideId); ResultSet rs = ps.executeQuery(); while (rs.next()) { if
     * (rs.getString("PROCESS_CODE") != null) { PreparedStatement psta = null;
     * if(rs.getString("PROCESS_CODE").equals(process)){ fl = true; continue; }
     * if(rs.getString("PROCESS_CODE").equals("D") && fl){ psta =
     * conn.prepareStatement(sqlProcD); psta.setObject(1, planGroupId);
     * ResultSet rsRate = psta.executeQuery(); if (rsRate.next()) {
     * CoreProcessOrdReq.addZgReqOrd(conn, planGroupId, outWeight, createName);
     * if (rsRate.getDouble("GETRATE") == 0) { try { conn.rollback(); } catch
     * (SQLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } cro.setV_errCode(-1);
     * cro.setV_errMsg("轧管工序成材率有误！"); return cro; } outWeight = outWeight /
     * rsRate.getDouble("GETRATE"); } psta.close(); rsRate.close(); } else
     * if(rs.getString("PROCESS_CODE").equals("E") && fl){ psta =
     * conn.prepareStatement(sqlProcE); psta.setObject(1, planGroupId);
     * ResultSet rsRate = psta.executeQuery(); if(rsRate.next()){
     * CoreProcessOrdReq.addDbkReqOrd(conn, planGroupId, outWeight, createName);
     * if (rsRate.getDouble("GETRATE") == 0) { try { conn.rollback(); } catch
     * (SQLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } cro.setV_errCode(-1);
     * cro.setV_errMsg("镦拔扩工序成材率有误！"); return cro; } outWeight = outWeight /
     * rsRate.getDouble("GETRATE"); } psta.close(); rsRate.close(); } else
     * if(rs.getString("PROCESS_CODE").equals("F") && fl){ psta =
     * conn.prepareStatement(sqlProcF); psta.setObject(1, planGroupId);
     * ResultSet rsRate = psta.executeQuery(); if(rsRate.next()){
     * CoreProcessOrdReq.addRclReqOrd(conn, planGroupId, outWeight, createName);
     * if (rsRate.getDouble("GETRATE") == 0) { try { conn.rollback(); } catch
     * (SQLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } cro.setV_errCode(-1);
     * cro.setV_errMsg("热处理工序成材率有误！"); return cro; } outWeight = outWeight /
     * rsRate.getDouble("GETRATE"); } psta.close(); rsRate.close(); } } }
     * ps.close(); rs.close(); 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()); return cro; } finally { try { if
     * (conn != null && !conn.isClosed()) { conn.close(); } } catch
     * (SQLException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } } return cro; }
     */
}
