package com.yem.em.bd.bomchange.op;

import com.yem.em.bd.bomchange.validator.BomChangeAuditvalidatorEdit;
import com.yem.em.utils.AtlasUtils;
import com.yem.wm.im.tracktaskconsole.validator.TracktaskconsoleSubmitvalidator;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
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.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.*;

/**
 * @author zhouc
 * @date 2023/8/30 11:27
 * @className BomChangeAuditEdit
 * @description BOM变更单【审核】服务插件
 */
public class BomChangeAuditEdit extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("createorg");
        keys.add("number");
        keys.add("yem_entryentity.yem_subno");
        keys.add("yem_entryentity.yem_subname");
        keys.add("yem_entryentity.yem_replace");
        keys.add("yem_entryentity.yem_qty");
        keys.add("yem_entryentity.yem_enablesubno");
        keys.add("yem_entryentity.yem_enablesubname");
        keys.add("yem_entryentity.yem_enablesubqty");
        keys.add("yem_entryentity.yem_subname");
        keys.add("yem_entryentity.yem_enablesta");
        keys.add("yem_entryentity.yem_isass");
        keys.add("yem_entryentity.yem_isresource");
        keys.add("yem_entryentity.yem_parentno");
        keys.add("yem_entryentity.yem_parentname");
        keys.add("yem_entryentity.yem_enableddate");
        keys.add("yem_entryentity.yem_downdate");
        keys.add("yem_entryentity.yem_subenname");
        keys.add("yem_entryentity.yem_enablesubenname");
    }

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

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        if (e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            for (DynamicObject bill : bills) {
                DynamicObjectCollection yem_entryentity = bill.getDynamicObjectCollection("yem_entryentity");
                for (int i = 0; i < yem_entryentity.size(); i++) {
                    DynamicObject entryentity = yem_entryentity.get(i);
                    String yem_enablesta = entryentity.getString("yem_enablesta");
                    String yem_enablesubno = entryentity.getString("yem_enablesubno");
                    if (yem_enablesta.equals("B") && StringUtils.isNotEmpty(yem_enablesubno)) {
                        //部件
                        boolean yem_isass = entryentity.getBoolean("yem_isass");
                        if (yem_isass) {
                            Setsubstitution(bill, entryentity, "yem_em_substitution");
                        }
                        //资源
                        boolean yem_isresource = entryentity.getBoolean("yem_isresource");
                        if (yem_isresource) {
                            Setsubstitution(bill, entryentity, "yem_em_compsub");
                        }
                    }
                }
                SetEnName(bill);
            }
        }
    }


    /**
     * 创建替换单据
     *
     * @param bill        表头数据包
     * @param entryentity 分录行数据包
     * @param entityName  单据标识
     */
    public void Setsubstitution(DynamicObject bill, DynamicObject entryentity, String entityName) {
        DynamicObject billObj = BusinessDataServiceHelper.newDynamicObject(entityName);
        billObj.set("createorg", bill.getDynamicObject("createorg"));
        billObj.set("enable", "1");
        billObj.set("status", "C");
//        billObj.set("number", entryentity.getString("yem_subno"));
//        billObj.set("name", entryentity.getString("yem_subname"));
        //yem_parentname
        billObj.set("number", entryentity.getString("yem_parentno"));
        billObj.set("name", entryentity.getString("yem_parentname"));
        billObj.set("yem_replace1", entryentity.getString("yem_replace"));
        billObj.set("creator", YEM.getCurrentUserId());
        billObj.set("yem_sourcetype", "BOM");
        billObj.set("yem_parentno", entryentity.getString("yem_parentno"));
        //原零件信息
        billObj.set("yem_pnumber", entryentity.getString("yem_subno"));
        billObj.set("yem_pname", entryentity.getString("yem_subname"));
        billObj.set("yem_penname", entryentity.getString("yem_subenname"));
        billObj.set("yem_pqty", entryentity.getBigDecimal("yem_qty"));
        //替换件信息
        billObj.set("yem_tnumber", entryentity.getString("yem_enablesubno"));
        billObj.set("yem_tname", entryentity.getString("yem_enablesubname"));
        billObj.set("yem_tenname", entryentity.getString("yem_enablesubname"));
        billObj.set("yem_tqty", entryentity.getString("yem_enablesubqty"));
        //明细信息
        DynamicObjectCollection yem_entryentity = billObj.getDynamicObjectCollection("yem_entryentity");
        DynamicObject subentryentity = yem_entryentity.addNew();
        //原零件信息
        subentryentity.set("yem_onumber", entryentity.getString("yem_subno"));
        subentryentity.set("yem_oname", entryentity.getString("yem_enablesubenname"));
        subentryentity.set("yem_oenname", entryentity.getString("yem_subenname"));
        subentryentity.set("yem_oqty", entryentity.getBigDecimal("yem_qty"));
        //替换件信息
        subentryentity.set("yem_repnumber", entryentity.getString("yem_enablesubno"));
        subentryentity.set("yem_repname", entryentity.getString("yem_enablesubname"));
        subentryentity.set("yem_repenname", entryentity.getString("yem_enablesubenname"));
        subentryentity.set("yem_repenqty", entryentity.getString("yem_enablesubqty"));
        subentryentity.set("yem_replace", entryentity.getString("yem_replace"));
        subentryentity.set("yem_replacedate", new Date());
        subentryentity.set("yem_technology", new Date());
        subentryentity.set("yem_operator", YEM.getCurrentUserId());
        subentryentity.set("yem_trackingno", bill.getString("number"));
        subentryentity.set("yem_trackingid", bill.getPkValue());
        subentryentity.set("yem_completetime", entryentity.getDate("yem_completetime"));
        subentryentity.set("yem_statedate", entryentity.getDate("yem_enableddate"));
        subentryentity.set("yem_downdate", entryentity.getDate("yem_downdate"));
        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                billObj.getDynamicObjectType().getName(),
                new DynamicObject[]{billObj}, OperateOption.create());
        if (Operate.isSuccess()) {
            //根据子件编码查询替换关系
            AtlasUtils.Selectsubstitution(entryentity.getString("yem_subno"), bill, entryentity, "Entry", entityName);
            //更新产品资源明细是否替换
            boolean yem_isass = entryentity.getBoolean("yem_isass");
            if (yem_isass) {
                AtlasUtils.Upassatlasdet(bill,entryentity,"Audit");
            }
        } else {
            List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
            String message = Operate.getMessage();
            throw new KDBizException("保存《替换关系》失败，失败信息为：," + message + "，" + allErrorOrValidateInfo);
        }
    }

    /**
     * 根据编码获取英文名称
     *
     * @param bill
     */
    public void SetEnName(DynamicObject bill) {
        List asslist = new ArrayList<>();
        List resource = new ArrayList<>();
        DynamicObjectCollection yem_entryentity = bill.getDynamicObjectCollection("yem_entryentity");
        for (int i = 0; i < yem_entryentity.size(); i++) {
            DynamicObject entryentity = yem_entryentity.get(i);
            String yem_enablesta = entryentity.getString("yem_subno");
            String yem_enablesubno = entryentity.getString("yem_enablesubno");
            //部件
            boolean yem_isass = entryentity.getBoolean("yem_isass");
            if (yem_isass) {
                asslist.add(yem_enablesta);
                asslist.add(yem_enablesubno);
            }
            //资源
            boolean yem_isresource = entryentity.getBoolean("yem_isresource");
            if (yem_isresource) {
                resource.add(yem_enablesta);
                resource.add(yem_enablesubno);
            }
        }
        DynamicObjectCollection yem_em_assatlasdet = null;
        QFilter filter = new QFilter("status", QCP.not_equals, null);
        //查询分录总成
        if (asslist.size() > 0) {
            filter.and(new QFilter("yem_entryentity.yem_partnumber", QCP.in, asslist));
            yem_em_assatlasdet = QueryServiceHelper.query("yem_em_assatlasdet",
                    "id,yem_entryentity.yem_partenname yem_enname,yem_entryentity.yem_partnumber number"
                    , new QFilter[]{filter}, null);
        }
        //查询表头总成
        if (resource.size() > 0) {
            filter.and(new QFilter("number", QCP.in, resource));
            yem_em_assatlasdet = QueryServiceHelper.query("yem_em_assatlasdet", "id,name,number,yem_enname"
                    , new QFilter[]{filter}, null);
        }

        if (yem_em_assatlasdet != null) {
            Map map = new HashMap<>();
            for (int i = 0; i < yem_em_assatlasdet.size(); i++) {
                DynamicObject dynamicObject = yem_em_assatlasdet.get(i);
                map.put(dynamicObject.getString("number"), dynamicObject.getString("yem_enname"));
            }
            if (map.size() > 0) {
                for (int i = 0; i < yem_entryentity.size(); i++) {
                    DynamicObject entryentity = yem_entryentity.get(i);
                    String yem_enablesta = entryentity.getString("yem_subno");
                    String yem_enablesubno = entryentity.getString("yem_enablesubno");
                    if (map.containsKey(yem_enablesta)) {
                        entryentity.set("yem_subenname", map.get(yem_enablesta));
                    }
                    if (map.containsKey(yem_enablesubno)) {
                        entryentity.set("yem_enablesubenname", map.get(yem_enablesubno));
                    }
                }
                OperationResult Operate = OperationServiceHelper.executeOperate("save",
                        bill.getDynamicObjectType().getName(),
                        new DynamicObject[]{bill}, OperateOption.create());
                if (Operate.isSuccess()) {

                }
            }
        }
    }
}
