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.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ivtTransferFormSaveAfter extends ExecuteListener {
    public String getDescription() {
        return "表单保存后，数据处理事件";
    }

    /**
     *转移单保存后，更新库存
     * @param processExecutionContext
     * @throws Exception
     */
    @Override
    public void execute(ProcessExecutionContext processExecutionContext) throws Exception {
        String processId = processExecutionContext.getProcessInstance().getId();
        RowMap rowMap = DBSql.getMap("select * from BO_EU_DNIVT_TRANSFER where BINDID =?", new Object[]{processId});
        if (rowMap.getString("STATUS").equals("1"))
            return;

        String sns = rowMap.getString("SN");
        Connection conn = null;
        try {
            conn = DBSql.open();
            conn.setAutoCommit(false);

            String PRODUCT_ID = rowMap.getString("PRODUCT_ID");//产品id
            String FROM_WAREHOUSE_ID = rowMap.getString("FROM_WAREHOUSE_ID");//转出仓库id
            String TYPE_ID = rowMap.getString("TYPE_ID");//转出类型

            if (StringUtils.isNotBlank(TYPE_ID) && !TYPE_ID.equals("0")) {
                BO fromBO = SDK.getBOAPI().query("BO_EU_DNIVT_WAREHOUSE_PRODUCT").connection(conn).addQuery("PRODUCT_ID=", PRODUCT_ID).addQuery("WAREHOUSE_ID=", FROM_WAREHOUSE_ID).detail();

                int transferQuantity = rowMap.getInt("QUANTITY");//转出数量
                int fromQuantity = Integer.parseInt(fromBO.get("QUANTITY").toString()) - transferQuantity;
                if (fromQuantity < 0) {
                    //报错
                    throw new RuntimeException("转出数量不能大于库存数量");
                }
                fromBO.set("QUANTITY", fromQuantity);
                SDK.getBOAPI().update("BO_EU_DNIVT_WAREHOUSE_PRODUCT", fromBO, conn);

                List<Map<String, Object>> fromLosts = new ArrayList<>();
                //更新出库的批次号

                String[] asArr = sns.split(",");
                int cnt = 0;
                List<BO> lots = SDK.getBOAPI().query("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT").addQuery("BINDID=", fromBO.getBindId()).addQuery("QUANTITY>0", null).orderByCreated().list();
                for (BO lot : lots) {
                    if (StringUtils.isNotBlank(sns)) {
                        //序列化产品
                        boolean isIn = false;
                        String lotSN = lot.getString("SN");
                        lotSN = "," + lotSN + ",";
                        List<String> toSN = new ArrayList<>();
                        for (String sn : asArr) {
                            if (lotSN.contains("," + sn + ",")) {
                                isIn = true;
                                lotSN = lotSN.replace("," + sn + ",", ",");
                                toSN.add(sn);
                                cnt++;
                            }
                            if (cnt >= asArr.length) break;
                        }
                        if (isIn) {
                            if (StringUtils.isNotBlank(lotSN)) {
                                lotSN = lotSN.replaceAll("^,+|,+$", "") // 移除首尾一个或多个逗号
                                        .replaceAll(",+", ",");     // 合并中间连续逗号
                                int count = (int) lotSN.chars().filter(c -> c == ',').count();
                                lot.set("SN", lotSN);
                                lot.set("QUANTITY", count + 1);
                            } else {
                                lot.set("SN", "");
                                lot.set("QUANTITY", 0);
                            }

                            SDK.getBOAPI().update("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT", lot, conn);
                            Map<String, Object> map = lot.asMap();
                            map.remove("ID");
                            map.remove("BINDID");
                            map.put("SN", StringUtils.join(toSN, ","));
                            map.put("QUANTITY", toSN.size());
                            fromLosts.add(map);
                        }
                        if (cnt >= asArr.length)
                            break;
                    } else {
                        //无序列化
                        int count = Integer.parseInt(lot.get("QUANTITY").toString());
                        int toQuantity = 0;
                        if (count > transferQuantity) {
                            lot.set("QUANTITY", count - transferQuantity);
                            toQuantity = transferQuantity;
                            transferQuantity = 0;
                        } else {
                            lot.set("QUANTITY", 0);
                            toQuantity = count;
                            transferQuantity = transferQuantity - count;
                        }

                        SDK.getBOAPI().update("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT", lot, conn);
                        Map<String, Object> map = lot.asMap();
                        map.remove("ID");
                        map.remove("BINDID");
                        map.put("SN", "");
                        map.put("QUANTITY", toQuantity);
                        fromLosts.add(map);
                        if (transferQuantity <= 0)
                            break;
                    }
                }


                if (TYPE_ID.equals("1481"))//仓库间转移
                {
                    String TO_WAREHOUSE_ID = rowMap.getString("TO_WAREHOUSE_ID");//转入仓库id
                    if (StringUtils.isBlank(TO_WAREHOUSE_ID)) {
                        //报错
                        throw new RuntimeException("转入仓库不能为空");
                    }
                    BO toBO = SDK.getBOAPI().query("BO_EU_DNIVT_WAREHOUSE_PRODUCT").connection(conn).addQuery("PRODUCT_ID=", PRODUCT_ID).addQuery("WAREHOUSE_ID=", TO_WAREHOUSE_ID).detail();

                    if (toBO == null) {
                        ProcessInstance processInstance = SDK.getProcessAPI().createBOProcessInstance("obj_41f06b1e807647db8a69dd10d4be5764", processExecutionContext.getUserContext().getUID(), "新增库存产品" + PRODUCT_ID + "仓库间转移" + TO_WAREHOUSE_ID);
                        toBO = new BO();
                        toBO.set("PRODUCT_ID", PRODUCT_ID);
                        toBO.set("WAREHOUSE_ID", TO_WAREHOUSE_ID);
                        toBO.set("QUANTITY", rowMap.getInt("QUANTITY"));
                        toBO.setBindId(processInstance.getId());
                        SDK.getBOAPI().create("BO_EU_DNIVT_WAREHOUSE_PRODUCT", toBO, processInstance.getId(), processExecutionContext.getUserContext().getUID(), conn);
                    } else {
                        toBO.set("QUANTITY", Integer.parseInt(toBO.get("QUANTITY").toString()) + rowMap.getInt("QUANTITY"));
                        SDK.getBOAPI().update("BO_EU_DNIVT_WAREHOUSE_PRODUCT", toBO, conn);
                    }


                    //入库的批次号
                    //更新出库的批次号
                    if (StringUtils.isNotBlank(sns)) {
                        for (Map<String, Object> lot : fromLosts) {
                            BO toLot = SDK.getBOAPI().query("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT").addQuery("LOT=", lot.get("LOT")).addQuery("ORDER_PRODUCT_ID=", lot.get("ORDER_PRODUCT_ID")).addQuery("BINDID=", toBO.getBindId()).detail();
                            if (toLot != null) {
                                toLot.set("QUANTITY", Integer.parseInt(toLot.get("QUANTITY").toString()) + Integer.parseInt(lot.get("QUANTITY").toString()));
                                if (StringUtils.isNotBlank(lot.get("SN").toString()))
                                    toLot.set("SN", toLot.get("SN") + "," + lot.get("SN"));
                                SDK.getBOAPI().update("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT", toLot, conn);
                            } else {
                                toLot = new BO();
                                toLot.setAll(lot);
                                toLot.setBindId(toBO.getBindId());
                                toLot.set("ORDER_PRODUCT_ID", lot.get("ORDER_PRODUCT_ID"));
                                toLot.set("WAREHOUSE_ID", toBO.get("WAREHOUSE_ID"));
                                toLot.set("PRODUCT_ID", toBO.get("PRODUCT_ID"));
                                SDK.getBOAPI().createDataBO("BO_EU_DNIVT_WAREHOUSE_PRODUCT_LOT", toLot, processExecutionContext.getUserContext(), conn);
                            }
                        }
                    }
                }
            }

            //更新状态
            DBSql.update(conn, "update BO_EU_DNIVT_TRANSFER set STATUS=1 where BINDID=?", new Object[]{processId});

            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
        } finally {
            if (conn != null) DBSql.close(conn);
        }

    }
}
