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

import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
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.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.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author xwudd
 * @Description
 * @date 16:24
 **/
public class DeliverNoticeNewAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_isaccgift");
        fieldKeys.add("yem_isaccgift");
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            createDebCredNote(dataEntitie);
        }
    }

    /**
     * @description 审核生成贷记单
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/11/10 17:25
     */

    public void createDebCredNote(DynamicObject dataEntitie) {
        boolean isAccGift = dataEntitie.getBoolean("yem_isaccgift");
        String yem_partscredit = "";
        String yem_contractnum = dataEntitie.getString("yem_contractnum");
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("billno", QCP.equals, yem_contractnum));
        DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id,billno,yem_partscredit", new QFilter[]{qFilter});
        if (yem_es_salesorder != null) {
            yem_partscredit = yem_es_salesorder.getString("yem_partscredit");
        }
        if (isAccGift && yem_partscredit.equals("B")) {
            String name = dataEntitie.getDynamicObjectType().getName();
            PushArgs pushArgs = setPushArgs(dataEntitie, "yem_debcrednote", "1815340132866221056");
            ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);
            if (pushResult.isSuccess()) {
                MainEntityType targetMainType = EntityMetadataCache.getDataEntityType("yem_debcrednote");
                List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
                    @Override
                    public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                        BusinessDataReader.loadRefence(objs, dType);
                    }
                }, targetMainType);
                DynamicObject debCredNote = targetBillObjs.get(0);
                debCredNote.set("yem_groupcusfields", debCredNote.getDynamicObject("yem_customer").getDynamicObject("yem_groupcustomers"));
                QFilter qFilter1 = new QFilter("number", QCP.equals, "JDJLX-0002");
                DynamicObject Object = BusinessDataServiceHelper.loadSingle("yem_bd_debcredtype", "id,number,name", qFilter1.toArray());
                debCredNote.set("yem_credittype", Object);
                String debCredNoteNumber = debCredNote.getDynamicObjectType().getName();
                OperationResult save = OperationServiceHelper.executeOperate("save", debCredNoteNumber, new DynamicObject[]{debCredNote}, OperateOption.create());
                if (save.isSuccess()) {
                    OperationResult submit = OperationServiceHelper.executeOperate("submit", debCredNoteNumber, new Object[]{debCredNote.getPkValue()}, OperateOption.create());
                    if (submit.isSuccess()) {
                        OperationResult audit = OperationServiceHelper.executeOperate("audit", debCredNoteNumber, new Object[]{debCredNote.getPkValue()}, OperateOption.create());
                        if (audit.isSuccess()) {

                        } else {
                            List<IOperateInfo> allErrorOrValidateInfo = audit.getAllErrorOrValidateInfo();
                            String message = audit.getMessage();
                            throw new KDBizException("审核关联生成的贷记单失败," + message + "，" + allErrorOrValidateInfo);
                        }
                    } else {
                        List<IOperateInfo> allErrorOrValidateInfo = submit.getAllErrorOrValidateInfo();
                        String message = submit.getMessage();
                        throw new KDBizException("提交关联生成的贷记单失败," + message + "，" + allErrorOrValidateInfo);
                    }
                } else {
                    List<IOperateInfo> allErrorOrValidateInfo = save.getAllErrorOrValidateInfo();
                    String message = save.getMessage();
                    throw new KDBizException("保存关联生成的贷记单失败," + message + "，" + allErrorOrValidateInfo);
                }
            }
        }
    }

    public PushArgs setPushArgs(DynamicObject dataEntitie, String targetNumber, String ruleId) {
        String name = dataEntitie.getDynamicObjectType().getName();
        PushArgs pushArgs = new PushArgs();
        pushArgs.setSourceEntityNumber(name);
        pushArgs.setTargetEntityNumber(targetNumber);
        pushArgs.setRuleId(ruleId);
        pushArgs.setHasRight(true);
        pushArgs.setBuildConvReport(true);
        List<ListSelectedRow> selectedRows = new ArrayList<>();
        ListSelectedRow srcBill1 = new ListSelectedRow(dataEntitie.getPkValue());
        selectedRows.add(srcBill1);
        pushArgs.setSelectedRows(selectedRows);
        return pushArgs;
    }
}
