package com.steering.pss.glbusiness;

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.comm.tools.SqlBuilder;
import com.steering.pss.plan.order.model.SlmOrderHeadCopy;
import com.steering.pss.plan.order.model.SlmOrderLineCopy;
import com.steering.pss.sale.order.CoreOrderCopy;
import com.steering.pss.sale.order.CoreOrderInfoUpdate;
import com.steering.pss.ydm.entity.PlnOrderZgSEntity;
import org.apache.commons.lang.time.DateFormatUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

public class FrmTHOrderManage extends DBCommon {

    public CoreReturnObject doQuery(String orderNo, String startTime, String endTime, String productionThFlag) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmTHOrderManage.doQuery");
        if (!StringUtils.isEmpty(productionThFlag)) {
            sql += " AND T.PRODUCTION_TH_FLAG >= '" + productionThFlag + "'";
        } else {
            sql += "AND (T.EXE_STATUS IN ('0','1') OR T.PRODUCTION_TH_FLAG IS NOT NULL)";
        }
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(startTime)) {
            sql += " AND T.CREATE_TIME >= TO_DATE('" + startTime + "','YYYY-MM-DD HH24:MI:SS')";
            sql += " AND T.CREATE_TIME <= TO_DATE('" + endTime + "','YYYY-MM-DD HH24:MI:SS')";
        }
        if (!StringUtils.isEmpty(orderNo)) {
            sql += " AND T.ORDER_NO LIKE '%" + orderNo + "%'";
        }
        return this.getData(sql);
    }

    public CoreReturnObject doQueryThOrderReport(String orderNo, String startTime, String endTime) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmTHOrderManage.doQueryThOrderReport");
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(startTime)) {
            sql += " AND T.CREATE_TIME >= TO_DATE('" + startTime + "','YYYY-MM-DD HH24:MI:SS')";
            sql += " AND T.CREATE_TIME <= TO_DATE('" + endTime + "','YYYY-MM-DD HH24:MI:SS')";
        }
        if (!StringUtils.isEmpty(orderNo)) {
            sql += " AND T.TPCOHT LIKE '%" + orderNo + "%'";
        }
        return this.getData(sql);
    }

    public CoreReturnObject getThBcOrder(String orderNo){
        Object[] param = {orderNo};
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmTHOrderManage.getThBcOrder");
        return this.getData(sql,param);
    }

    public CoreReturnObject doUpdate(ArrayList<ArrayList<Object>> list) {
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        String sql1="";
        for (ArrayList<Object> o : list) {
                String sql = CoreXmlSqlParsersFactory
                        .getSql("FrmTHOrderManage.doUpdate");
                String i3=(String)o.get(3);
                if(o.get(3).equals("123502")){
                    sql1="  CONFIRM_DATE_PDFWK=SYSDATE ";
                }
                if (o.get(3).equals("123504")) {
                    sql1 = "  CONFIRM_DATE_TH=SYSDATE ";
                }
                if(o.get(3).equals("123501")){
                    sql1="  CONFIRM_DATE_ZZB=SYSDATE ";
                }
            Object[] param = {o.get(0),o.get(1),o.get(2)};
            sql = sql.replace("#something#", sql1);
            sqllist.add(sql);
            params.add(param);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
    }


    public CoreReturnObject doupdateField(ArrayList<String> list) {
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        String sql1=null;
        for (String o : list) {
            PlnOrderZgSEntity plnOrderZgSEntity = EntityTool.getEntityByJSONStr(o, PlnOrderZgSEntity.class);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmTHOrderManage.doupdateField");
            Object[] param = {
                    plnOrderZgSEntity.getOrderDelvryEdate(),
                    plnOrderZgSEntity.getProPlanId(),
                    plnOrderZgSEntity.getGxPlanNo()};
            sqllist.add(sql);
            params.add(param);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
    }

    public CoreReturnObject doupdateWeight(ArrayList<String> list) {
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        String sql1=null;
        for (String o : list) {
            PlnOrderZgSEntity plnOrderZgSEntity = EntityTool.getEntityByJSONStr(o, PlnOrderZgSEntity.class);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmTHOrderManage.doupdateWeight");
            Object[] param = {
                    plnOrderZgSEntity.getMemo(),
                    plnOrderZgSEntity.getProPlanId(),
                    plnOrderZgSEntity.getGxPlanNo()};
            sqllist.add(sql);
            params.add(param);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
    }

    public CoreReturnObject doUpdateThOrder(ArrayList<ArrayList<Object>> list) {
        CoreReturnObject returnObject = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        for (ArrayList<Object> o : list) {

            SlmOrderHeadCopy orderState = getThBcOrderState(o.get(0).toString());
            if(orderState != null && Integer.parseInt(orderState.getOrderSts()) >= 12020301){
                returnObject.setV_errCode(-1);
                returnObject.setV_errMsg(o.get(0).toString() + "合同已生效，无法修改！");
                return returnObject;
            }

            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmTHOrderManage.doUpdateThOrder");
            Object[] param = o.toArray();
            sqllist.add(sql);
            params.add(param);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
    }

    public SlmOrderHeadCopy getThBcOrderState(String orderNo){
        Connection con = null;
        SlmOrderHeadCopy slmOrderHead = new SlmOrderHeadCopy();
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            SqlBuilder b = new SqlBuilder("FrmTHOrderManage.getThBcOrderState");
            b.Fill(new String[]{orderNo});
            slmOrderHead = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderHeadCopy.class);
            return slmOrderHead;
        }catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return slmOrderHead;
    }

    /**
     * 生成合同
     * @param list
     * @return
     */
    public CoreReturnObject doAddOrder(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        CoreOrderInfoUpdate coreOrderInfoUpdate = new CoreOrderInfoUpdate();
        Connection con = null;

        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            Statement ps = con.createStatement();

            for (String json : list) {
                PlnOrderZgSEntity plnOrderZgEntity = EntityTool.getEntityByJSONStr(json, PlnOrderZgSEntity.class);
                String ordLnDlyPk = plnOrderZgEntity.getOrdLnDlyPk();
                CoreOrderCopy orderCopy = new CoreOrderCopy();
                // 合同头
                SlmOrderHeadCopy orderHead = SlmOrderHead(con, orderCopy);
                String sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addHead");
                sql = EntityTool.fillSqlByEntity(sql, orderHead);
                ps.executeUpdate(sql);
                //合同行
                String ordLnPk = coreOrderInfoUpdate.getAddLineOrdLnPk(con, orderHead.getOrdPk());
                // 获取轧管合同信息
                SqlBuilder b = new SqlBuilder("CoreOrderCopy.queryLine");
                b.Append(" AND ORD_LN_PK = {1}");
                b.Fill(new String[]{ordLnDlyPk.substring(0, ordLnDlyPk.length() - 6), ordLnDlyPk.substring(0, ordLnDlyPk.length() - 3)});
                SlmOrderLineCopy line = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderLineCopy.class);

                SlmOrderLineCopy slmOrderLine = new SlmOrderLineCopy();
                slmOrderLine.setOrdPk(orderHead.getOrdPk());
                slmOrderLine.setOrdLnPk(ordLnPk);
                slmOrderLine.setOrderSeq("001");
                slmOrderLine.setPsc(line.getPsc());
                slmOrderLine.setPscDesc(line.getPscDesc());
                slmOrderLine.setPrdCls(line.getPrdCls());
                slmOrderLine.setProduccode(line.getProduccode());
                slmOrderLine.setProducname(line.getProducname());
                slmOrderLine.setStdCode(line.getStdCode());
                slmOrderLine.setStdName(line.getStdName());
                slmOrderLine.setSteelcode(line.getSteelcode());
                slmOrderLine.setSteelname(line.getSteelname());
                slmOrderLine.setStdStyle(line.getStdStyle());
                slmOrderLine.setStdStyleDesc(line.getStdStyleDesc());
                slmOrderLine.setOrderSpecCode(line.getOrderSpecCode());
                slmOrderLine.setOrderSpecDesc(line.getOrderSpecDesc());
                slmOrderLine.setSpecCode(line.getSpecCode());
                slmOrderLine.setSpecName(line.getSpecName());
                slmOrderLine.setDimater(line.getDimater());
                slmOrderLine.setHeight(line.getHeight());
                slmOrderLine.setModelCode(line.getModelCode());
                slmOrderLine.setModelDesc(line.getModelDesc());
                slmOrderLine.setLenDesc(line.getLenDesc());
                slmOrderLine.setLenMax(line.getLenMax());
                slmOrderLine.setLenMin(line.getLenMin());
                slmOrderLine.setLenNo(line.getLenNo());
                slmOrderLine.setLenUnit(line.getLenUnit());
                slmOrderLine.setOrderUnit(line.getOrderUnit());
                slmOrderLine.setOrderQty(line.getOrderQty());
                slmOrderLine.setOrdEnsuTotlLen(line.getOrdEnsuTotlLen());
                slmOrderLine.setPrdctWgt(line.getPrdctWgt());
                slmOrderLine.setDelvryRangeMax(line.getDelvryRangeMax());
                slmOrderLine.setDelvryRangeMin(line.getDelvryRangeMin());
                slmOrderLine.setDelvryRangeTpe(line.getDelvryRangeTpe());
                slmOrderLine.setFinalUserDesc("天津钢管制造有限公司");
                slmOrderLine.setFinalUser("1012800159");
                slmOrderLine.setOutsBilletFl("121801");
                slmOrderLine.setOutsStlPipeFl("121901");
                slmOrderLine.setOrderLnStatus("12020101");
                slmOrderLine.setAsselFl("0");
                slmOrderLine.setProducerFl("0");
                slmOrderLine.setValidflag("1");
                slmOrderLine.setCreateName("蒋政");
                slmOrderLine.setIslock("0");
                slmOrderLine.setBalncePriceSts("0");
                slmOrderLine.setBalncePriceOrgSts("0");
                slmOrderLine.setAw(line.getAw());
                slmOrderLine.setManInspection(line.getManInspection());
                slmOrderLine.setQualityUser(line.getQualityUser());
                slmOrderLine.setQualityUserDesc(line.getQualityUserDesc());
                slmOrderLine.setOutputStdNo(line.getOutputStdNo());
                slmOrderLine.setPicFdCheck(line.getPicFdCheck());
                sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addLine");
                sql = EntityTool.fillSqlByEntity(sql, slmOrderLine);
                ps.executeUpdate(sql);
                coreOrderInfoUpdate.doCrmEvent(con, "", ordLnPk, "", "0");

                //修改生产表天淮合同号
                sql = "UPDATE PLN_ORDER_ZG_S T SET TH_ORDER_NO_SEQ = '" + orderHead.getOrderNo() + "/" + slmOrderLine.getOrderSeq() + "'\n" +
                        "WHERE\n" +
                        "PRO_PLAN_ID = '" + plnOrderZgEntity.getProPlanId() + "'" +
                        "AND GX_PLAN_NO = '" + plnOrderZgEntity.getGxPlanNo() + "'";
                ps.executeUpdate(sql);
            }
            con.commit();
        } catch (Exception 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;
    }

    private SlmOrderHeadCopy SlmOrderHead(Connection con, CoreOrderCopy orderCopy) throws SQLException {
        String orderNo = orderCopy.generateOrderNo("100105", "122301", "122503", "120101", "");
        String ordPkNew = orderCopy.getOrdPk(con);
        String managNo = orderCopy.getManagNo(con,DateFormatUtils.format(new Date(), "yyMM"));
        String revwRptNo = orderCopy.getRevwRptNo(con, "HG" + DateFormatUtils.format(new Date(), "yyyyMM"));

        SlmOrderHeadCopy orderHead = new SlmOrderHeadCopy();
        orderHead.setOrderNo(orderNo);
        orderHead.setOrdPk(ordPkNew);
        orderHead.setManagNo(managNo);
        orderHead.setCustmOrderNo("N/A");
        orderHead.setRevwRptNo(revwRptNo);
        orderHead.setOrderTyp("120101");
        orderHead.setOrderTypDesc("自产期货");
        orderHead.setCustomerNo("1012800159");
        orderHead.setCustomerNm("天津钢管制造有限公司");
        orderHead.setMarketSys("/");
        orderHead.setAbrvition("天管制造");
        orderHead.setSupplyUnit("120504");
        orderHead.setPriceFl("120302");
        orderHead.setCurrency("120701");
        orderHead.setMnyAskTyp("121205");
        orderHead.setMnyAskDesc("发票开出后30天付款。");
        orderHead.setStlmtUnitNo("1012800159");
        orderHead.setStlmtUnitNm("天津钢管制造有限公司");
        orderHead.setFstDraweeUnit("120607");
        orderHead.setLegalPsn("曹敏");
        orderHead.setAgent("岳立海");
        orderHead.setAddress("天津市东丽区津塘公路396号");
        orderHead.setZipCode("300301");
        orderHead.setBank("中国工商银行天津市新华路支行");
        orderHead.setAccount("0302090319300225543");
        orderHead.setTaxId("91120110566114496B");
        orderHead.setPhone("022-24800516");
        orderHead.setFax("022-24800516");
        orderHead.setSignDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        orderHead.setSignAddress("江苏省淮安市");
        orderHead.setOrderYear(DateFormatUtils.format(new Date(), "yyyy") + "年");
        orderHead.setSaleOrg("100105");
        orderHead.setSaleOrgDesc("天淮公司");
        orderHead.setSaleAreaNo("10010502");
        orderHead.setSaleAreaDesc("销售部");
        orderHead.setOrderSts("12020101");
        orderHead.setOrderStsDesc("录入");
        orderHead.setValidflag("1");
        orderHead.setCreateName("蒋政");
        orderHead.setCreateDept("002023001");
        orderHead.setApprovalMan("蒋政");
        orderHead.setIslock("0");
        orderHead.setPrintPrice("结算价");
        orderHead.setContainTax("1");
        orderHead.setTradeType("122301");
        orderHead.setOrderClassify("122503");
        orderHead.setLocalLaw("无");
        return orderHead;
    }

    /**
     * 成品合同
     * @param orderNo
     * @param orderStart
     * @param orderEnd
     * @return
     */
    public CoreReturnObject doQueryZc(String orderNo, String orderStart,String orderEnd){
        Object[] params = new Object[] { orderNo, orderStart, orderEnd};
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmTHOrderManage.doQueryZc");
        return this.getData(sql,params);
    }

    public SlmOrderHeadCopy doQueryZcState(String ordPk){
        Connection con = null;
        SlmOrderHeadCopy slmOrderHead = new SlmOrderHeadCopy();
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            SqlBuilder b = new SqlBuilder("FrmTHOrderManage.doQueryZcState");
            b.Fill(new String[]{ordPk});
            slmOrderHead = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderHeadCopy.class);
            return slmOrderHead;
        }catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return slmOrderHead;
    }

    public CoreReturnObject doUpdateZcState(String ordPk,String state){
        CoreReturnObject cro = new CoreReturnObject();
        SlmOrderHeadCopy slmOrderHeadCopy = doQueryZcState(ordPk);
        if (slmOrderHeadCopy != null) {
            if(!slmOrderHeadCopy.getOrderSts().equals("12020101") && !slmOrderHeadCopy.getOrderSts().equals("12020102")){
                cro.setV_errCode(-1);
                cro.setV_errMsg("非‘录入/待提报评审’状态的合同，不能进行下发/撤销下发！");
                return cro;
            }
            if("0".equals(state) && state.equals(slmOrderHeadCopy.getThOrderFalgZc())){
                cro.setV_errCode(-1);
                cro.setV_errMsg("未下发状态，不能进行撤销下发！");
                return cro;
            }
            if("1".equals(state) && state.equals(slmOrderHeadCopy.getThOrderFalgZc())){
                cro.setV_errCode(-1);
                cro.setV_errMsg("下发状态，不能进行下发！");
                return cro;
            }
        }else {
            cro.setV_errCode(-1);
            cro.setV_errMsg("未查询到合同！");
            return cro;
        }
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        String sql = CoreXmlSqlParsersFactory.getSql("FrmTHOrderManage.doUpdateZcState");
        Object[] param = new Object[]{state,ordPk};
        sqllist.add(sql);
        params.add(param);
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
    }
}
