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

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.awspaas.user.apps.donenow_ctt.service.wareHouseProductService;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.util.*;

public class costPickFormAfterSave extends ExecuteListener {
    public String getDescription() {
        return "合同产品拣货保存后";
    }

    /**
     *拣货
     * @param processExecutionContext
     * @throws Exception
     */
    @Override
    public void execute(ProcessExecutionContext processExecutionContext) throws Exception {

        BO pickBO = SDK.getBOAPI().getByProcess("BO_EU_DNCTT_CONTRACT_PRODUCT_PICK", processExecutionContext.getProcessInstance().getId());
        String warehouseProductId = pickBO.getString("WAREHOUSE_PRODUCT_ID");
        String contractCostId = pickBO.getString("CONTRACT_COST_ID");

        Set<String> pickSerials = new LinkedHashSet<>();
        String pick_sns = pickBO.getString("SERIAL_NUMBERS");
        String PICKED_SNS = pickBO.getString("PICKED_SNS");

        // 处理PICKED_SNS不为空的情况
        if (StringUtils.isNotBlank(PICKED_SNS)) {
            // 1. 处理originalSerials为null的情况，转为空字符串避免拼接出"null"
            String normalizedOriginals = StringUtils.defaultString(pick_sns, "");

            // 2. 拼接两个字符串，避免在originalSerials为空时产生多余逗号（如"picked,"）
            String combined;
            if (normalizedOriginals.isEmpty()) {
                combined = PICKED_SNS;
            } else {
                combined = PICKED_SNS + "," + normalizedOriginals;
            }

            // 3. 分割并去重，用LinkedHashSet保持插入顺序（首次出现的元素保留）

            for (String serial : combined.split(",")) {
                // 过滤空字符串（避免连续逗号产生的空元素）
                if (StringUtils.isNotBlank(serial)) {
                    pickSerials.add(serial);
                }
            }

            // 4. 拼接去重后的结果，更新回BO
            pick_sns = StringUtils.join(pickSerials, ",");
            pickBO.set("SERIAL_NUMBERS", pick_sns);
        }


        int PICK_QUANTITY = ObjToInt(pickBO.get("PICK_QUANTITY"));//拣货数量
        //验库存
        //可用库存
        int warehouseProductAvailableQuantity = ObjToInt(DBSql.getString("SELECT SUM(AVAILABLE) FROM VIEW_EU_DNINVT_PRODUCT_INVENTORY where ID=?", new Object[]{warehouseProductId}));

        if (warehouseProductAvailableQuantity <= 0) throw new BPMNError("", "库存数量不足");

        if (PICK_QUANTITY > warehouseProductAvailableQuantity) throw new BPMNError("", "库存数量不足");

        int contractCostQuantity = ObjToInt(SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST", contractCostId, "QUANTITY"));//全部拣货数量
        //已拣货数量
        int contractProductPickQuantity = ObjToInt(DBSql.getString("SELECT SUM(QUANTITY) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=?  AND CLOSED=0", new Object[]{contractCostId}));

        if (contractProductPickQuantity + PICK_QUANTITY > contractCostQuantity)
            throw new BPMNError("", "拣货数量超出合同数量");

        Connection conn = null;
        try {
            conn = DBSql.open();
            conn.setAutoCommit(false);
            // PICK_TYPE 拣货方式
            String WAREHOUSE_ID = pickBO.getString("WAREHOUSE_ID");

            int STATUS_ID = 2157;//库存转移给我
            if (pickBO.getString("PICK_TYPE").equals("1"))//库存转移给我
            {
                String resWareId = DBSql.getString(conn, "SELECT ID FROM BO_EU_DNIVT_WAREHOUSE WHERE RESOURCE_ID=? AND CLOSED=0 ", new Object[]{processExecutionContext.getUserContext().getUID()});
                if (StringUtils.isNotBlank(resWareId)) {
                    WAREHOUSE_ID = resWareId;
                } else {
                    BO resWare = new BO();
                    resWare.set("NAME", "员工：" + processExecutionContext.getUserContext().getUserName());

                    ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_e10413dd6e034d22aac787a35917814c", processExecutionContext.getUserContext().getUID(), "创建员工仓库" + resWare.getString("NAME"));
                    resWare.setBindId(processInstance.getId());
                    resWare.set("IS_DEFAULT", 0);
                    resWare.set("IS_ACTIVE", 1);
                    resWare.set("RESOURCE_ID", processExecutionContext.getUserContext().getUID());
                    SDK.getBOAPI().create("BO_EU_DNIVT_WAREHOUSE", resWare, processInstance, processExecutionContext.getUserContext(), conn);
                    WAREHOUSE_ID = resWare.getId();
                }
            } else if (pickBO.getString("PICK_TYPE").equals("2")) {
                STATUS_ID = 2159;//已配送
            }

            BO costProductBO = new BO();
            ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_6bc913271069455abbd516c556b26d31", processExecutionContext.getUserContext().getUID(), "合同产品物流管理");

            costProductBO.setBindId(processInstance.getId());

            // costProductBO.setBindId(SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT_COST", contractCostId, "BINDID").toString());
            costProductBO.set("WAREHOUSE_ID", WAREHOUSE_ID);
            costProductBO.set("CONTRACT_COST_ID", contractCostId);
            costProductBO.set("QUANTITY", pickBO.get("PICK_QUANTITY"));
            costProductBO.set("SN", pick_sns);
            costProductBO.set("STATUS_ID", STATUS_ID);
            costProductBO.set("OLD_QUANTITY", costProductBO.get("QUANTITY"));//配送数量
            SDK.getBOAPI().create("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", costProductBO, processInstance, processExecutionContext.getUserContext(), conn);


            //修改状态
            int contractCostStatusId = 0;
            contractCostQuantity = ObjToInt(SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_COST").connection(conn).detailByField(contractCostId, "QUANTITY"));//全部拣货数量
            //已拣货数量
            contractProductPickQuantity = ObjToInt(DBSql.getString(conn, "SELECT SUM(QUANTITY) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=? AND CLOSED=0", new Object[]{contractCostId}));

            if (contractCostQuantity == contractProductPickQuantity) {
                // 只要存在采购中
                if (DBSql.getInt(conn, "SELECT COUNT(1) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=? AND CLOSED=0 AND STATUS_ID=?", new Object[]{contractCostId, 2156}) > 0) {
                    contractCostStatusId = 1235;   // 采购中
                } else if (DBSql.getInt(conn, "SELECT COUNT(1) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=? AND CLOSED=0 AND STATUS_ID<>? AND STATUS_ID<>?", new Object[]{contractCostId, 2157, 2158}) == 0) {
                    contractCostStatusId = 1236;  // 待配送
                } else if (DBSql.getInt(conn, "SELECT COUNT(1) FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT WHERE CONTRACT_COST_ID=? AND CLOSED=0 AND STATUS_ID<>? ", new Object[]{contractCostId, 2159}) == 0) {
                    contractCostStatusId = 1237;   // 已配送
                } else {
                    contractCostStatusId = 1236;  // 待配送
                }
            } else {
                if (DBSql.getInt(conn, "SELECT DOES_NOT_REQUIRE_PROCUREMENT FROM BO_EU_DNIVT_PRODUCT WHERE ID=?", new Object[]{pickBO.getString("PRODUCT_ID")}) == 1) {
                    contractCostStatusId = 1234;
                } else {


                }

            }
            if (contractCostStatusId != 0) {
                DBSql.update(conn, "UPDATE BO_EU_DNCTT_CONTRACT_COST SET STATUS_ID=? WHERE ID=?", new Object[]{contractCostStatusId, contractCostId});
            }


            if (pickBO.getString("PICK_TYPE").equals("1"))//库存转移给我
            {
                wareHouseProductService.getInstance().transfer(processExecutionContext.getUserContext(), conn, pickBO.getString("PRODUCT_ID"), pickBO.getString("WAREHOUSE_ID"), WAREHOUSE_ID, ObjToInt(pickBO.get("PICK_QUANTITY")), pick_sns, 1481, null); // 仓库间转移

            } else if (pickBO.getString("PICK_TYPE").equals("2"))//库存转移给客户
            {
                BO costBO = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_COST").connection(conn).addQuery("ID=", pickBO.getString("CONTRACT_COST_ID")).detail();

                Map<String, Object> ivtTransfer = new HashMap<>();
                ivtTransfer.put("TO_ACCOUNT_ID", costBO.get("ACCOUNT_ID"));
                ivtTransfer.put("TO_CONTRACT_ID", costBO.get("CONTRACT_ID"));
                ivtTransfer.put("TO_PROJECT_ID", costBO.get("PROJECT_ID"));
                ivtTransfer.put("TO_TASK_ID", costBO.get("TASK_ID"));

                wareHouseProductService.getInstance().transfer(processExecutionContext.getUserContext(), conn, pickBO.getString("PRODUCT_ID"), pickBO.getString("WAREHOUSE_ID"), null, ObjToInt(pickBO.get("PICK_QUANTITY")), pick_sns, 1482, ivtTransfer); // 转移给客户
            }


            //已完成拣货或者在采购中

            //仍需数量：
            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(conn, sql, new Object[]{contractCostId}) <= 0) {
                //更新状态
                BO costBO = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_COST").connection(conn).addQuery("ID=", contractCostId).detail();
                if (DBSql.getInt(conn, "select count(ID) from BO_EU_DNCTT_CONTRACT_COST_PRODUCT where CONTRACT_COST_ID=? AND STATUS_ID=2156  AND CLOSED=0", new Object[]{contractCostId}) > 0) {
                    costBO.set("STATUS_ID", 1235); //1235 采购中
                } else if (DBSql.getInt(conn, "select count(ID) from BO_EU_DNCTT_CONTRACT_COST_PRODUCT where CONTRACT_COST_ID=? AND (STATUS_ID=2158 OR STATUS_ID=2157)  AND CLOSED=0", new Object[]{contractCostId}) > 0) {
                    costBO.set("STATUS_ID", 1236); //1236 待配送
                } else {
                    costBO.set("STATUS_ID", 1237); //1236 已配送
                }
                SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_COST", costBO, conn);
            }

            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            throw new BPMNError("550", "库存转移失败");
        } finally {
            DBSql.close(conn);
        }

    }

    /**
     * 将Object转换为int
     * @param obj
     * @return
     */
    private int ObjToInt(Object obj) {
        if (obj == null)
            return 0;

        String objStr = obj.toString();
        if (objStr.equals(""))
            return 0;
        //如果有小数点，只取整数
        if (objStr.contains(".")) {
            objStr = objStr.substring(0, objStr.indexOf("."));
        }
        return Integer.parseInt(objStr);
    }


}
