package com.awspaas.user.apps.donenow_ivt.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.donenow_ivt.constant.IVTConstant;
import com.awspaas.user.apps.donenow_ivt.utils.BigDecimalUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class DoWorkThread extends Thread {
    private ProcessExecutionContext process;

    //有参构造方法
    public DoWorkThread(ProcessExecutionContext process) {
        this.process = process;
    }

    public void run() {
        System.out.println("======================多线程开始分割线====================================");
        doWork(process);
    }

    public String doWork(ProcessExecutionContext process) {

        System.out.println("=========================BO_EU_DNIVT_RECEIVE_MAIN=================================");

        UserContext uc = process.getUserContext();
        BO formData = process.getFormData();
        String boName = process.getParameterOfString("$BONAME");


        //采购接收主表保存
        if (IVTConstant.BO_EU_DNIVT_RECEIVE_MAIN.equals(boName)) {
            String bindId = process.getProcessInstance().getId();
            List<BO> list = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_RECEIVE_SUB).bindId(bindId).list();

            System.out.println("=========================BO_EU_DNIVT_RECEIVE_SUB=================================" + list.size());

            //循环开始
            for (BO bo : list) {
                String BEN_RECEIVE = BigDecimalUtil.isNull(bo.getString("BEN_RECEIVE"));
                //本次接收数量为0，则跳过
                int intBenReceive = Integer.valueOf(BEN_RECEIVE).intValue();//本次接收数量

                //本次接收数量为0，则跳过
                if (intBenReceive == 0) continue;

                //多次保存，导致重复接收订单
                if (bo.getString("STATUS").equals("待接收") == false) {
                    continue;
                }
                bo.set("STATUS", "已接收");
                SDK.getBOAPI().update(IVTConstant.BO_EU_DNIVT_RECEIVE_SUB, bo);

                RowMap rowMap = DBSql.getMap("select ORDER_PRODUCT_ID,sum(QUANTITY_RECEIVED) QUANTITY_RECEIVED from BO_EU_DNIVT_RECEIVE WHERE  ORDER_PRODUCT_ID=? group by ORDER_PRODUCT_ID", new Object[]{bo.getString("ORDER_PRODUCT_ID")});
                BO receiveBo = new BO();
                receiveBo.set("ORDER_PRODUCT_ID", bo.get("ORDER_PRODUCT_ID"));
                receiveBo.set("QUANTITY_RECEIVED", bo.getString("BEN_RECEIVE"));
                String sub = BigDecimalUtil.sub(bo.getString("QUANTITY"), bo.getString("BEN_RECEIVE"), (null == rowMap ? "0" : rowMap.getString("QUANTITY_RECEIVED")));
                receiveBo.set("QUANTITY_BACKORDERED", sub);
                receiveBo.set("UNIT_COST", bo.get("UNIT_COST"));
                receiveBo.set("EXPORTED_TIME", new Date());
                receiveBo.set("RECEIVE_BY_ID", uc.getUID());
                receiveBo.set("SN", bo.get("SN"));//序列号
                ProcessInstance createBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_60c43c56593d42108be36f3aa8d3f8a2, uc.getUID(), "订单接收");
                receiveBo.setBindId(createBOProcessInstance.getId());
                SDK.getBOAPI().createDataBO(IVTConstant.BO_EU_DNIVT_RECEIVE, receiveBo, uc);


                //更新产品的库存
                String wareHouseProductBINDID = null;
                int oldQuantity = 0;//全部库存数量
                BO wareHouseProduct = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT).addQuery("WAREHOUSE_ID=", bo.getString("WAREHOUSE_ID")).addQuery("PRODUCT_ID=", bo.getString("PRODUCT_ID")).detail();
                if (wareHouseProduct != null && wareHouseProduct.isNew() == false) {

                    oldQuantity = Integer.valueOf(wareHouseProduct.getString("QUANTITY")).intValue();

                    String add = BigDecimalUtil.add(wareHouseProduct.getString("QUANTITY"), bo.getString("BEN_RECEIVE"));
                    wareHouseProduct.set("QUANTITY", add);
                    SDK.getBOAPI().update(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT, wareHouseProduct);
                    wareHouseProductBINDID = wareHouseProduct.getBindId();
                } else {
                    ProcessInstance wareBOProcessInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_41f06b1e807647db8a69dd10d4be5764, uc.getUID(), "");
                    BO wareHouseBo = new BO();
                    wareHouseBo.setBindId(wareBOProcessInstance.getId());
                    wareHouseBo.set("QUANTITY", bo.getString("BEN_RECEIVE"));
                    wareHouseBo.set("PRODUCT_ID", bo.getString("PRODUCT_ID"));
                    wareHouseBo.set("WAREHOUSE_ID", bo.getString("WAREHOUSE_ID"));
                    wareHouseBo.set("QUANTITY_MINIMUM", 0);
                    wareHouseBo.set("QUANTITY_MAXIMUM", 0);
                    SDK.getBOAPI().create(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT, wareHouseBo, wareBOProcessInstance, uc);
                    wareHouseProductBINDID = wareHouseBo.getBindId();
                }

                //1、库存批次  BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT
                //多次接收是更新操作
                BO warehouseProductLotBo = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT).addQuery("ORDER_PRODUCT_ID=", bo.getString("ORDER_PRODUCT_ID")).detail();
                if (warehouseProductLotBo == null || warehouseProductLotBo.isNew()) {
                    warehouseProductLotBo = new BO();
                    warehouseProductLotBo.setBindId(wareHouseProductBINDID);
                    warehouseProductLotBo.set("PRODUCT_ID", bo.getString("PRODUCT_ID"));
                    warehouseProductLotBo.set("WAREHOUSE_ID", bo.getString("WAREHOUSE_ID"));
                    warehouseProductLotBo.set("QUANTITY", bo.getString("BEN_RECEIVE"));
                    warehouseProductLotBo.set("UNIT_COST", bo.getString("UNIT_COST"));//成本
                    warehouseProductLotBo.set("SN", bo.getString("SN"));//序列号
                    warehouseProductLotBo.set("ORDER_PRODUCT_ID", bo.getString("ORDER_PRODUCT_ID"));
                    warehouseProductLotBo.set("IN_DATE", new Date());
                    SDK.getBOAPI().createDataBO(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT, warehouseProductLotBo, uc);

                } else {
                    if (StringUtils.isNotBlank(bo.getString("SN"))) {
                        if (intBenReceive > 0)
                            warehouseProductLotBo.set("SN", warehouseProductLotBo.getString("SN") + "," + bo.getString("SN"));
                        else {
                            String sns = warehouseProductLotBo.getString("SN");
                            sns = "," + sns + ",";
                            for (String sn : bo.getString("SN").split(",")) {
                                sns = sns.replaceAll("," + sn + ",", ",");
                            }
                            warehouseProductLotBo.set("SN", sns.substring(1, sns.length() - 1));
                        }
                    }
                    //String sns = warehouseProductLotBo.getString("SN");
                    //long count = StringUtils.isBlank(sns) ? 0 : sns.chars().filter(c -> c == ',').count()+1;
                    warehouseProductLotBo.set("QUANTITY", BigDecimalUtil.add(warehouseProductLotBo.getString("QUANTITY"), bo.getString("BEN_RECEIVE")));

                    SDK.getBOAPI().update(IVTConstant.BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT, warehouseProductLotBo);
                }

                //更新 产品信息
                //BO_EU_DNIVT_PRODUCT 上面的 库存平均单元成本 UNIT_COST_AVG
                //入库时，需要计算库存成本（客户虚拟仓不需要）
                BO productBo = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_PRODUCT).addQuery("ID=", warehouseProductLotBo.getString("PRODUCT_ID")).detail();
                if (productBo.getString("OUT_RULE").equals("1030") && DBSql.getString("SELECT CATE_ID FROM BO_EU_DNIVT_WAREHOUSE WHERE ID=?", new Object[]{warehouseProductLotBo.getString("WAREHOUSE_ID")}).equals("1")) {

                    double UNIT_COST_AVG = Double.parseDouble(productBo.getString("UNIT_COST_AVG"));
                    UNIT_COST_AVG = (oldQuantity * UNIT_COST_AVG + intBenReceive * Double.parseDouble(bo.getString("UNIT_COST"))) / (oldQuantity + intBenReceive);
                    productBo.set("UNIT_COST_AVG", UNIT_COST_AVG);
                    SDK.getBOAPI().update(IVTConstant.BO_EU_DNIVT_PRODUCT, productBo);
                }

                //2、库存转移记录 BO_EU_DNIVT_TRANSFER
                ProcessInstance warehouseTransferInstance = SDK.getProcessAPI().createBOProcessInstance("obj_e15a8fedeaeb43dc85aa258a7e1cffcf", uc.getUID(), "采购接收-" + warehouseProductLotBo.get("LOT"));
                BO warehouseTransferBo = new BO();
                warehouseTransferBo.setBindId(warehouseTransferInstance.getId());
                warehouseTransferBo.set("PRODUCT_ID", bo.getString("PRODUCT_ID"));
                warehouseTransferBo.set("TO_WAREHOUSE_ID", bo.getString("WAREHOUSE_ID"));
                warehouseTransferBo.set("QUANTITY", bo.getString("BEN_RECEIVE"));
                warehouseTransferBo.set("NOTES", "采购接收");
                warehouseTransferBo.set("TYPE_ID", "1484");//接收/取消接收
                warehouseTransferBo.set("LOT", warehouseProductLotBo.get("LOT"));
                warehouseTransferBo.set("SN", bo.get("SN"));
                SDK.getBOAPI().createDataBO(IVTConstant.BO_EU_DNIVT_TRANSFER, warehouseTransferBo, uc);

                //更新成本信息
                if (StringUtils.isNotBlank(bo.getString("CONTRACT_COST_ID"))) {
                    //根据采购项上的CONTRACT_COST_ID查找对应的成本
                    RowMap receiveMap = DBSql.getMap("select ORDER_PRODUCT_ID,sum(QUANTITY_RECEIVED) QUANTITY_RECEIVED from BO_EU_DNIVT_RECEIVE WHERE  ORDER_PRODUCT_ID=? group by ORDER_PRODUCT_ID", new Object[]{bo.getString("ORDER_PRODUCT_ID")});

                    BO CONTRACT_COST_Detail = SDK.getBOAPI().query(IVTConstant.BO_EU_DNCTT_CONTRACT_COST).detailById(bo.getString("CONTRACT_COST_ID"));
                    if (null != CONTRACT_COST_Detail) {
                        //根据成本ID找到对应的所有成本产品
                        List<BO> costProductList = SDK.getBOAPI().query(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT).addQuery("CONTRACT_COST_ID=", CONTRACT_COST_Detail.getId()).list();
                        //判断成本是否是采购中状态

                        //采购接收
                        if (intBenReceive > 0) {
                            for (BO costProductBo : costProductList) {
                                //采购中
                                if (IVTConstant.STATUS_1235.equals(costProductBo.getString("STATUS_ID"))) {
                                    String QUANTITY = BigDecimalUtil.isNull(costProductBo.getString("QUANTITY"));
                                    //采购数量
                                    int intQuantity = Integer.valueOf(QUANTITY).intValue();

                                    //待配送
                                    if (intQuantity <= intBenReceive) {
                                        intBenReceive = intBenReceive - intQuantity;
                                        costProductBo.set("STATUS_ID", IVTConstant.STATUS_1236);
                                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, costProductBo);
                                    } else if (intBenReceive < intQuantity) {
                                        costProductBo.set("STATUS_ID", IVTConstant.STATUS_1236);
                                        costProductBo.set("QUANTITY", intBenReceive);
                                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, costProductBo);

                                        //将剩余的数量生成一条新的成本产品，状态为采购中
                                        BO newCostProductBo = new BO();
                                        newCostProductBo.setAll(costProductBo.asMap());
                                        //IVTConstant.obj_6bc913271069455abbd516c556b26d31
                                        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_6bc913271069455abbd516c556b26d31, uc.getUID(), "");
                                        newCostProductBo.setBindId(processInstance.getId());
                                        newCostProductBo.set("QUANTITY", intQuantity - intBenReceive);
                                        newCostProductBo.setId(UUIDGener.getUUID());
                                        costProductBo.set("STATUS_ID", IVTConstant.STATUS_1235);
                                        SDK.getBOAPI().create(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, newCostProductBo, processInstance, uc);
                                        break;
                                    }
                                    if (intBenReceive <= 0) break;
                                }

                            }
                        }
                        //采购接收取消
                        else if (intBenReceive < 0) {
                            int outBenReceive = 0 - intBenReceive;//取消数量
                            for (BO costProductBo : costProductList) {
                                //如果存在采购中的成本产品,将取消数量加到采购数量中 从待配送数量中减
                                if (IVTConstant.STATUS_1236.equals(costProductBo.getString("STATUS_ID"))) {
                                    //采购数量
                                    String QUANTITY = BigDecimalUtil.isNull(costProductBo.getString("QUANTITY"));
                                    int intQuantity = Integer.valueOf(QUANTITY).intValue();

                                    if (intQuantity <= outBenReceive) {
                                        costProductBo.set("STATUS_ID", IVTConstant.STATUS_1235);//采购中
                                        costProductBo.set("QUANTITY", intQuantity);
                                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, costProductBo);
                                        outBenReceive = outBenReceive - intQuantity;
                                    } else {
                                        //待配送
                                        costProductBo.set("QUANTITY", intQuantity - outBenReceive);
                                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, costProductBo);

                                        //采购中
                                        //将剩余的数量生成一条新的成本产品，状态为采购中
                                        BO newCostProductBo = new BO();
                                        newCostProductBo.setAll(costProductBo.asMap());
                                        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance(IVTConstant.obj_6bc913271069455abbd516c556b26d31, uc.getUID(), "");
                                        newCostProductBo.setBindId(processInstance.getId());
                                        newCostProductBo.set("QUANTITY", outBenReceive);
                                        newCostProductBo.setId(UUIDGener.getUUID());
                                        costProductBo.set("STATUS_ID", IVTConstant.STATUS_1235);
                                        SDK.getBOAPI().create(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, newCostProductBo, processInstance, uc);
                                        break;
                                    }
                                    if (outBenReceive <= 0) break;
                                }
                            }
                        }
                    }
                }
            }
            //循环结束


            //更改采购项状态为全部接收、部门接收、已提交
            String orderBindId = DBSql.getString("SELECT BINDID FROM " + IVTConstant.BO_EU_DNIVT_ORDER_PRODUCT + " WHERE ID='" + list.get(0).getString("ORDER_PRODUCT_ID") + "'");
            List<BO> orderProductList = SDK.getBOAPI().query(IVTConstant.BO_EU_DNIVT_ORDER_PRODUCT).bindId(orderBindId).list();
            int count = 0;
            boolean exitsReceive = false;//存在接收
            for (BO bo : orderProductList) {
                RowMap map = DBSql.getMap("select ORDER_PRODUCT_ID,sum(QUANTITY_RECEIVED) QUANTITY_RECEIVED from BO_EU_DNIVT_RECEIVE WHERE  ORDER_PRODUCT_ID=? group by ORDER_PRODUCT_ID", new Object[]{bo.getString("ID")});
                //采购项总共接收数量
                int QUANTITY_RECEIVED = map == null ? 0 : map.getInt("QUANTITY_RECEIVED");
                if (QUANTITY_RECEIVED > 0) {
                    exitsReceive = true;
                }
                //采购项数量
                int QUANTITY = Integer.valueOf(BigDecimalUtil.isNull(bo.getString("QUANTITY"))).intValue();
                if (QUANTITY_RECEIVED == QUANTITY) {
                    count++;
                }
            }
            if (count == orderProductList.size() && count > 0) {
                //全部接收
                DBSql.update("UPDATE " + IVTConstant.BO_EU_DNIVT_ORDER + " SET STATUS_ID=" + IVTConstant.STATUS_2150 + " WHERE BINDID='" + orderBindId + "'");

                for (BO bo : orderProductList) {

                    //采购项全部接收后，更改关联合同产品的状态
                    String sql = "SELECT a.QUANTITY-SUM(ifnull(b.QUANTITY,0)) FROM BO_EU_DNCTT_CONTRACT_COST a LEFT JOIN BO_EU_DNCTT_CONTRACT_COST_PRODUCT b ON a.ID=b.CONTRACT_COST_ID AND b.CLOSED = 0 WHERE a.ID=?";
                    if (DBSql.getInt(sql, new Object[]{bo.getString("CONTRACT_COST_ID")}) <= 0) {
                        BO contractProductBo = SDK.getBOAPI().get(IVTConstant.BO_EU_DNCTT_CONTRACT_COST, bo.getString("CONTRACT_COST_ID"));
                        contractProductBo.set("STATUS_ID", IVTConstant.STATUS_1236);//待配送

                        //更新采购订单号
                        String PURCHASE_ORDER_NO = DBSql.getString("SELECT GROUP_CONCAT(PURCHASE_ORDER_NO) FROM " + IVTConstant.BO_EU_DNIVT_ORDER + " WHERE CLOSED=0 AND ID IN (SELECT ORDER_ID FROM BO_EU_DNIVT_ORDER_PRODUCT WHERE CONTRACT_COST_ID=?) ", new Object[]{bo.getString("CONTRACT_COST_ID")});
                        contractProductBo.set("PURCHASE_ORDER_NO", PURCHASE_ORDER_NO);
                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST, contractProductBo);
                    }
                    //更新合同产品上面的合同产品状态

                    BO costProduct = SDK.getBOAPI().query(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT).addQuery("ORDER_ID=", bo.getString("ORDER_ID")).addQuery("CONTRACT_COST_ID=", bo.getString("CONTRACT_COST_ID")).detail();
                    if (costProduct != null) {
                        costProduct.set("STATUS_ID", "2158");//待配送
                        costProduct.set("SN", DBSql.getString("SELECT GROUP_CONCAT(SN) FROM BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT WHERE ORDER_PRODUCT_ID=?", new Object[]{bo.getId()}));
                        //记录日志
                        dn.recordFormChanges.record(uc, costProduct, "采购产品接收后更新");
                        SDK.getBOAPI().update(IVTConstant.BO_EU_DNCTT_CONTRACT_COST_PRODUCT, costProduct);
                    }
                }

            } else if (count > 0 || exitsReceive) {
                //部分接收
                DBSql.update("UPDATE " + IVTConstant.BO_EU_DNIVT_ORDER + " SET STATUS_ID=" + IVTConstant.STATUS_2149 + " WHERE BINDID='" + orderBindId + "'");
            } else {
                DBSql.update("UPDATE " + IVTConstant.BO_EU_DNIVT_ORDER + " SET STATUS_ID=" + IVTConstant.STATUS_2148 + " WHERE BINDID='" + orderBindId + "'");
            }
        }


        return "";
    }
}
