package com.steering.pss.plnsaleord.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.order.baseMethod.CoreAdjustWellMonth;
import com.steering.pss.plnsaleord.order.model.PlnSaleordProcEntity;

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

/**
 * 排产合同处理
 * @author xiaohai
 */
public class CorePlnModifyOrdDPine extends DBCommon {
    /**
     * 查询
     * @param list
     * @param designOk
     * @return
     */
    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
            String strFinish, Boolean isConfirm) {
        return querySaleOrder(list,strFinish,isConfirm,"");
    }

    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
                                           String strFinish, Boolean isConfirm,String supp) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnModifyOrdDPine.querySaleOrder");
        if (isConfirm) {
            sql = sql + " AND E.PLAN_IS_OK = '0'";
        }
        if (strFinish.equals("0")) {
            sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3') OR "
                    + "(E.PLANSTATUS IN ('4', '5') AND "
                    + "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        else if (strFinish.equals("1")) {
            sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3', '4') OR "
                    + "(E.PLANSTATUS = '5' AND "
                    + "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        /*if (!StringUtils.isEmpty(supp)) {
            sql += " and T.SUPPLY_UNIT_CODE = '"+ supp+"'";
        }*/
        cro = this.getData(sql, list.toArray());
        return cro;
    }

    /**
     * 查询指定交货行数据
     * @param ordLnDlyPk
     * @param list
     * @param strFinish
     * @param isConfirm
     * @return
     */
    public CoreReturnObject querySaleOrder(String ordLnDlyPk,
            ArrayList<Object> list, String strFinish, Boolean isConfirm) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnModifyOrdDPine.querySaleOrder");
        if (isConfirm) {
            sql = sql + " AND E.PLAN_IS_OK = '0'";
        }
        if (strFinish.equals("0")) {
            sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3') OR "
                    + "(E.PLANSTATUS IN ('4', '5') AND "
                    + "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        else if (strFinish.equals("1")) {
            sql = sql + " AND (E.PLANSTATUS IN ('1', '2', '3', '4') OR "
                    + "(E.PLANSTATUS = '5' AND "
                    + "TO_DATE(E.ROLL_MONTH, 'YYYY-MM') = "
                    + "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
        }
        sql = sql + " AND T.ORD_LN_DLY_PK = '" + ordLnDlyPk + "'";
        cro = this.getData(sql, list.toArray());
        return cro;
    }

    /**
     * 查询合同行状态
     * @param str
     * @return object
     */
    public CoreReturnObject queryOrdLineStatus(String str) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CorePlnModifyOrdDPine.queryOrdLineStatus",
                new Object[] { str });
        return cro;
    }

    /**
     * 查询销售合同状态
     * @param str
     * @return object
     */
    public CoreReturnObject querySaleStatus(String str) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CorePlnModifyOrdDPine.querySaleStatus",
                new Object[] { str });
        return cro;
    }

    /**
     * 查询排产分解合同状态
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return object
     */
    public CoreReturnObject queryProcOrdStatus(String ordLnDlyPk,
            String plnDivideId) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CorePlnModifyOrdDPine.queryProcOrdStatus",
                new Object[] { ordLnDlyPk, plnDivideId });
        return cro;
    }

    /**
     * 查询产线基础表
     */
    public CoreReturnObject queryBaseDPline() {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CorePlnModifyOrdDPine.queryBaseDPline");
        return cro;
    }

    /**
     * 修改坯料来源
     * @param list
     * @return
     */
    public CoreReturnObject saveOutsBilletFl(ArrayList<ArrayList<String>> list) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();

        for (int i = 0; i < list.size(); i++) {
            sqllist.add("CorePlnModifyOrdDPine.saveOutsBilletFl");
            parmlist.add(list.get(i).toArray());
        }
        cro = this.setDataById(sqllist, parmlist);
        return cro;
    }

    /**
     * 修改轧制月份
     * @param list
     * @return
     */
    public CoreReturnObject saveSaleOrderRollMonth(
            ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.updateOrdRollMonth");
            String sqlP = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.updateOrdProcRollMonth");
            String sqlQ = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.queryRollWellMonth");
            for (int i = 0; i < list.size(); i++) {
                PreparedStatement psta = null;
                ps = conn.prepareStatement(sqlP);
                ps.setObject(1, list.get(i).getRollMonth());
                ps.setObject(2, list.get(i).getOrdLnDlyPk());
                ps.setObject(3, list.get(i).getPlnDivideId());
                ps.executeUpdate();
                ps.close();

                psta = conn.prepareStatement(sqlQ);
                psta.setObject(1, list.get(i).getOrdLnDlyPk());
                psta.setObject(2, list.get(i).getPlnDivideId());
                ResultSet rst = psta.executeQuery();
                if (rst.next()) {
                    if (rst.getString("ORDER_SOURCE") != null
                            && rst.getString("ORDER_SOURCE").trim().equals(
                                    "销售合同")) {
                        ps = conn.prepareStatement(sql);
                        ps.setObject(1, list.get(i).getRollMonth());
                        ps.setObject(2, list.get(i).getOrdLnDlyPk());
                        ps.executeUpdate();
                        ps.close();

                        if (rst.getString("ROLL_WELL_MONTH") != null
                                && rst.getString("ROLL_WELL_MONTH").length() >= 7) {
                            String rollWellMonth = rst
                                    .getString("ROLL_WELL_MONTH");
                            if (!list.get(i).getRollMonth().equals(
                                    rollWellMonth)
                                    && !rollWellMonth.equals("")) {
                                int mon = 0;
                                int year = Integer.parseInt(list.get(i)
                                        .getRollMonth().substring(0, 4));
                                int month = Integer.parseInt(list.get(i)
                                        .getRollMonth().substring(5, 7));
                                int yearWell = Integer.parseInt(rollWellMonth
                                        .substring(0, 4));
                                int monthWell = Integer.parseInt(rollWellMonth
                                        .substring(5, 7));
                                mon = (year - yearWell) * 12
                                        + (month - monthWell);
                                CoreAdjustWellMonth.adjustWellMonth(conn, list
                                        .get(i).getOrdLnDlyPk(), mon);
                            }
                        }
                    }
                }
                rst.close();
                psta.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());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 销售锁定
     * @param list
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject updateIfSaleFreeze(ArrayList<Object> list) {
        CoreReturnObject cro = new CoreReturnObject();
        // ArrayList<String> sqllist = new ArrayList<String>();
        // ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
             for (int i = 0; i < list.size(); i++) {
                 ArrayList<String> pram = (ArrayList<String>) list.get(i);
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CorePlnModifyOrdDPine.updateIfSaleFreeze");
                ps = conn.prepareStatement(sql);
                ps.setObject(1, pram.get(0));
                ps.setObject(2, pram.get(1));
                ps.executeUpdate();
                ps.close();
                // String sqlUp = EntityTool.fillSqlByEntity(sql,
                // list.get(i).getIfSaleFreeze());
                // sqllist.add(sqlUp);
                // parmlist.add(new Object[] {});
            }
            // cro = this.setData(sqllist, parmlist);
            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 list
     * @return
     */
    public CoreReturnObject updatePlanConfirm(
            ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePlnModifyOrdDPine.updatePlanConfirm");
        for (int i = 0; i < list.size(); i++) {
            String sqlUp = EntityTool.fillSqlByEntity(sql, list.get(i));
            sqllist.add(sqlUp);
            parmlist.add(new Object[] {});
        }
        cro = this.setData(sqllist, parmlist);
        // 判断是否可以下发
        for (int i = 0; i < list.size(); i++) {
            CoreSaleOrderReceive plnSale = new CoreSaleOrderReceive();
            plnSale.isPrepIssued(list.get(i).getOrdLnDlyPk());
        }
        return cro;
    }

    /**
     * 查询可选轧管机组
     * @param list
     * @return
     */
    public CoreReturnObject queryProcOrdDPline(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            String sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.getCustomRpline");
            ps = conn.prepareStatement(sql);
            ps.setString(1, list.get(2).toString());
            ps.setString(2, list.get(3).toString());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                cro = this.getDataBySqlID(
                        "CorePlnModifyOrdDPine.getBomCustomRDpl", list
                                .toArray());
            }
            else {
                Object[] param = new Object[] { list.get(0), list.get(1),
                        list.get(4), list.get(5), list.get(6), list.get(7) };
                cro = this.getDataBySqlID(
                        "CorePlnModifyOrdDPine.getBomMaterialDpl", param);
            }
            rs.close();
            ps.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());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 查询可选轧管机组
     * @param desginKey
     * @param mscPline
     * @param finalUser
     * @param produccode
     * @return
     */
    public CoreReturnObject queryProcOrdDPline(String desginKey,
            String mscPline, String finalUser, String produccode) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            String sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.getCustomRpline");
            ps = conn.prepareStatement(sql);
            ps.setString(1, finalUser);
            ps.setString(2, produccode);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                Object[] param = new Object[] { desginKey, mscPline, finalUser,
                        produccode, desginKey };
                cro = this.getDataBySqlID(
                        "CorePlnModifyOrdDPine.getLineBomCustomRDpl", param);
            }
            else {
                Object[] param = new Object[] { desginKey, mscPline, desginKey };
                cro = this.getDataBySqlID(
                        "CorePlnModifyOrdDPine.getLineBomMaterialDpl", param);
            }
            rs.close();
            ps.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());
        }
        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 updateConfirmDPline(
            ArrayList<PlnSaleordProcEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement psta = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            String sqlW1 = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.saveConfirmStatus");
            String sqlW2 = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.updateSaleordProcDp");
            String sqlW3 = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.updateSaleordProcBom");
            String sqlW4 = CoreXmlSqlParsersFactory
                    .getSql("CorePlnModifyOrdDPine.updateSaleordProcAmout");
            for (PlnSaleordProcEntity procEntity : list) {
                String sqlUpe = EntityTool.fillSqlByEntity(sqlW1, procEntity);
                psta = conn.prepareStatement(sqlUpe);
                psta.executeUpdate();
                psta.close();
                if (!procEntity.getGroupRoll().equals("")) {
                    String sqlUp = EntityTool
                            .fillSqlByEntity(sqlW2, procEntity);
                    psta = conn.prepareStatement(sqlUp);
                    psta.executeUpdate();
                    psta.close();
                }
                if (!procEntity.getBom().equals("")) {
                    String sqlUp = EntityTool
                            .fillSqlByEntity(sqlW3, procEntity);
                    psta = conn.prepareStatement(sqlUp);
                    psta.executeUpdate();
                    psta.close();
                }
                if (!procEntity.getPlanWtD().equals("")) {
                    String sqlUp = EntityTool
                            .fillSqlByEntity(sqlW4, procEntity);
                    psta = conn.prepareStatement(sqlUp);
                    psta.executeUpdate();
                    psta.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());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }
}