package com.steering.pss.sale.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.comm.tools.SqlBuilder;
import com.steering.pss.glbusiness.FrmTHOrderManage;
import com.steering.pss.plan.order.model.SlmOrderDeliveryTransitEntity;
import com.steering.pss.plan.order.model.SlmOrderHeadCopy;
import com.steering.pss.plan.order.model.SlmOrderLineCopy;
import com.steering.pss.plan.order.model.SlmOrderLineDeliveryCopy;
import com.steering.pss.sale.base.SlmBaseCustomerEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignMain;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 复制生成天淮合同
 */

public class CoreOrderCopy extends DBCommon {

    public void OrderCopy(Connection con, String ordPk) throws SQLException {
        CoreOrderInfoUpdate coreOrderInfoUpdate = new CoreOrderInfoUpdate();
        Statement ps = con.createStatement();
        String sql = "";
        // 获取pk值
        String ordPkNew = getOrdPk(con);
        // 查询合同
        SqlBuilder b = new SqlBuilder("CoreOrderCopy.queryHead");
        b.Fill(new String[]{ordPk});
        SlmOrderHeadCopy orderHead = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderHeadCopy.class);
        if(orderHead == null){
            return;
        }
        //现货合同
        if(orderHead.getOrderTyp().equals("120102")){
            return;
        }
        // 查询是否已经生成了
        String order = getOrderByCustm(con, orderHead.getOrderNo());
        // 天淮合同不进行合同生成
        if(orderHead.getSaleOrg().equals("100105")){
            return;
        }

        // 首次收票人（卖出单位）不是天淮                          制造商是天淮
        if (!(!orderHead.getFstDraweeUnit().equals("120607") && orderHead.getSupplyUnit().equals("120504")) || !StringUtils.isEmpty(order)) {
            return;
        }

        // 制造商是天管
        if(orderHead.getSupplyUnit().equals("120501")){
            return;
        }

        // 生成天淮的合同号
//        String orderNo = generateOrderNo("200101", orderHead.getTradeType(), orderHead.getOrderClassify(), orderHead.getOrderTyp(), orderHead.getBusinessType());
        String orderNo = "TH"+orderHead.getOrderNo().substring(2);
                // 获取首次收票人（卖出单位）的客户信息
        b = new SqlBuilder("CoreOrderCopy.queryCustomer");
        b.Fill(new String[]{orderHead.getFstDraweeUnit()});
        SlmBaseCustomerEntity customer = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmBaseCustomerEntity.class);

        orderHead.setOrdPk(ordPkNew);
        orderHead.setCustmOrderNo(orderHead.getOrderNo());
        orderHead.setOrderNo(orderNo);
        orderHead.setSupplyUnit("120504");
        orderHead.setFstDraweeUnit("120607");
        orderHead.setStlmtUnitNo(customer.getCustomerNo());
        orderHead.setStlmtUnitNm(customer.getCustomerNm());
        orderHead.setCustomerNo(customer.getCustomerNo());
        orderHead.setCustomerNm(customer.getCustomerNm());
        orderHead.setBeOrderSts("");
        orderHead.setBeOrderStsDesc("");
        orderHead.setOrderSts("12020101");
        orderHead.setOrderStsDesc("录入");
        orderHead.setSaleOrg("100105");
        orderHead.setSaleOrgDesc("天淮公司");
        orderHead.setSaleAreaNo("10010502");
        orderHead.setSaleAreaDesc("销售部");
        orderHead.setCreateName("蒋政");
        orderHead.setCreateDept("002023001");
        orderHead.setApprovalMan("蒋政");
        // 添加合同头
        sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addHead");
        sql = EntityTool.fillSqlByEntity(sql, orderHead);
        ps.executeUpdate(sql);
        coreOrderInfoUpdate.doCrmEvent(con, ordPkNew,"","","0");

        List<SlmOrderLineCopy> slmOrderLineCopyList = new ArrayList<SlmOrderLineCopy>();

        // 添加合同行
        b = new SqlBuilder("CoreOrderCopy.queryLine");
        b.Fill(new String[]{ordPk});
        ArrayList<SlmOrderLineCopy> lineList = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, SlmOrderLineCopy.class);
        String ordLnPkOld = "";
        for (SlmOrderLineCopy slmOrderLine : lineList) {
            ordLnPkOld = slmOrderLine.getOrdLnPk();
            // 获取新的pk值
            String ordLnPk = coreOrderInfoUpdate.getAddLineOrdLnPk(con, ordPkNew);
            slmOrderLine.setOrdPk(ordPkNew);
            slmOrderLine.setOrdLnPk(ordLnPk);
//            slmOrderLine.setFinalUser(customer.getCustomerNo());
//            slmOrderLine.setFinalUserDesc(customer.getCustomerNm());
//            slmOrderLine.setOutsBilletFl("121802");
//            slmOrderLine.setOutsStlPipeFl("121901");
            slmOrderLine.setOrderLnStatus("12020101");
            slmOrderLine.setBeOrderLnStatus("");
            slmOrderLine.setCreateName("蒋政");
            sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addLine");
            sql = EntityTool.fillSqlByEntity(sql, slmOrderLine);
            ps.executeUpdate(sql);
            slmOrderLineCopyList.add(slmOrderLine);
            coreOrderInfoUpdate.doCrmEvent(con, "",ordLnPk,"","0");

            // 添加交货行
            b = new SqlBuilder("CoreOrderCopy.queryDelivery");
            b.Fill(new String[]{ordPk, ordLnPkOld});
            ArrayList<SlmOrderLineDeliveryCopy> deliveryList = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, SlmOrderLineDeliveryCopy.class);
            String deliveryPkOld = "";
            for (SlmOrderLineDeliveryCopy slmOrderLineDelivery : deliveryList) {
                deliveryPkOld = slmOrderLineDelivery.getOrdLnDlyPk();
                String deliveryPk = getDeliveryPk(con, ordLnPk);
                sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addDelivery");
                slmOrderLineDelivery.setOrdPk(ordPkNew);
                slmOrderLineDelivery.setOrdLnPk(ordLnPk);
                slmOrderLineDelivery.setOrdLnDlyPk(deliveryPk);
                slmOrderLineDelivery.setDeliveryStatus("12020101");
                slmOrderLineDelivery.setBeDeliveryStatus("");
                slmOrderLineDelivery.setReceivNm(orderHead.getCustomerNm());
                slmOrderLineDelivery.setReceivNo(orderHead.getCustomerNo());
                slmOrderLineDelivery.setCreateName("蒋政");
                sql = EntityTool.fillSqlByEntity(sql, slmOrderLineDelivery);
                ps.executeUpdate(sql);

                b = new SqlBuilder("CoreOrderCopy.queryTransit");
                b.Fill(new String[]{deliveryPkOld});
                ArrayList<SlmOrderDeliveryTransitEntity> transitList = EntityTool.getEntitysBySqlNoClsCon(b.toString(), con, SlmOrderDeliveryTransitEntity.class);
                for (SlmOrderDeliveryTransitEntity transit : transitList) {
                    sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.addTransit");
                    transit.setOrdPk(orderHead.getOrdPk());
                    transit.setOrdLnPk(slmOrderLine.getOrdLnPk());
                    transit.setOrdLnDlyPk(slmOrderLineDelivery.getOrdLnDlyPk());
                    transit.setCreateName("蒋政");
                    sql = EntityTool.fillSqlByEntity(sql, transit);
                    ps.executeUpdate(sql);
                }
                coreOrderInfoUpdate.doCrmEvent(con, "","",deliveryPk,"0");
            }
        }
        ps.close();
        con.commit();
        new FrmTHOrderManage().doUpdateZcState(orderHead.getOrdPk(),"1");
        autoConfirmOrder(orderHead);
        autoQualityDesign(orderHead,slmOrderLineCopyList);
        autoCoreOrderReviewManagerReport(orderHead);
    }

    /**
     * 自动确认
     * @param orderHead
     */
    public void autoConfirmOrder(SlmOrderHeadCopy orderHead){
        ArrayList parmsHead = new ArrayList();
        parmsHead.add("12020102");
        parmsHead.add("待提报评审");
        parmsHead.add(orderHead.getOrderSts());
        parmsHead.add("合同销售管理(frmOrderManager.cs),点击确认按钮");
        parmsHead.add(orderHead.getOrdPk());
        parmsHead.add("");
        new CoreOrderInfoUpdate().doConfirmOrder(orderHead.getOrdPk(),parmsHead,orderHead.getCreateName(),orderHead.getSaleOrg());
    }

    /**
     * 自动质量设计
     * @param orderHead
     * @param slmOrderLineCopyList
     */
    public void autoQualityDesign(SlmOrderHeadCopy orderHead,List<SlmOrderLineCopy> slmOrderLineCopyList){
        for (SlmOrderLineCopy slmOrderLineCopy : slmOrderLineCopyList) {
            ArrayList param = new ArrayList();
            param.add("SYSTEM");

            new QualityDesignMain().qualityDesign(orderHead.getOrdPk(),slmOrderLineCopy.getOrdLnPk(),slmOrderLineCopy.getOrderSeq(),param);
        }
    }

    /**
     * 自动提报评审
     * @param orderHead
     */
    public void autoCoreOrderReviewManagerReport(SlmOrderHeadCopy orderHead){
        ArrayList param = new ArrayList();
        param.add("H");
        param.add(orderHead.getOrdPk());//pk值
        param.add(orderHead.getCreateName());
        param.add(orderHead.getOrdPk());

        String orderType = "B";
        if (orderHead.getOrderTyp().equals("120102")|| orderHead.getOrderTyp().equals("120105")) {
            orderType = "A";
        }

        new CoreOrderReviewManager().coreOrderReviewManagerReport(param,orderType,orderHead.getCreateName(),"",orderHead.getSaleOrg());
    }

    // 生成合同号
    public String generateOrderNo(String saleOrg, String tradeType,
                                  String classify, String type, String busType) {
        String[] msg = CoreGenerateOrderNo.generateOrderNo(saleOrg, tradeType,
                classify, type, busType);
        if (msg != null && msg.length == 2) {
            if (msg[0].equals("False")) {
                new Exception("合同号生成失败！！");
            } else {
                return msg[1];
            }
        } else {
            new Exception("合同号生成失败！！");
        }
        return msg[1];
    }

    public String getDeliveryPk(Connection con, String ordLnPk) throws SQLException {
        SqlBuilder b = new SqlBuilder("CoreOrderCopy.getDeliveryPk");
        b.Fill(new String[]{ordLnPk});
        PreparedStatement ps = con.prepareStatement(b.toString());
        ResultSet rs = ps.executeQuery();
        String ordLnDlyPk = "";
        if (rs.next()) {
            ordLnDlyPk = rs.getString(1);
        }
        rs.close();
        ps.close();
        return ordLnDlyPk;
    }

    public String getOrdPk(Connection con) throws SQLException {
        String sql = CoreXmlSqlParsersFactory.getSql("CoreOrderManager.sysGuid");
        PreparedStatement ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        String ordPk = "";
        if (rs.next()) {
            ordPk = rs.getString(1);
        }
        rs.close();
        ps.close();
        return ordPk;
    }

    public String getManagNo(Connection con,String managYear) throws SQLException {
        String sql = CoreXmlSqlParsersFactory.getSql("CoreOrderCopy.getManagNo");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,managYear);
        ps.setObject(2,managYear);
        ResultSet rs = ps.executeQuery();
        String managNo = "";
        if (rs.next()) {
            managNo = rs.getString(1);
        }
        rs.close();
        ps.close();
        return managNo;
    }

    public String getRevwRptNo(Connection con,String rptno) throws SQLException {
        String sql = CoreXmlSqlParsersFactory.getSql("CoreOrderManager.slmOredHeadRevwRptNo");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,rptno);
        ResultSet rs = ps.executeQuery();
        String revwRptNo = "";
        if (rs.next()) {
            revwRptNo = rs.getString(1);
        }
        rs.close();
        ps.close();
        return revwRptNo;
    }


    public CoreReturnObject getOrder_TH(String orderNo){
        CoreReturnObject returnObject = new CoreReturnObject();
        Connection con = null;
        try {
            if (StringUtils.isEmpty(orderNo)) {
                returnObject.setV_errCode(1);
                return returnObject;
            }
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            String order = getOrderByCustm(con, orderNo);
            con.commit();
            if(StringUtils.isEmpty(order)){
                returnObject.setResult(1);
            } else {
                returnObject.setResult(-1);
            }
        } catch (SQLException e) {
            try {
                con.rollback();
                returnObject.setV_errCode(-1);
                returnObject.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return returnObject;
    }


    public String getOrderByCustm(Connection con,String custmNo) throws SQLException {
        SqlBuilder b = new SqlBuilder("CoreOrderCopy.getOrderByCustm");
        b.Fill(new String[]{custmNo});
        PreparedStatement ps = con.prepareStatement(b.toString());
        ResultSet rs = ps.executeQuery();
        String orderNo = "";
        if (rs.next()) {
            orderNo = rs.getString(1);
        }
        rs.close();
        ps.close();
        return orderNo;
    }

    public String getOrderByOrderNo(Connection con,String orderNo) throws SQLException {
        SqlBuilder b = new SqlBuilder("CoreOrderCopy.getOrderByOrderNo");
        b.Fill(new String[]{orderNo});
        PreparedStatement ps = con.prepareStatement(b.toString());
        ResultSet rs = ps.executeQuery();
        orderNo = "";
        if (rs.next()) {
            orderNo = rs.getString(1);
        }
        rs.close();
        ps.close();
        return orderNo;
    }
}
