package com.steering.pss.plnsaleord.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import net.sf.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.judge.model.SlmOrderLineEntity;
import com.steering.pss.plnsaleord.order.model.SlmOrderLenEntity;
import com.steering.pss.plnsaleord.processOrder.CoreProcessFinish;
import com.steering.pss.sale.order.CoreOrderInfoUpdate;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CoreOrdFinishSet extends DBCommon {

    /**
     * 查询
     * @param list
     * @return
     */
    public CoreReturnObject querySaleOrderSc(ArrayList<Object> list,
            String strStatus) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.queryFinishOrdSale");
        if (!strStatus.trim().equals("")) {
            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 {
            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')))";
        }
        cro = this.getData(sql, list.toArray());
        return cro;
    }

    /**
     * 查询
     * @param list
     * @return
     */
    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
                                           String ordFrom) {
        return querySaleOrder(list,ordFrom,null);
    }
    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
                                           String ordFrom,String[] arr) {
        return querySaleOrder(list,ordFrom,arr,null);
    }
    public CoreReturnObject querySaleOrder(ArrayList<Object> list,
            String ordFrom,String[] arr,String orderSource) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.queryFinishOrdSale");
        sql += " AND E.PLANSTATUS LIKE '%' || ? || '%'"
                + " AND E.PLANSTATUS IN ('2', '3', '4', '5')";
        if (!ordFrom.trim().equals("")) {
            sql = sql + " AND T.ORDERFROM = '" + ordFrom + "'";
        }

        if (arr != null && arr.length > 0) {
            String condition2 = CoreConverter.toSqlConditionString1000("OH.CREATE_DEPT",arr);
            sql += "AND (T.ORD_PK LIKE 'BL%' OR " + condition2 + ")";
        }
        if (!StringUtils.isEmpty(orderSource)) {
            sql = sql + " AND E.ORDER_SOURCE != '" + orderSource + "'";
        }
        cro = this.getData(sql, list.toArray());
        return cro;
    }

    /**
     * 查询交货行对应排产计划
     * @param
     * @return
     */
    public CoreReturnObject queryPlnExeStatus(String ordLnPk, String plnDivideId) {
        CoreReturnObject cro = new CoreReturnObject();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.queryPlnExeStatus");
        cro = this.getData(sql, new Object[] { ordLnPk, plnDivideId, ordLnPk,
                plnDivideId, ordLnPk, plnDivideId, ordLnPk, plnDivideId });
        return cro;
    }

    /**
     * 修改销售合同状态
     * @param list
     * @return object
     */
    public CoreReturnObject setModifySale(ArrayList<ArrayList<String>> list,
                                          String intFalg,String userName) {
        return setModifySale(list,intFalg,userName,"");
    }
    public CoreReturnObject setModifySale(ArrayList<ArrayList<String>> list,
            String intFalg,String userName,String customInfo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            for (int i = 0; i < list.size(); i++) {

                String status = list.get(i).get(0);
                String ordLnDlyPk = list.get(i).get(1);
                String ordLnPk = list.get(i).get(2);// 和同行pk
                String orderNo = list.get(i).get(3);
                String pnDivideId = list.get(i).get(4);
                if (intFalg.equals("0")) {
                    // 判断轧管排产状态
                    String zgStatus = "";
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdFinishSet.selectPlnOrderZgStatus");
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setObject(1, ordLnDlyPk);
                    ps.setObject(2, pnDivideId);
                    ResultSet rs = ps.executeQuery();
                    while (rs.next()) {
                        zgStatus = rs.getString("EXE_STATUS");
                        if (zgStatus != null && !zgStatus.equals("")
                                && Integer.parseInt(zgStatus) < 2) {
                            cro.setV_errMsg("合同号为:" + orderNo
                                    + ",向下轧管排产计划未生产完成。");
                            return cro;
                        }
                    }
                    rs.close();
                    ps.close();

                    // 判断镦拔扩排产状态
                    String dbkStatus = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdFinishSet.selectPlnOrderDbkStatus");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, ordLnDlyPk);
                    ps.setObject(2, pnDivideId);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        dbkStatus = rs.getString("EXE_STATUS");
                        if (dbkStatus != null && !dbkStatus.equals("")
                                && Integer.parseInt(dbkStatus) < 2) {
                            cro.setV_errMsg("合同号为:" + orderNo
                                    + ",向下镦拔扩排产计划未生产完成。");
                            return cro;
                        }
                    }
                    rs.close();
                    ps.close();

                    // 判断热处理排产状态
                    String rclStatus = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdFinishSet.selectPlnOrderRclStatus");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, ordLnDlyPk);
                    ps.setObject(2, pnDivideId);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        rclStatus = rs.getString("EXE_STATUS");
                        if (rclStatus != null && !rclStatus.equals("")
                                && Integer.parseInt(rclStatus) < 2) {
                            cro.setV_errMsg("合同号为:" + orderNo
                                    + ",向下热处理排产计划未生产完成。");
                            return cro;
                        }
                    }
                    rs.close();
                    ps.close();

                    // 判断加工排产状态
                    String jgxStatus = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdFinishSet.selectPlnOrderJgxStatus");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, ordLnDlyPk);
                    ps.setObject(2, pnDivideId);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        jgxStatus = rs.getString("EXE_STATUS");
                        if (jgxStatus != null && !jgxStatus.equals("")
                                && Integer.parseInt(jgxStatus) < 2) {
                            cro.setV_errMsg("合同号为:" + orderNo
                                    + ",向下加工线排产计划未生产完成。");
                            return cro;
                        }
                    }
                    rs.close();
                    ps.close();
                    // 判断接箍排产状态
                    String jgStatus = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdFinishSet.selectPlnOrderJgStatus");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, ordLnDlyPk);
                    ps.setObject(2, pnDivideId);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                    	jgStatus = rs.getString("EXE_STATUS");
                        if (jgStatus != null && !jgStatus.equals("")
                                && Integer.parseInt(jgStatus) < 2) {
                            cro.setV_errMsg("合同号为:" + orderNo
                                    + ",向下接箍排产计划未生产完成。");
                            return cro;
                        }
                    }
                    rs.close();
                    ps.close();
                }
                setPlnOrdStatus(conn, ordLnPk, ordLnDlyPk, status, pnDivideId,userName, customInfo);

                // 添加crm记录
                CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
                cou.doCrmEvent(conn,"","",ordLnDlyPk,"1");

                cro.setV_errMsg("修改成功!");
                conn.commit();

            }
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        catch (Exception ex) {
            if (conn != null) {
                try {
                    conn.rollback();
                }
                catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(ex.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 status
     * @throws SQLException
     * @throws ParseException
     */
    public static void setPlnOrdStatus(Connection conn, String ordLnPk,
                                       String ordLnDlyPk, String status, String pnDivideId,String userName)
            throws SQLException, ParseException {
        setPlnOrdStatus(conn, ordLnPk, ordLnDlyPk, status, pnDivideId, userName, "");
    }
    public static void setPlnOrdStatus(Connection conn, String ordLnPk,
            String ordLnDlyPk, String status, String pnDivideId,String userName,String customInfo)
            throws SQLException, ParseException {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String systime = dateFormat.format(now);
        String sqlUp = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.setModifySale");
        String sqlDelivery = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.setLineDeliveryStatus");
        String statusDelivery = "";
        if (status.equals("4")) {
            statusDelivery = "12020502";
        }
        else if (status.equals("5")) {
            statusDelivery = "12020602";
        }
        else {
            return;
        }
        // 工序生产完成
        CoreProcessFinish.setOrdLnDlyProc(conn, ordLnDlyPk, status);

        PreparedStatement psta = null;
        String sqlUpPrc = "";
        if(status.equals("4"))
        {
            if (!StringUtils.isEmpty(customInfo) && "@JkFinish".equals(customInfo)) {
                sqlUpPrc = CoreXmlSqlParsersFactory
                        .getSql("CoreOrdFinishSet.setModifySaleProcJk");
                if (!pnDivideId.equals("")) {
                    sqlUpPrc += " AND T.PLN_DIVIDE_ID='" + pnDivideId + "'";
                    psta = conn.prepareStatement(sqlUpPrc);
                    psta.setObject(1, status);
                    psta.setObject(2, ordLnDlyPk);
                    psta.executeUpdate();
                    psta.close();
                }
                else {
                    psta = conn.prepareStatement(sqlUpPrc);
                    psta.setObject(1, status);
                    psta.setObject(2, ordLnDlyPk);
                    psta.executeUpdate();
                    psta.close();
                }
            } else {
                sqlUpPrc = CoreXmlSqlParsersFactory
                        .getSql("CoreOrdFinishSet.setModifySaleProc");
                if (!pnDivideId.equals("")) {
                    sqlUpPrc += " AND T.PLN_DIVIDE_ID='" + pnDivideId + "'";
                    psta = conn.prepareStatement(sqlUpPrc);
                    psta.setObject(1, status);
                    psta.setObject(2,userName);
                    psta.setObject(3,systime);
                    psta.setObject(4, ordLnDlyPk);
                    psta.executeUpdate();
                    psta.close();
                }
                else {
                    psta = conn.prepareStatement(sqlUpPrc);
                    psta.setObject(1, status);
                    psta.setObject(2,userName);
                    psta.setObject(3,systime);
                    psta.setObject(4, ordLnDlyPk);
                    psta.executeUpdate();
                    psta.close();
                }
            }
        }else if(status.equals("5"))
        {
            sqlUpPrc = CoreXmlSqlParsersFactory
                    .getSql("CoreOrdFinishSet.setModifySaleProcJk");
            if (!pnDivideId.equals("")) {
                sqlUpPrc += " AND T.PLN_DIVIDE_ID='" + pnDivideId + "'";
                psta = conn.prepareStatement(sqlUpPrc);
                psta.setObject(1, status);
                psta.setObject(2, ordLnDlyPk);
                psta.executeUpdate();
                psta.close();
            }
            else {
                psta = conn.prepareStatement(sqlUpPrc);
                psta.setObject(1, status);
                psta.setObject(2, ordLnDlyPk);
                psta.executeUpdate();
                psta.close();
            }
        }

        int planstratsus = 0;
        // 查询排产分解表交货行PK 是否全不关闭
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.selectPlnSaleordProcPl");
        PreparedStatement psta1 = conn.prepareStatement(sql);
        psta1.setObject(1, ordLnDlyPk);
        ResultSet rs = psta1.executeQuery();
        if (rs.next()) {
            planstratsus = rs.getInt("PLANSTATUS");
        }
        if (planstratsus >= 4) {
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, status);
            psta.setObject(2, ordLnDlyPk);
            psta.executeUpdate();
            psta.close();

            psta = conn.prepareStatement(sqlDelivery);
            psta.setObject(1, statusDelivery);
            psta.setObject(2, ordLnDlyPk);
            psta.executeUpdate();
            psta.close();

            if (status.trim().equals("4")) {
                // 和同行生产状态设置
                setOrdLineFinishSc(conn, ordLnPk);
            }
            if (status.trim().equals("5")) {
                // 和同行缴库状态设置
                setOrdLineFinishJk(conn, ordLnPk);
            }
            
            //上传到产销
            String querySql = "SELECT \r\n" + 
            		"       (SELECT T.ORDER_NO FROM SLM_ORDER_HEAD T WHERE T.ORD_PK =LINE.ORD_PK ) ORD_PK,\r\n" + 
            		"       ORDER_SEQ\r\n" + 
            		"  FROM SLM_ORDER_LINE LINE\r\n" + 
            		"  WHERE LINE.ORD_LN_PK = '"+ordLnPk+"'";
            PreparedStatement psta2 = conn.prepareStatement(querySql);
            ResultSet rs1 = psta2.executeQuery();
            if(rs1.next()) {
               JSONObject jsonObject = new JSONObject();
               jsonObject.put("form_code","MESTHSO11");
               jsonObject.put("form_name","合同状态关闭");
               jsonObject.put("form_time",systime);
               jsonObject.put("con_no", rs1.getString(1));//add("con_no", rs1.getString("ORD_PK"));
               jsonObject.put("con_line_no", rs1.getString(2));
            	DefaultWebServiceRequest request = new DefaultWebServiceRequest();
            	request.setMsgBody(jsonObject.toString());
 			    request.setServiceId("MESTHSO11");
 			   try {
				ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,
							"receiveMessage","");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
//            	interfaceState = ServiceToCx.HttpPostExample("",gson.toJson(smLenEntities));	
//            	if(!interfaceState) {
//            		System.out.println("接口数据上传失败！");
//            	}
            }
        }
    }

    /**
     * 设置合同行生产完成
     * @param ordLnPk 合同行Pk
     * @throws SQLException
     */
    public static void setOrdLineFinishSc(Connection conn, String ordLnPk)
            throws SQLException {
        PreparedStatement psta = null;
        int count1 = 0;
        int count2 = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.getNumDeliveryByLine");
        String sqlUp = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.setOrdLineStatus");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            count1 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        sql = sql + " AND SUBSTR(T.DELIVERY_STATUS, 0, 6) = '120205'";
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        rs = psta.executeQuery();
        if (rs.next()) {
            count2 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        if (count2 > 0 && count1 > 0 && count1 > count2) {
            // 已开始生产
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020501");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
        if (count2 > 0 && count1 > 0 && count1 == count2) {
            // 生产完成
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020502");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
    }

    /**
     * 设置合同行缴库完成
     * @param ordLnPk 合同行Pk
     * @throws SQLException
     */
    public static void setOrdLineFinishJk(Connection conn, String ordLnPk)
            throws SQLException {
        PreparedStatement psta = null;
        int count1 = 0;
        int count2 = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.getNumDeliveryByLine");
        String sqlUp = CoreXmlSqlParsersFactory
                .getSql("CoreOrdFinishSet.setOrdLineStatus");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            count1 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        sql = sql + " AND SUBSTR(T.DELIVERY_STATUS, 0, 6) = '120206'";
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        rs = psta.executeQuery();
        if (rs.next()) {
            count2 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        if (count2 > 0 && count1 > 0 && count1 > count2) {
            // 已开始生产
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020601");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
        if (count2 > 0 && count1 > 0 && count1 == count2) {
            // 生产完成
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020602");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
    }

}