package com.yem.wm.utils;


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.datamodel.IRefrencedataProvider;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.OperationResult;
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.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;


public class IABudgetCommon {

    /**
     * 外销合同下推生成内审预算单
     */
    public static void pushToGeneration(DynamicObject dataEntity, int[] selectRows, String entryKey) {
        deleteExistIAData(dataEntity, selectRows, entryKey);
        String billtype = dataEntity.getString("yem_billtype.number");
        // 整机按照单据头下推
        // 配件按照分录下推
        String from = dataEntity.getDataEntityType().getName();
        String to = "yem_im_intauditbusa";
        Long id = dataEntity.getLong("id");
        String ruleId = "";
        List<ListSelectedRow> selectedRows = new ArrayList<>();

        // 内贸整机合同 || 外贸整机合同
//        if ("yem_es_salesorder_nmzj".equals(billtype) || "yem_es_salesorder_ZJ".equals(billtype)) {
        if (StringUtils.containsIgnoreCase(billtype, "salesorder") && StringUtils.containsIgnoreCase(billtype, "zj")) {
            ruleId = "1934363427698911232";//外销合同 >> 内审预算单（整机）
            if (StringUtils.containsIgnoreCase(billtype, "x")) {//变更单
                ruleId = "1995630519982761984";//（yem）外销合同变更单 >> 内审预算单（整机）
            }
            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection(entryKey);
            for (int selectRowId : selectRows) {
                DynamicObject object = materialinfo.get(selectRowId);
                ListSelectedRow srcBillRows = new ListSelectedRow(id);
                srcBillRows.setEntryPrimaryKeyValue(object.getPkValue());
                srcBillRows.setEntryEntityKey(entryKey);
                selectedRows.add(srcBillRows);
            }
        }

        // 内贸配件合同 || 外贸配件合同
//        if ("yem_es_salesorder_nmpj".equals(billtype) || "yem_es_salesorder_PJ".equals(billtype)) {
        if (StringUtils.containsIgnoreCase(billtype, "salesorder") && StringUtils.containsIgnoreCase(billtype, "pj")) {
            ruleId = "1934358354914736128";//外销合同 >> 内审预算单（配件）
            if (StringUtils.containsIgnoreCase(billtype, "x")) {
                ruleId = "1995638449608075264";//（yem）外销合同变更单 >> 内审预算单（配件）
            }
            ListSelectedRow srcBillRows = new ListSelectedRow(id);
            selectedRows.add(srcBillRows);
        }

        // 外贸客户需求单-配件 || 内贸客户需求单-配件
        if ("yem_im_inclientdema_pj".equals(billtype) || "yem_im_clientdema_pj".equals(billtype)) {
            ruleId = "1936311988980316160";
            ListSelectedRow srcBillRows = new ListSelectedRow(id);
            selectedRows.add(srcBillRows);
        }

        // 外贸客户需求单-整机 || 内贸客户需求单-整机
        if ("yem_im_inclientdeman_zj".equals(billtype) || "yem_im_clientdeman_zj".equals(billtype)) {
            ruleId = "1936312822665345024";
            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection(entryKey);
            for (int selectRowId : selectRows) {
                DynamicObject object = materialinfo.get(selectRowId);
                ListSelectedRow srcBillRows = new ListSelectedRow(id);
                srcBillRows.setEntryPrimaryKeyValue(object.getPkValue());
                srcBillRows.setEntryEntityKey(entryKey);
                selectedRows.add(srcBillRows);
            }
        }

        PushArgs pushArgs = new PushArgs();
        pushArgs.setSourceEntityNumber(from);        // 必选，源单标识
        pushArgs.setTargetEntityNumber(to);          // 必选，目标单标识
        pushArgs.setHasRight(false);                 // 可选，传入true，不检查目标单新增权
        pushArgs.setRuleId(ruleId);                  // 可选，传入本次下推使用的转换规则id；传入空值，由系统自动寻找合适的转换规则
        pushArgs.setBuildConvReport(true);           // 是否输出详细错误报告
        pushArgs.setSelectedRows(selectedRows);      // 必选，设置需要下推的源单及分录内码

        ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);
        if (pushResult.isSuccess()) {
            // 获取生成的目标单数据包
            MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(to);
            List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
                @Override
                public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                    BusinessDataReader.loadRefence(objs, dType);
                }
            }, targetMainType);
            // 设置保存参数，调用目标单保存服务，保存目标单（保存时自动反写源单）
            OperateOption saveOption = OperateOption.create();
            saveOption.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true));    // 不执行警告级别校验器
            saveOption.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true));    // 不显示交互提示，自动执行到底
            saveOption.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(true));        // 全部校验通过才保存
            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection(entryKey);
            for (DynamicObject target : targetBillObjs) {
                int index = targetBillObjs.indexOf(target);
                OperationResult saveResult = SaveServiceHelper.saveOperate(to, new DynamicObject[]{target}, saveOption);
                // 判断保存结果
                if (!saveResult.isSuccess()) {
                    throw new KDBizException("生成的内审预算单保存失败：" + saveResult.getMessage());
                } else {
                    String IAno = target.getString("billno");
                    long IAid = target.getLong("id");
                    for (DynamicObject object : materialinfo) {
                        int idx = materialinfo.indexOf(object);
                        if (idx == selectRows[index]) {
                            object.set("yem_intauditbusano", IAno);
                            object.set("yem_intauditbusaid", IAid);
                            if ("yem_es_salesorder_nmzj".equals(billtype) || "yem_es_salesorder_ZJ".equals(billtype) || "yem_im_inclientdeman_zj".equals(billtype) || "yem_im_clientdeman_zj".equals(billtype)) {
                                bingEntryConfigInfo(target, object);
                                SaveServiceHelper.save(new DynamicObject[]{target});
                            }
                        }
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
        } else {
            String message = pushResult.getMessage();
            throw new KDBizException("下推失败：" + message);
        }
    }

    private static void bingEntryConfigInfo(DynamicObject target, DynamicObject object) {
        // 外销合同-多功能配置
        DynamicObjectCollection multiconfig = object.getDynamicObjectCollection("yem_multiconfig");
        // 内审预算-订单配置要求
        DynamicObjectCollection intauditbusa = target.getDynamicObjectCollection("yem_im_intauditbusa_b");
        for (DynamicObject dynamicObject : multiconfig) {
            DynamicObject add = intauditbusa.addNew();
            // 配置类型
            add.set("yem_configurtype", dynamicObject.get("yem_configurtype"));
            // 配置名称
            add.set("yem_configurname", dynamicObject.get("yem_configurname"));
            // 标准销售加价（结算币别）
            add.set("yem_marketraiseprice", dynamicObject.get("yem_marketraiseprice"));
            // 单台数量
            add.set("yem_unitsetnumber", dynamicObject.get("yem_unitsetnumber"));
            // 单台加价金额（结算币别）
            add.set("yem_unitsetamount", dynamicObject.get("yem_unitsetamount"));
            // 单台加价金额（本位币）
            add.set("yem_unitsetamountbase", dynamicObject.get("yem_unitsetamountbase"));
        }
    }

    private static void deleteExistIAData(DynamicObject dataEntity, int[] selectRows, String entryKey) {
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection(entryKey);
        for (int selectRowId : selectRows) {
            DynamicObject object = materialinfo.get(selectRowId);
            Object objId = object.get("yem_intauditbusaid");
            if (YEM.isEmpty(objId)) continue;
            Long id = (Long) objId;
            DynamicObject IA = BusinessDataServiceHelper.loadSingle("yem_im_intauditbusa", "id, billno, billstatus", new QFilter[]{new QFilter("id", QCP.equals, id)});
            if (YEM.isEmpty(IA)) continue;
            String billstatus = IA.getString("billstatus");
            String billno = IA.getString("billno");
            OperateOption option = YEM.getOption();
            if ("C".equals(billstatus)) {
                OperationResult unaudit = OperationServiceHelper.executeOperate("unaudit", "yem_im_intauditbusa", new Object[]{id}, option);
                if (unaudit.isSuccess()) {
                    OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_im_intauditbusa", new Object[]{id}, option);
                    if (!delete.isSuccess()) {
                        throw new KDBizException(String.format("删除内审预算单 [ %s ] 失败，原因：[ %s ]，请手动删除后重新生成！", billno, delete.getMessage()));
                    }
                } else {
                    throw new KDBizException(String.format("反审核内审预算单 [ %s ] 失败，原因：[ %s ]，请手动反审核删除后重新生成！", billno, unaudit.getMessage()));
                }
            }
            if ("B".equals(billstatus)) {
                OperationResult unsubmit = OperationServiceHelper.executeOperate("unsubmit", "yem_im_intauditbusa", new Object[]{id}, option);
                if (unsubmit.isSuccess()) {
                    OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_im_intauditbusa", new Object[]{id}, option);
                    if (!delete.isSuccess()) {
                        throw new KDBizException(String.format("删除内审预算单 [ %s ] 失败，原因：[ %s ]，请手动删除后重新生成！", billno, delete.getMessage()));
                    }
                } else {
                    throw new KDBizException(String.format("撤销内审预算单 [ %s ] 失败，原因：[ %s ]，请手动撤销删除后重新生成！", billno, unsubmit.getMessage()));
                }
            }
            if ("A".equals(billstatus)) {
                OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_im_intauditbusa", new Object[]{id}, option);
                if (!delete.isSuccess()) {
                    throw new KDBizException(String.format("删除内审预算单 [ %s ] 失败，原因：[ %s ]，请手动删除后重新生成！", billno, delete.getMessage()));
                }
            }
        }
    }
}
