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.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
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;

/**
 * 销售合同制程默认BOM变更
 * @author xiaohai
 */
public class CoreSaleOrderReceive extends DBCommon {
    /**
     * 查询
     * @param list
     * @param depart
     * @param confirm
     * @param validDataPurviewIds
     * @return
     */
    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
            String strFinish, String depart, String confirm,  String[] validDataPurviewIds) {
        return querySaleOrder(list,strFinish,depart,confirm,validDataPurviewIds,"");
    }

    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
                                           String strFinish, String depart, String confirm,  String[] validDataPurviewIds,String supp) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreSaleOrderReceive.querySaleOrder");
        if (depart.equals("Dbk")) {
            sql += " AND E.E_IS_OK != '2' AND E.BJ_TYPE != '镦粗'";
            sql += " AND E.BJ_TYPE IN (SELECT G.PROCESS_DESC_C FROM COM_BASE_PROCESS_GROUP G," +
                    " COM_BASE_PLINE B WHERE B.PLINE_CODE = G.PLINE_CODE AND B.PROCESS_CODE = 'E'";
            sql += CoreConverter.toSqlConditionString("B.DEPARTMENT_CODE",
                    validDataPurviewIds);
            sql += ")";
            if (confirm.equals("1")) {
                sql = sql + " AND (SELECT MAX(T1.CRAFT_NO)"
                        + " FROM CRAFT_ORD_DESIGN T1"
                        + " WHERE T1.ORD_LN_PK = T.ORD_LN_PK"
                        + " AND T1.VALIDFLAG = '1') IS NOT NULL";
            }
        }
        if (depart.equals("Zg")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.D_IS_OK = '0'";
            }
            else {
                sql = sql + " AND E.D_IS_OK != '2'";
            }
        }
        if (depart.equals("Grade")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.GRADECODE_IS_OK = '0'";
            }
        }
        if (depart.equals("Jgx")) {
            if (confirm.equals("1")) {
                sql = sql + " AND INSTR(E.PROCESS_SEQ, 'G') > 0 AND E.G_IS_OK = '0'";
            }
            else {
                sql = sql + " AND INSTR(E.PROCESS_SEQ, 'G') > 0 ";
            }
        }
        if (depart.equals("Rcl")) {
            if (confirm.equals("1")) {
                sql = sql + " AND INSTR(E.PROCESS_SEQ, 'F') > 0 AND E.F_IS_OK = '0'";
            }
            else {
                sql = sql + " AND INSTR(E.PROCESS_SEQ, 'F') > 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;
    }
    
    
    /**
     * 查询BYID
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return
     */
    public CoreReturnObject querySaleOrder(String ordLnDlyPk,
            ArrayList<Object> list, String strFinish, String depart,
            String confirm) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreSaleOrderReceive.querySaleOrder");
        if (depart.equals("Dbk")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.E_IS_OK = '0'";
            }
            else {
                sql = sql + " AND E.E_IS_OK != '2'";
            }
        }
        if (depart.equals("Zg")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.D_IS_OK = '0'";
            }
            else {
                sql = sql + " AND E.D_IS_OK != '2'";
            }
        }
        if (depart.equals("Grade")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.GRADECODE_IS_OK = '0'";
            }
        }
        if (depart.equals("Jgx")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.G_IS_OK = '0'";
            }
            else {
                sql = sql + " AND E.G_IS_OK != '2'";
            }
        }
        if (depart.equals("Rcl")) {
            if (confirm.equals("1")) {
                sql = sql + " AND E.F_IS_OK = '0'";
            }
            else {
                sql = sql + " AND E.F_IS_OK != '2'";
            }
        }
        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 E.ORD_LN_DLY_PK = '" + ordLnDlyPk
                + "' ORDER BY E.PLN_DIVIDE_ID DESC";
        cro = this.getData(sql, list.toArray());
        return cro;
    }

    /**
     * 查询投入产出物料
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return
     */
    public CoreReturnObject selectOrdProcBomDpline(String ordLnDlyPk,
            String plnDivideId){
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID(
                "CoreSaleOrderReceive.selectOrdProcBomDpline", new Object[] {
                        ordLnDlyPk, plnDivideId });
        return cro;
    }
    
    /**
     * 查询合同行适用工艺制程
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject queryCraftMscPline(String ordLnPk) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryCraftMscPline",
                new Object[] { ordLnPk });
        return cro;
    }
    /***
     * 查询备料合同PK
     * @param ordLnDivPk
     * @return
     */
    public CoreReturnObject queryPlnSorder(String ordLnDivPk)
    {
    	return this.getDataBySqlID("CoreSaleOrderReceive.queryPlnSorder", new Object[]{ordLnDivPk});
    }
    /**
     * 查询工艺文件上传路径
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return
     */
    public CoreReturnObject queryCraftFilePath(String ordLnDlyPk,
            String plnDivideId) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryCraftFilePath",
                new Object[] { ordLnDlyPk, plnDivideId });
        return cro;
    }

    /**
     * 查询合同行工艺有无锁定
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject queryCraftLockFlag(String ordLnPk) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryCraftLockFlag",
                new Object[] { ordLnPk });
        return cro;
    }

    /**
     * 查询合同行有无锁定
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject queryLineLocked(String ordLnPk) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryLineLocked",
                new Object[] { ordLnPk });
        return cro;
    }

    /**
     * 销售合同查询制程适用钢种
     * @param list
     * @return object
     */
    public CoreReturnObject queryMscPlGz(ArrayList<String> list) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryMscPlGz",
                list.toArray());
        return cro;
    }

    /**
     * 销售合同查询制程工序点路径
     * @param list
     * @return object
     */
    public CoreReturnObject queryPlStation(ArrayList<String> list) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreSaleOrderReceive.queryPlStation",
                list.toArray());
        return cro;
    }

    /**
     * 查询拆分合同
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return
     */
    public CoreReturnObject querySaleProcStatus(String ordLnDlyPk,
            String plnDivideId) {
        CoreReturnObject cro = null;
        cro = this.getDataBySqlID("CoreSaleOrderReceive.querySaleProcStatus",
                new Object[] { ordLnDlyPk, plnDivideId });
        return cro;
    }

    /**
     * 查询轧管小时能力表
     * @return object
     */
    public CoreReturnObject getBomMaterialDpl(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("CoreSaleOrderReceive.getCustomRpline");
            ps = conn.prepareStatement(sql);
            ps.setString(1, list.get(4).toString());
            ps.setString(2, list.get(5).toString());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                cro = this
                        .getDataBySqlID(
                                "CoreSaleOrderReceive.getBomCustomRDpl",
                                list.toArray());
            }
            else {
                Object[] param = new Object[] { list.get(0), list.get(1),
                        list.get(2), list.get(3) };
                cro = this.getDataBySqlID(
                        "CoreSaleOrderReceive.getBomMaterialDpl", param);
            }
            rs.close();
            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;
    }

    /**
     * 更改Bom和轧管产线
     * @param ordProcEntity
     * @return
     */
    public CoreReturnObject updateSaleordProcBomDp(
            PlnSaleordProcEntity ordProcEntity) {
        CoreReturnObject cro = null;
        String sqle = CoreXmlSqlParsersFactory
                .getSql("CoreSaleOrderReceive.updateSaleordProc");
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreSaleOrderReceive.updateSaleordProcBomDp");
        if (ordProcEntity.getPlanWtD().equals("")) {
            String sqlUp = EntityTool.fillSqlByEntity(sqle, ordProcEntity);
            cro = this.setData(sqlUp);
        }
        else {
            String sqlUp = EntityTool.fillSqlByEntity(sql, ordProcEntity);
            cro = this.setData(sqlUp);
        }
        isPrepIssued(ordProcEntity.getOrdLnDlyPk());
        return cro;
    }

    /**
     * 热处理确认
     * @param list 加工组、热处理组
     * @return
     */
    public CoreReturnObject saveSaleOrderRcl(ArrayList<ArrayList<String>> list,
            ArrayList<String> listPk) {
        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("CoreSaleOrderReceive.saveSaleOrderRcl");
            parmlist.add(list.get(i).toArray());
        }
        cro = this.setDataById(sqllist, parmlist);

        for (int i = 0; i < listPk.size(); i++) {
            isPrepIssued(listPk.get(i));
        }
        return cro;
    }

    /**
     * 加工线确认
     * @param list 加工组
     * @return
     */
    public CoreReturnObject saveSaleOrderGjg(ArrayList<ArrayList<String>> list,
            ArrayList<String> listPk) {
        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("CoreSaleOrderReceive.saveSaleOrderGjg");
            parmlist.add(list.get(i).toArray());
        }
        cro = this.setDataById(sqllist, parmlist);

        for (int i = 0; i < listPk.size(); i++) {
            isPrepIssued(listPk.get(i));
        }
        return cro;
    }

    /**
     * 默认物料确认
     * @param list
     * @return
     */
    public CoreReturnObject saveConfirmStatus(
            ArrayList<PlnSaleordProcEntity> list, ArrayList<String> listPk) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreSaleOrderReceive.saveConfirmStatus");

        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 < listPk.size(); i++) {
            isPrepIssued(listPk.get(i));
        }
        return cro;
    }

    /**
     * 判断是否可以下发
     * @param ord_ln_dly_pk
     */
    public void isPrepIssued(String ordLnDlyPk) {
        Connection conn = null;
        PreparedStatement psta = null;
        try {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreSaleOrderReceive.queryIsNotAllowIssue");
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            psta = conn.prepareStatement(sql);
            psta.setString(1, ordLnDlyPk);
            ResultSet rs = psta.executeQuery();
            while (rs.next()) {
                String plnDivideId = rs.getString("PLN_DIVIDE_ID");
                boolean isPrepare = false;
                // 合同状态为已接收
                if (rs.getString("PLANSTATUS") != null
                        && rs.getString("PLANSTATUS").equals("1")) {
                    if (rs.getString("PLAN_IS_OK") != null
                            && rs.getString("E_IS_OK") != null
                            && rs.getString("GRADECODE_IS_OK") != null
                            && rs.getString("F_IS_OK") != null
                            && rs.getString("G_IS_OK") != null
                            && !rs.getString("PLAN_IS_OK").equals("0")
                            && !rs.getString("E_IS_OK").equals("0")
                            && !rs.getString("GRADECODE_IS_OK").equals("0")
                            && !rs.getString("F_IS_OK").equals("0")
                            && !rs.getString("G_IS_OK").equals("0")) {
                        isPrepare = true;
                    }
                }

                if (isPrepare) {
                    // 接箍、接箍料需求、短节备料需求、钢种是否确认、
                    // 轧管、管加工都经过确认
                    this.setDataBySqlID("CoreSaleOrderReceive.IfAllowIssue",
                            new Object[] { "1", ordLnDlyPk, plnDivideId });
                }
                else {
                    this.setDataBySqlID("CoreSaleOrderReceive.IfAllowIssue",
                            new Object[] { "0", ordLnDlyPk, plnDivideId });
                }
            }
            rs.close();
            psta.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();
            }
        }
    }
    
    
}