package com.steering.pss.sale.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.judge.Bll.BllCreateZbsInfo;
import com.steering.pss.sale.order.model.CoreOrderStatus;
import com.steering.pss.sale.order.model.SlmOrderLineNewEntity;
import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

public class CoreMatInfo extends DBCommon {

    public CoreReturnObject queryMatInfo(String[] arr, ArrayList<String> parm) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreMatInfo.queryMatInfo");


        if(!parm.get(0).equals("")){
            sql+= " AND  T1.JUDGE_STOVE_NO LIKE '%" + parm.get(0)  + "%'";
        }

        if(!parm.get(1).equals("")){
            sql+= " AND  T1.PRODUCNAME LIKE '%" + parm.get(1)  + "%'";
        }

        if(!parm.get(2).equals("")){
            sql+= " AND  T1.STEELNAME LIKE '%" + parm.get(2)  + "%'";
        }

        if(!parm.get(3).equals("")){
            sql+= " AND  T1.SPEC_NAME LIKE '%" + parm.get(3)  + "%'";
        }
        if(!parm.get(4).equals("")){
        	sql+= " AND T1.SUPPLY_UNIT_CODE='" + parm.get(4) + "' ";
        }

        String str = CoreConverter.toSqlConditionString("T1.BELONG_CODE", arr);
        sql += str;
        sql += " GROUP BY T1.BELONG_CODE,T1.BELONG_NAME,T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.PRODUCT_FLAG,T1.MAT_STATUS,T1.SPEC_CODE,T1.SPEC_NAME,"
                + "T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.PRODUCCODE,T1.PRODUCNAME,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.STEELCODE,T1.STEELNAME,T1.JUDGE_STD_NAME,"
                + "T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ORD_PK,T1.ORD_LN_PK,T1.ORD_LN_DLY_PK,T1.PRO_ORDER_NO,T1.PRO_ORDER_ID,T1.LOCK_FLAG,T1.MNG_LOCK_FLAG,"
                + "T1.MEMO,T1.JUDGE_RESULT_CODE,T1.JUDGE_RESULT,T2.STORAGE_NO,T1.MODEL_CODE,T1.MODEL_DESC,T1.STD_STYLE,T1.STD_STYLE_DESC,T1.GRADECODE,T1.GRADENAME,T1.SUPPLY_UNIT_CODE,T1.SUPPLY_UNIT ORDER BY T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.ORDER_NO,"
                + "T1.ORDER_SEQ,T1.ORDER_SEQ_NO,MIN(T1.INSTOCK_TIME)";
        return this.getData(sql);
    }

    /**
     * 新增现货合同+利库
     * @param
     * @param parm
     * @param orderNo
     * @param saleOrg
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject addSpotOrderLine(ArrayList<String> lineParm,
            ArrayList<Object> parm, String orderNo, String ordPk,
            String saleOrg,String userName) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        String processCode = "";
        String inDoc = "";
        String outDoc = "";
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        String systime = dateFormat.format(now);
        String bathYear = df.format(now);
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
            CoreOrderStatus cos = cou.getOrderStatus(con, ordPk); // 合同状态
            java.sql.Date date = new java.sql.Date(
                    new java.util.Date().getTime());
            String saleOrgDesc = "";
            if (saleOrg.equals("100101")) {
                saleOrgDesc = "国内贸易部";
            }
            else if (saleOrg.equals("100102")) {
                saleOrgDesc = "国际贸易部";
            }
            else if (saleOrg.equals("100103")) {
                saleOrgDesc = "钢贸公司";
            }
            else if (saleOrg.equals("100105")) {
                saleOrgDesc = "天淮公司";
            }

            if (cos == null) {
                cro.setV_errCode(-1);
                con.rollback();
                cro.setV_errMsg("该合同头已经无效，不能新增合同行！");
            }
            // 炉号批组 对应的 ORD_LN_PK
            HashMap<String, String> map = new HashMap<String, String>();

            if (cos.getOrderSts().equals("12020101")
                    || cos.getOrderSts().equals("12020102")) { // 录入
                PreparedStatement ps = null;
                ResultSet rs = null;
                String createName = "";
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreMatInfo.GetOrderLinePkWithAdd");

                inDoc = getInListDoc(con, "800712");
                outDoc = getOutListDoc(con, "800812");
                for (int i = 0; i < lineParm.size(); i++) {
                    String str = lineParm.get(i);
                    JSONObject json = JSONObject.fromObject(str);
                    SlmOrderLineNewEntity ole = (SlmOrderLineNewEntity) JSONObject
                            .toBean(json, SlmOrderLineNewEntity.class);
                    createName = ole.getCreateName();
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, ole.getOrdPk());
                    ps.setObject(2, ole.getOrdPk());
                    rs = ps.executeQuery();
                    String ordLnPk = "";
                    if (rs.next()) {
                        ordLnPk = rs.getString(1);
                    }
                    if (ordLnPk == null || ordLnPk.equals("")) {
                        cro.setV_errMsg("合同行主键生成失败！");
                        cro.setV_errCode(-1);
                        con.rollback();
                        return cro;
                    }
                    rs.close();
                    ps.close();
                    ole.setOrdLnPk(ordLnPk);
                    String[] stove = ole.getStoveBatchGroup().split("&");
                    for (int j = 0; j < stove.length; j++) {
                        map.put(stove[j], ordLnPk);
                    }
                    String sql1 = CoreXmlSqlParsersFactory
                            .getSql("CoreMatInfo.doAddLine");
                    sql1 = EntityTool.fillSqlByEntity(sql1, ole);
                    ps = con.prepareStatement(sql1);
                    ps.executeUpdate();
                    ps.close();
                    //添加crm
                    cou.doCrmEvent(con, "",ordLnPk,"","0");
                }


                for (int i = 0; i < parm.size(); i++) {
                    ArrayList<Object> list = (ArrayList<Object>) parm.get(i);
                    String sql2 = CoreXmlSqlParsersFactory
                            .getSql("CoreMatInfo.ISExistsMat");
                    ps = con.prepareStatement(sql2);
                    ps.setObject(1, list.get(0));
                    ps.setObject(2, list.get(1));
                    ps.setObject(3, list.get(2));
                    ps.setObject(4, list.get(3));
                    String count = "";
                    rs = ps.executeQuery();
                    if (rs.next()) {
                        count = rs.getString(1);
                    }

                    if (count == null || count.equals("")) {
                        cro.setV_errMsg("您选择的炉号、批号、组号已经被其他合同占用或者处于质量/管理封锁状态！");
                        cro.setV_errCode(-1);
                        con.rollback();
                        return cro;
                    }
                    rs.close();
                    ps.close();

                    String stoveStr = list.get(0) + "@" + list.get(1) + "@"
                            + list.get(2);
                    String lnPk = map.get(stoveStr);
                    //所属权不一致写出入库记录
//                    if(!saleOrg.equals(list.get(4).toString()))
//                    {
//                        MatZcMEntity matZcEntity = new MatZcMEntity();
//                        matZcEntity.setInstockDoc(inDoc);
//                        matZcEntity.setOutstockDoc(outDoc);
//                        matZcEntity.setJudgeStoveNo(list.get(0).toString());
//                        matZcEntity.setBatchNo(list.get(1).toString());
//                        matZcEntity.setBatchGroudNo(list.get(2).toString());
//                        matZcEntity.setActCount(list.get(3).toString());
//                        matZcEntity.setNewbelongCode(saleOrg);
//                        matZcEntity.setNewbelongName(saleOrgDesc);
//                        matZcEntity.setBelongCode(list.get(4).toString());
//                        matZcEntity.setCreateTime(systime);
//                        matZcEntity.setCreateName(userName);
//                        String sql4  = CoreXmlSqlParsersFactory.getSql("CoreMatInfo.InsertInlistOut");
//                        sql4 = EntityTool.fillSqlByEntity(sql4,matZcEntity);
//                        ps = con.prepareStatement(sql4);
//                        ps.executeUpdate();
//                        ps.close();
//                    }else
//                    {
                        // 写入材料表 更新材料状态
                        String sql3 = CoreXmlSqlParsersFactory
                                .getSql("CoreMatInfo.Liku");
                        sql3 = sql3.replaceAll("#ORDER_NO#", orderNo);
                        sql3 = sql3.replaceAll("#ORD_LN_PK#", lnPk);
                        sql3 = sql3.replaceAll("#ORD_PK#", ordPk);
                        sql3 = sql3.replaceAll("#JUDGE_STOVE_NO#",
                                list.get(0).toString());
                        sql3 = sql3.replaceAll("#BATCH_NO#",
                                list.get(1).toString());
                        sql3 = sql3.replaceAll("#BATCH_GROUD_NO#",
                                list.get(2).toString());
                        sql3 = sql3.replaceAll("#NUM#", list.get(3).toString());
                        sql3 = sql3.replaceAll("#BELONG_CODE#", saleOrg);
                        sql3 = sql3.replaceAll("#BELONG_NAME#", saleOrgDesc);
                        sql3 = sql3.replaceAll("#OLD_BELONG_CODE#", list.get(4).toString());

                        sql3 = sql3.replaceAll("#ACT_LEN_MIN#", list.get(6).toString());
                        sql3 = sql3.replaceAll("#ACT_LEN_MAX#", list.get(7).toString());

                        ps = con.prepareStatement(sql3);
                        ps.executeUpdate();
                        ps.close();
                    //}

                    
                    
                } // 循环炉 批 组
                CoreOrderStatusCommFun.clearOrderPriceStatus(con, ordPk);
                // 更改合同状态
                CoreOrderStatusCommFun.updateOrderHeadStatusConfirm(con, ordPk,
                        "12020101", "录入", createName, date.toString());
                cou.updateOrderLineStatus(con, ordPk, "12020101");
                cou.updateOrderDeliveryLineStatus(con, ordPk, "12020101");
                
                // 将材料表实际利库的炉号信息重量反写会合同行
                String sql4 = CoreXmlSqlParsersFactory
                        .getSql("CoreMatInfo.UpdateOrderLineQty");
                Iterator<Entry<String, String>> iter = map.entrySet()
                        .iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String pk = entry.getValue();
                    ps = con.prepareStatement(sql4);
                    ps.setObject(1, pk);
                    ps.setObject(2, pk);
                    ps.setObject(3, pk);
                    ps.executeUpdate();
                    ps.close();
                }
                cou.doCrmEvent(con, ordPk,"","","1");
                con.commit();
                cro.setV_errCode(0);
            }
            else {
                cro.setV_errMsg("现货合同只有在录入状态和待提报评审状态下允许新增现货合同行！");
                cro.setV_errCode(-1);
                con.rollback();
                return cro;
            }

        }
        catch (SQLException e) {
            try {
                if (con != null && !con.isClosed()) {
                    con.rollback();
                    cro.setV_errMsg(e.getMessage());
                    cro.setV_errCode(-1);
                    e.printStackTrace();
                }
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return cro;
    }
    /***
     * 获取入库单号
     *
     * @param conn
     * @param strInbound
     * @return
     * @throws SQLException
     */
    public String getInListDoc(Connection conn, String strInbound)
            throws SQLException {
        String inListDoc = "";
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmFinishAfrim.getInListDoc");
        PreparedStatement psta = conn.prepareStatement(sql);
        psta.setString(1, strInbound);
        psta.setString(2, strInbound);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            inListDoc = rs.getString("INSTOCK_DOC");
        }
        rs.close();
        psta.close();
        return inListDoc;
    }
    /***
     * 获取出库单号
     *
     * @param conn
     * @param
     * @return
     * @throws SQLException
     */
    public String getOutListDoc(Connection conn, String strOutbound)
            throws SQLException {
        String outListDoc = "";
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmFinishAfrim.getOutListDoc");
        PreparedStatement psta = conn.prepareStatement(sql);
        psta.setString(1, strOutbound);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            outListDoc = rs.getString("OUTSTOCK_DOC");
        }
        rs.close();
        psta.close();
        return outListDoc;
    }
    /**
     * 修改现货合同
     * @param parm
     * @return
     */
    public CoreReturnObject updateSpotOrderLine(ArrayList<Object> parm) {
        
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreMatInfo.updateSpotOrderLine");
            PreparedStatement ps = con.prepareStatement(sql);
            for (int i = 0; i < parm.size(); i++) {
                ps.setObject(i + 1, parm.get(i));
            }
            cro.setResult(ps.executeUpdate());
            ps.close();
            cou.doCrmEvent(con, "",parm.get(6).toString(),"","1");
            con.commit();
            cro.setV_errCode(0);
        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 更新合同行的交货行描述、交货行时间 材料表中交货行PK值
     * @param ordLnPk
     * @param desc
     * @return
     */
    public CoreReturnObject updateOrderLineDesc(String ordLnPk, String desc) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreMatInfo.UpdateOrderLineDesc");
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setObject(1, desc);
            ps.setObject(2, ordLnPk);
            ps.setObject(3, ordLnPk);
            ps.executeUpdate();
            ps.close();
            
            
            
            
            
            String sql1 = CoreXmlSqlParsersFactory
                    .getSql("CoreMatInfo.UpdateMatWithLnDlyPk");
            ps = con.prepareStatement(sql1);
            ps.setObject(1, ordLnPk);
            ps.setObject(2, ordLnPk);
            ps.setObject(3, ordLnPk);
            int count = ps.executeUpdate();
            
            
            sql = CoreXmlSqlParsersFactory.getSql("CoreOrderInfoUpdate.selectMatZcMOrderLn");//查询合同行下库存信息
            ps = con.prepareStatement(sql);
            ps.setString(1, ordLnPk);
            ResultSet rs = ps.executeQuery();
            while(rs.next())
            {
            	try {
					BllCreateZbsInfo.saveSpotInfo(rs.getString("JUDGE_STOVE_NO"),rs.getString("BATCH_NO"),rs.getString("BATCH_GROUD_NO"),rs.getString("PROCESS_CODE"),ordLnPk + "001",con);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            rs.close();
            ps.close();
            
            cro.setResult(count);
            con.commit();

        }
        catch (SQLException e) {
            e.printStackTrace();
            try {
                con.rollback();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 修改合同的最终用户(只影响本身字段为空的数据)
     * @param parm
     * @return
     */
    public CoreReturnObject updateSpotLineFinaUser(ArrayList<Object> parm) {
        return this.setDataBySqlID("CoreMatInfo.updateSpotLineFinaUser",
                parm.toArray());
    }

}
