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.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class ivtOrderFormAfter extends ExecuteListener {
    private static final Logger logger = SDK.getLogAPI().getLogger(ivtOrderFormAfter.class);//记录日志

    public String getDescription() {
        return "采购订单表单保存后，数据处理事件";
    }

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

        logger.info("采购订单表单保存后，数据处理事件");
        BO orderBO = SDK.getBOAPI().getByProcess("BO_EU_DNIVT_ORDER", processExecutionContext.getProcessInstance().getId());
        List<BO> orderProducts = SDK.getBOAPI().query("BO_EU_DNIVT_ORDER_PRODUCT").bindId(orderBO.getBindId()).list();
        List<BO> costProducts = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_COST_PRODUCT").addQuery("ORDER_ID =", orderBO.getId()).list();

        for (BO costProduct : costProducts) {

            BO orderProduct = orderProducts.stream().filter(op -> op.getString("CONTRACT_COST_ID").equals(costProduct.getString("CONTRACT_COST_ID"))).findFirst().orElse(null);
            if (orderProduct == null) {
                continue;
            }
            costProduct.set("WAREHOUSE_ID", orderProduct.get("WAREHOUSE_ID"));
            costProduct.set("QUANTITY", orderProduct.get("QUANTITY"));
            costProduct.set("UNIT_COST", orderProduct.get("UNIT_COST"));
            costProduct.set("QUANTITY", orderProduct.get("QUANTITY"));
            costProduct.set("OLD_QUANTITY", orderProduct.get("QUANTITY"));

            SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", costProduct);
        }

        //删除多余的采购订单产品
        List<String> costProductIds = DBSql.getList("SELECT a.ID FROM BO_EU_DNCTT_CONTRACT_COST_PRODUCT a  LEFT JOIN BO_EU_DNIVT_ORDER_PRODUCT b ON a.ORDER_ID=b.ORDER_ID AND a.CONTRACT_COST_ID=b.CONTRACT_COST_ID WHERE b.ID IS NULL AND a.ORDER_ID=?", String.class, new Object[]{orderBO.getId()});
        for (String costProductId : costProductIds) {
            SDK.getBOAPI().remove("BO_EU_DNCTT_CONTRACT_COST_PRODUCT", costProductId);
        }

        //采购订单编号
        String purchaseOrderNo = orderBO.getString("PURCHASE_ORDER_NO");
        logger.info("采购订单编号：" + purchaseOrderNo);
        if (StringUtils.isBlank(purchaseOrderNo) || purchaseOrderNo.indexOf("CHT") != 0) {

            // purchaseOrderNo = SDK.getRuleAPI().executeAtScript("@sequenceYear(@companyId_purchase_order,4,0,130)", processExecutionContext.getUserContext());

            String varname = processExecutionContext.getUserContext().getCompanyModel().getId() + "_ivtorder_" + LocalDate.now().getYear();
            purchaseOrderNo = SDK.getRuleAPI().executeAtScript("@sequence(" + varname + ",5)");

            String cssx = "SH";//城市缩写
            /*
            String DISTRICT_ID = DBSql.getString("select DISTRICT_ID from BO_EU_DNCRM_ACCOUNT where ID=?", new Object[]{orderBO.getString("VENDOR_ACCOUNT_ID")});
            if (StringUtils.isNotBlank(DISTRICT_ID)) {
                RowMap city = DBSql.getMap("SELECT EXTTEXT1,EXTTEXT2 FROM BO_ACT_DICT_KV_ITEM WHERE DICTKEY = 'GB.ADDR' AND ITEMNO= ?", new Object[]{DISTRICT_ID});
                if (city != null) {
                    cssx = city.getString("EXTTEXT1");
                    if (!cssx.contains("市")) {
                        cssx = city.getString("EXTTEXT2");
                    }
                    //如果 cssx="上海市" 则输出 SH
                    cssx = getCityAbbreviation(cssx);
                }
            }
            */
            purchaseOrderNo = "CHT-" + cssx + "-" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "-" + purchaseOrderNo;

            orderBO.set("PURCHASE_ORDER_NO", purchaseOrderNo);

            logger.info("采购订单编号：" + purchaseOrderNo);

            SDK.getBOAPI().update("BO_EU_DNIVT_ORDER", orderBO);

        }
    }
}
