package com.yem.wm.im.placeexamine.op;

import com.yem.em.utils.BigDecimalUtils;
import com.yem.wm.im.placeexamine.vaildator.AlaceexamineUnAuditValidator;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/10/10 14:54
 * @className AlaceexamineUnAuditOp
 * @description 下单审批【反审核】服务插件
 */
public class AlaceexamineUnAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        //audit
        if ("unaudit".equals(e.getOperationKey())) {
            if (null != e.getDataEntities()) {
                DynamicObject[] bills = e.getDataEntities();
                for (int i = 0; i < bills.length; ++i) {
                    DynamicObject bill = bills[i];
                    bill = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
                    back_placeexamine(bill);
                }
            }
        }
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new AlaceexamineUnAuditValidator());
    }

    /**
     * 根据外销合同id删除外销合同下游《跟单任务控制台》
     *
     * @param bill
     */
    public static void back_placeexamine(DynamicObject bill) {
        Map map = new HashMap<>();//存放跟单任务控制台内码
        List del_id_s = new ArrayList();
        long yemSourcebillid = bill.getLong("yem_sourcebillid");//外销合同id
        long id = bill.getLong("id");//当前单据id
        DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yemSourcebillid, "yem_es_salesorder");
        if (yem_es_salesorder != null) {
            DynamicObjectCollection yem_Shippingplan = yem_es_salesorder.getDynamicObjectCollection("yem_shippingplan_entry");
            for (int i = 0; i < yem_Shippingplan.size(); i++) {
                DynamicObject Shippingplan = yem_Shippingplan.get(i);
                DynamicObject yemPlaceexamine = Shippingplan.getDynamicObject("yem_placeexamine");
                if (yemPlaceexamine != null) {
                    if (yemPlaceexamine.getLong("id") == id) {
                        DynamicObjectCollection yemPlandetailEntry = Shippingplan.getDynamicObjectCollection("yem_plandetail_entry");
                        for (int j = 0; j < yemPlandetailEntry.size(); j++) {
                            DynamicObject PlandetailEntry = yemPlandetailEntry.get(j);
                            if (PlandetailEntry != null) {
                                DynamicObject yem_tracktaskconsole = PlandetailEntry.getDynamicObject("yem_tracktaskconsole");
                                if (yem_tracktaskconsole != null) {
                                    if (!map.containsKey(yem_tracktaskconsole.getLong("id"))) {
                                        map.put(yem_tracktaskconsole.getLong("id"), yem_tracktaskconsole);
                                    }
                                }

                            }
                        }
                        break;
                    }
                }
            }

            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next().toString();
                DynamicObject yem_tracktaskconsole = BusinessDataServiceHelper.loadSingle(key, "yem_tracktaskconsole");
                //备料信息
                DynamicObjectCollection yem_es_salesorder_r_s = yem_tracktaskconsole.getDynamicObjectCollection("yem_es_salesorder_r");
                if (null != yem_es_salesorder_r_s && yem_es_salesorder_r_s.size() > 0) {
                    throw new KDBizException("单据编号【" + yem_tracktaskconsole.getString("billno") + "】跟单任务控制台已下备料，不允许取消！");
                }

                String billstatus = yem_tracktaskconsole.getString("billstatus");
                if (!"A".equals(billstatus)) {
                    throw new KDBizException("单据编号【" + yem_tracktaskconsole.getString("billno") + "】跟单任务已提交/审核，不允许取消！");
                }
                //下游订单产品需求单
                QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, yem_tracktaskconsole.getLong("id"));
                DynamicObject[] yem_orderproreqbill_s = BusinessDataServiceHelper.load("yem_orderproreqbill", "id,billno,billstatus",
                        new QFilter[]{qFilter}, null);
                if (null != yem_orderproreqbill_s && yem_orderproreqbill_s.length > 0) {
                    throw new KDBizException("单据编号【" + yem_tracktaskconsole.getString("billno") + "】跟单任务下游存在订单产品需求单，不允许取消！");
                }
                del_id_s.add(yem_tracktaskconsole.getLong("id"));
            }
            //删除跟单任务
            if (del_id_s.size() > 0) {
//                QFilter qFilter = new QFilter("id", QCP.in, del_id_s);
//                DeleteServiceHelper.delete("yem_tracktaskconsole", new QFilter[]{qFilter});
                for (int i = 0; i < del_id_s.size(); i++) {
                    Object o = del_id_s.get(i);
                    OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_tracktaskconsole", new Object[]{o}, OperateOption.create());
                    if (!delete.isSuccess()) {
                        String message = delete.getMessage();
                        List<IOperateInfo> allErrorOrValidateInfo = delete.getAllErrorOrValidateInfo();
                        throw new KDBizException(String.format("《跟单任务》删除失败，%s，%s", message, allErrorOrValidateInfo));
                    }
                }
            }
            //取消外销合同跟单任务明细记录【yem_tracktaskconsoleid】、【yem_tracktaskconsole】
            for (int i = 0; i < yem_Shippingplan.size(); i++) {
                DynamicObject Shippingplan = yem_Shippingplan.get(i);
                DynamicObject yemPlaceexamine = Shippingplan.getDynamicObject("yem_placeexamine");
                if (yemPlaceexamine != null) {
                    if (yemPlaceexamine.getLong("id") == id) {
                        DynamicObjectCollection yemPlandetailEntry = Shippingplan.getDynamicObjectCollection("yem_plandetail_entry");
                        for (int j = 0; j < yemPlandetailEntry.size(); j++) {
                            DynamicObject PlandetailEntry = yemPlandetailEntry.get(j);
                            if (PlandetailEntry != null) {
                                PlandetailEntry.set("yem_tracktaskconsoleid", 0);
                                PlandetailEntry.set("yem_tracktaskconsole", null);
                            }
                        }
                        break;
                    }
                }
            }
//            cal_yem_orderqty(yem_es_salesorder);
            SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
        }
    }

    /**
     * 计算已下单数量、剩余未下单数量
     *
     * @param bill 外销合同
     */
    public static void cal_yem_orderqty(DynamicObject bill) {
        Map map = new HashMap();
        DynamicObjectCollection yem_shippingplan_entry_s = bill.getDynamicObjectCollection("yem_shippingplan_entry");
        for (int i = 0; i < yem_shippingplan_entry_s.size(); i++) {
            DynamicObject yem_shippingplan_entry = yem_shippingplan_entry_s.get(i);
            DynamicObjectCollection yem_plandetail_entry_s = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");
            for (int j = 0; j < yem_plandetail_entry_s.size(); j++) {
                DynamicObject yem_plandetail_entry = yem_plandetail_entry_s.get(j);
                BigDecimal yem_qty2 = yem_plandetail_entry.getBigDecimal("yem_qty2");
                long yem_srcentryid = yem_plandetail_entry.getLong("yem_srcentryid");
                if (map.containsKey(yem_srcentryid)) {
                    BigDecimal yem_qty2_old = new BigDecimal(map.get(yem_srcentryid).toString());
                    map.put(yem_srcentryid, yem_qty2_old.add(yem_qty2));
                } else {
                    map.put(yem_srcentryid, yem_qty2);
                }
            }
        }
        DynamicObjectCollection yem_es_materialinfo_s = bill.getDynamicObjectCollection("yem_es_materialinfo");
        for (int i = 0; i < yem_es_materialinfo_s.size(); i++) {
            DynamicObject yem_es_materialinfo = yem_es_materialinfo_s.get(i);
            BigDecimal yem_qty = yem_es_materialinfo.getBigDecimal("yem_qty");
            BigDecimal yem_orderqty = BigDecimalUtils.toBigDecimal(map.get(yem_es_materialinfo.getLong("id")));
            BigDecimal yem_unorderqty = BigDecimalUtils.sub(yem_qty, yem_orderqty, 10);
            yem_es_materialinfo.set("yem_orderqty", yem_orderqty);
            yem_es_materialinfo.set("yem_unorderqty", yem_unorderqty);
        }
    }
}
