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


import com.yem.em.utils.AtlasUtils;
import com.yem.wm.utils.StringUtils;
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.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.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.List;

/**
 * @author zhouc
 * @date 2023/8/30 11:27
 * @className BomChangeAuditEdit
 * @description BOM变更单【反审核】服务插件
 */
public class BomChangeUnAuditEdit 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");
    }

    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        if (e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            for (DynamicObject bill : bills) {
                String id = bill.getString("id");
                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) {
                            DeleteSetsubstitution(bill, entryentity, "yem_em_substitution");
                        }
                        //资源
                        boolean yem_isresource = entryentity.getBoolean("yem_isresource");
                        if (yem_isresource) {
                            DeleteSetsubstitution(bill, entryentity, "yem_em_compsub");
                        }
                    }
                }
            }
        }
    }

    /**
     * 删除生成替换关系
     *
     * @param bill        表头数据包
     * @param entryentity 分录行数据包
     * @param entityName  单据标识
     */
    public static void DeleteSetsubstitution(DynamicObject bill, DynamicObject entryentity, String entityName) {
        //1.根据单据id获取
        QFilter qFilter = new QFilter("yem_entryentity.yem_trackingid", QCP.equals, bill.getString("id"));//替换零件编码
        qFilter.and(new QFilter("yem_parentno", QCP.equals, entryentity.getString("yem_parentno")));
        DynamicObject[] yem_em_substitution = BusinessDataServiceHelper.load("yem_em_substitution", "id"
                , new QFilter[]{qFilter}, null);
        if (yem_em_substitution.length > 0) {
            for (int i = 0; i < yem_em_substitution.length; i++) {
                DynamicObject substitution = yem_em_substitution[i];
                DynamicObject component = BusinessDataServiceHelper.loadSingle(substitution.getLong("id"), entityName);
                if (component != null) {
                    DynamicObjectCollection yemEntryentity = component.getDynamicObjectCollection("yem_entryentity");
                    if (yemEntryentity.size() > 0) {
                        if (yemEntryentity.size() == 1) {
                            //反审核
                            OperationResult unAudit = OperationServiceHelper.executeOperate("unaudit", entityName, new Object[]{substitution.getLong("id")}, OperateOption.create());
                            if (unAudit.isSuccess()) {
                                OperationResult delete = OperationServiceHelper.executeOperate("delete", entityName, new Object[]{substitution.getLong("id")}, OperateOption.create());
                                if (!delete.isSuccess()) {
                                    String message = delete.getMessage();
                                    List<IOperateInfo> allErrorOrValidateInfo = delete.getAllErrorOrValidateInfo();
                                    throw new KDBizException(String.format("《替换关系》删除失败，%s，%s", message, allErrorOrValidateInfo));
                                }
                            } else {
                                String message = unAudit.getMessage();
                                List<IOperateInfo> allErrorOrValidateInfo = unAudit.getAllErrorOrValidateInfo();
                                throw new KDBizException(String.format("《替换关系》删除失败，%s，%s", message, allErrorOrValidateInfo));
                            }
                        } else {
                            for (int j = 0; j < yemEntryentity.size(); j++) {
                                DynamicObject dynamicObject = yemEntryentity.get(j);
                                String yem_trackingid = dynamicObject.getString("yem_trackingid");
                                if (yem_trackingid.equals(bill.getString("id"))) {
                                    yemEntryentity.remove(j--);
                                    break;
                                }
                            }
                            //更改表头替换件信息
                            component.set("yem_tnumber", entryentity.getString("yem_subno"));
                            component.set("yem_tname", entryentity.getString("yem_enablesubenname"));
                            component.set("yem_tenname", entryentity.getString("yem_subenname"));
                            component.set("yem_tqty", entryentity.getBigDecimal("yem_qty"));
                        }
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                component.getDynamicObjectType().getName(),
                                new DynamicObject[]{component}, OperateOption.create());
                        if (Operate.isSuccess()) {
                            //更新产品资源明细是否替换
                            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);
                        }
                    }
//                    SaveServiceHelper.save(new DynamicObject[]{component});
                }
            }
        }
    }
}
