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

import com.yem.em.utils.BigDecimalUtils;
import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.botp.runtime.SourceBillReport;
import kd.bos.entity.datamodel.IRefrencedataProvider;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.operate.OperateOptionConst;
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.args.AfterOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/9/28 16:38
 * @className AlaceexamineAuditOp
 * @description 下单审批【审核】服务插件
 */
public class AlaceexamineAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);


        // 审核执行转移到提交执行 --2024-04-13 张子帅
        //audit
//        if ("place".equals(e.getOperationKey()) || "audit".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);
//                }
//            }
//        }
    }

    /**
     * 根据外销合同id调用生成跟单任务控制
     *
     * @param bill
     */
    public static void back_placeexamine(DynamicObject bill) {
        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) {
            Map BOTPmap = new HashMap<>();
            Map<Long, Map<String, Object>> orderFieldMap = new HashMap<>();
            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) {
                                String yem_businesssort1 = PlandetailEntry.getString("yem_businesssort1");
                                BOTPmap.put(yem_businesssort1, Shippingplan);
                                Map<String, Object> map = new HashMap<>();
                                map.put("yem_isckd", bill.getString("yem_isckd"));
                                orderFieldMap.put(yemSourcebillid, map);
                            }
                        }
                        break;
                    }
                }
            }
            Iterator iteratorBOTP = BOTPmap.keySet().iterator();
            while (iteratorBOTP.hasNext()) {
                String key = iteratorBOTP.next().toString();
                DynamicObject value = (DynamicObject) BOTPmap.get(key);
                //生成跟单任务控制台
                create_yem_tracktaskconsole(yemSourcebillid, value, key, yem_es_salesorder, orderFieldMap);
            }
        }
    }

    /**
     * 生成跟单任务控制台
     *
     * @param bill_id                外销合同id
     * @param yem_shippingplan_entry 跟单任务对象
     * @param key                    业务类型
     * @param orderFieldMap
     */
    public static void create_yem_tracktaskconsole(long bill_id, DynamicObject yem_shippingplan_entry, String key, DynamicObject yem_es_salesorder, Map<Long, Map<String, Object>> orderFieldMap) {
        String isckd = "";
        if (orderFieldMap.containsKey(bill_id)) {
            Map<String, Object> map = orderFieldMap.get(bill_id);
            if (map.containsKey("yem_isckd")) {
                isckd = (String) map.get("yem_isckd");
            }
        }
        String bill1 = "yem_es_salesorder";
        String bill2 = "yem_tracktaskconsole";
        String ruleId = "";
        if ("Z".equals(key)) {
            ruleId = "1746461370783643648";
        } else if ("P".equals(key)) {
            ruleId = "1746467553313569792";
        }

        PushArgs pushArgs = new PushArgs();
        pushArgs.setSourceEntityNumber(bill1);        // 必选，源单标识
        pushArgs.setTargetEntityNumber(bill2);      // 必选，目标单标识
        pushArgs.setHasRight(false);                // 可选，传入true，不检查目标单新增权
        pushArgs.setAppId("yem_es");                // 可选，传入目标单验权使用的应用编码
        pushArgs.setDefOrgId(0L);                    // 可选，传入目标单主组织默认值
        pushArgs.setRuleId(ruleId);                    // 可选，传入本次下推使用的转换规则id；传入空值，由系统自动寻找合适的转换规则
        pushArgs.setBuildConvReport(true);            // 是否输出详细错误报告

        List<ListSelectedRow> selectedRows = new ArrayList<>();
        ListSelectedRow srcBillRows = new ListSelectedRow(bill_id);
        selectedRows.add(srcBillRows);
        pushArgs.setSelectedRows(selectedRows);        // 必选，设置需要下推的源单及分录内码

        // 调用下推引擎，下推目标单
        ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);

        // 判断下推是否成功，如果失败，提炼失败消息输出
        if (!pushResult.isSuccess()) {
            String errMessage = pushResult.getMessage();    // 错误摘要
            for (SourceBillReport billReport : pushResult.getBillReports()) {
                // 演示如何提取各单错误报告
                if (!billReport.isSuccess()) {
                    String billMessage = billReport.getFailMessage();
                    errMessage = errMessage + ";" + billMessage;
                }
            }
            throw new KDBizException("下推失败:" + errMessage);
        }

        // 获取生成的目标单数据包
        MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(bill2);
        List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
            @Override
            public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                BusinessDataReader.loadRefence(objs, dType);
            }
        }, targetMainType);

        DynamicObject newbill = targetBillObjs.get(0);

        initData(yem_shippingplan_entry, newbill, key, isckd);

        OperateOption option = OperateOption.create();
        option.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true));    // 不执行警告级别校验器
        option.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true));    // 不显示交互提示，自动执行到底
        option.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(true));        // 全部校验通过才保存
        option.setVariableValue(OperateOptionConst.ISHASRIGHT, String.valueOf(true));

        OperationResult result_save = SaveServiceHelper.saveOperate(bill2, new DynamicObject[]{newbill}, option);
        // 判断保存结果
        if (!result_save.isSuccess()) {
            String errMessage = result_save.getMessage();
            List<IOperateInfo> operateInfo = result_save.getAllErrorOrValidateInfo();
            for (IOperateInfo tempOperateInfo : operateInfo) {
                errMessage = errMessage + ";" + tempOperateInfo.getMessage();
            }
            throw new KDBizException("生成跟单任务控制台时保存失败：" + errMessage);
        } else {
            //跟单任务控制台
            long id = (long) result_save.getSuccessPkIds().get(0);
            DynamicObject yem_tracktaskconsole = BusinessDataServiceHelper.loadSingle(id, "yem_tracktaskconsole");
            DynamicObject yem_billtype = yem_tracktaskconsole.getDynamicObject("yem_billtype");//跟单任务控制台单据类型
            DynamicObjectCollection yem_es_materialinfo = yem_tracktaskconsole.getDynamicObjectCollection("yem_es_materialinfo");
            //外销合同子单据体
            DynamicObjectCollection yem_plandetail_entry = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");
            for (int i = 0; i < yem_plandetail_entry.size(); i++) {//外销合同子单据体
                DynamicObject plandetail = yem_plandetail_entry.get(i);
                for (int k = 0; k < yem_es_materialinfo.size(); k++) {//跟单任务控制台
                    DynamicObject aterialinfo = yem_es_materialinfo.get(k);//跟单子分录
                    String yem_businesssort1 = plandetail.getString("yem_businesssort1");
                    if (yem_businesssort1.equals("Z") && yem_billtype.getString("number").equals("yem_tracktaskconsole_zj")) {//整机
                        plandetail.set("yem_tracktaskconsole", yem_tracktaskconsole);
                        plandetail.set("yem_tracktaskconsoleid", id);
                    }
                    if (yem_businesssort1.equals("P") && yem_billtype.getString("number").equals("yem_tracktaskconsole_pj")) {//配件
                        plandetail.set("yem_tracktaskconsole", yem_tracktaskconsole);
                        plandetail.set("yem_tracktaskconsoleid", id);
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
        }
    }

    /**
     * 设置跟单任务控制台信息
     *
     * @param yem_shippingplan_entry 跟单任务分录
     * @param newbill                跟单任务控制台
     * @param key                    业务分类：整机(Z)、配件(P)
     * @param isckd
     */
    public static void initData(DynamicObject yem_shippingplan_entry, DynamicObject newbill, String key, String isckd) {
        Map yem_plandetail_entry_map = new HashMap();
        Map productsList = new HashMap();
        BigDecimal qty_s = BigDecimal.ZERO;
        //跟单任务明细子分录
        //获取跟单任务明细中的基础机型
        Map yem_productmodelmap = new HashMap();

        DynamicObjectCollection yem_plandetail_entry_s = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");
        for (int i = 0; i < yem_plandetail_entry_s.size(); i++) {
            DynamicObject yem_plandetail_entry = yem_plandetail_entry_s.get(i);
            long yem_srcentryid = yem_plandetail_entry.getLong("yem_srcentryid");
            if (yem_plandetail_entry.getString("yem_businesssort1").equals(key)) {
                yem_plandetail_entry_map.put(yem_srcentryid, yem_plandetail_entry);
            }
            DynamicObject yem_productmodel1 = yem_plandetail_entry.getDynamicObject("yem_productmodel1");
            if (yem_productmodel1 != null) {
                long productid = yem_productmodel1.getLong("id");
                if (yem_productmodelmap.containsKey(productid)) {
                    yem_productmodelmap.put(productid, yem_productmodel1);
                }
            }
        }
        newbill.set("yem_nameplatetype", yem_shippingplan_entry.getString("yem_nameplatetypegd"));
        newbill.set("yem_nameplatelogo", yem_shippingplan_entry.getDynamicObject("yem_nameplatelogogd"));
        newbill.set("yem_nameplateqty", yem_shippingplan_entry.getInt("yem_nameplateqtygd"));
        newbill.set("yem_placemark", yem_shippingplan_entry.getString("yem_placemark"));
        newbill.set("yem_acshipdate", yem_shippingplan_entry.getDate("yem_acshipdate1"));
        newbill.set("yem_lotno", yem_shippingplan_entry.getString("yem_lotno"));
        newbill.set("yem_isckd", isckd);
        if("Z".equals(key)){
            newbill.set("billno", newbill.getString("yem_contractnumber") + "-" + yem_shippingplan_entry.getString("yem_lotno")+ "-ZJ");
        }
        if("P".equals(key)){
            newbill.set("billno", newbill.getString("yem_contractnumber") + "-" + yem_shippingplan_entry.getString("yem_lotno")+ "-PJ");
        }
        //商品明细
        DynamicObjectCollection yem_es_salesorder_r = newbill.getDynamicObjectCollection("yem_es_salesorder_r");
        yem_es_salesorder_r.clear();
        DynamicObjectCollection yem_es_materialinfo_s = newbill.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal yem_thisqty = BigDecimal.ZERO;
        for (int i = 0; i < yem_es_materialinfo_s.size(); i++) {
            DynamicObject yem_es_materialinfo = yem_es_materialinfo_s.get(i);
            long yem_sourceentryid = yem_es_materialinfo.getLong("yem_sourceentryid");
            DynamicObject yem_plandetail_entry = (DynamicObject) yem_plandetail_entry_map.get(yem_sourceentryid);
            if (yem_plandetail_entry != null) {
                yem_thisqty = yem_thisqty.add(yem_plandetail_entry.getBigDecimal("yem_qty2"));
                BigDecimal yem_qty = yem_plandetail_entry.getBigDecimal("yem_qty2");//数量
                BigDecimal yem_baseqty = yem_plandetail_entry.getBigDecimal("yem_baseqty1");//基本数量
                yem_es_materialinfo.set("yem_tracktaskentrryid", yem_plandetail_entry.getLong("id"));//合同跟单明细字单据体id
                yem_es_materialinfo.set("yem_qty", yem_qty);
                yem_es_materialinfo.set("yem_baseqty", yem_baseqty);
                yem_es_materialinfo.set("yem_nqty", yem_qty);
                BigDecimal yem_amt = yem_qty.multiply(yem_es_materialinfo.getBigDecimal("yem_price"));
                yem_es_materialinfo.set("yem_amt", yem_amt);
                yem_es_materialinfo.set("yem_locamt", yem_amt.multiply(newbill.getBigDecimal("yem_exrate")));
                qty_s = BigDecimalUtils.add(qty_s, yem_qty, 10);
                DynamicObject yem_productmodel = yem_es_materialinfo.getDynamicObject("yem_productmodel");
                if (yem_productmodel != null) {
                    DynamicObject yem_products = yem_productmodel.getDynamicObject("yem_products");
                    if (yem_products != null) {
                        long yem_productsid = yem_products.getLong("id");
                        if (!productsList.containsKey(yem_productsid)) {
                            productsList.put(yem_productsid, yem_qty);
                        } else {
                            productsList.replace(yem_productsid, BigDecimalUtils.add(productsList.get(yem_productsid), yem_qty, 10));
                        }
                    }

                }

                if ("Z".equals(key)) {
                    DynamicObjectCollection yem_multiconfig_s = yem_es_materialinfo.getDynamicObjectCollection("yem_multiconfig");
                    for (int j = 0; j < yem_multiconfig_s.size(); j++) {
                        DynamicObject yem_multiconfig = yem_multiconfig_s.get(j);
                        yem_multiconfig.set("yem_unitset", yem_qty);//台数
                    }
                    DynamicObjectCollection yem_retrofitting_s = yem_es_materialinfo.getDynamicObjectCollection("yem_retrofitting");
                    for (int j = 0; j < yem_retrofitting_s.size(); j++) {
                        DynamicObject yem_retrofitting = yem_retrofitting_s.get(j);
                        BigDecimal yem_singleqty = yem_retrofitting.getBigDecimal("yem_singleqty");//单台数量
                        BigDecimal yem_qtyamt = BigDecimalUtils.multiply(yem_singleqty, yem_qty, 10);//总数量
                        yem_retrofitting.set("yem_qty1", yem_qty);
                        yem_retrofitting.set("yem_qtyamt", yem_qtyamt);
                    }
                }
            } else {
                yem_es_materialinfo_s.remove(i--);
            }
        }
        newbill.set("yem_thisqty", yem_thisqty);
        if ("Z".equals(key)) {
            //随机资料及配件工具包
            DynamicObjectCollection yem_es_salesorder_p_s = newbill.getDynamicObjectCollection("yem_es_salesorder_p");
            for (int i = 0; i < yem_es_salesorder_p_s.size(); i++) {
                BigDecimal pcstype = BigDecimal.ZERO;
                DynamicObject yem_es_salesorder_p = yem_es_salesorder_p_s.get(i);
                BigDecimal yem_bicycleqty = yem_es_salesorder_p.getBigDecimal("yem_bicycleqty");//单车数量
                DynamicObject yem_accessorytype = yem_es_salesorder_p.getDynamicObject("yem_accessorytype");
                if (yem_accessorytype != null) {
                    long accessorytype = yem_accessorytype.getLong("id");
                    if (productsList.containsKey(accessorytype)) {
                        pcstype = (BigDecimal) productsList.get(accessorytype);
                    } else {
                        yem_es_salesorder_p_s.remove(i--);
                    }
                }
                BigDecimal yem_acallqty = BigDecimalUtils.multiply(yem_bicycleqty, pcstype, 10);//总数量
                yem_es_salesorder_p.set("yem_acallqty", yem_acallqty);
                yem_es_salesorder_p.set("yem_pcstype", pcstype);//机型台式
            }
        }
    }
}
