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

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.yem.wm.es.salesorder.validator.SaleOrderDelValidator;
import com.yem.wm.im.debcrednotenew.utils.DebCredUtils;
import com.yem.wm.im.debcrednotenew.validator.DebCredNewAuditValidatorOp;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouc
 * @date 2024/3/28 10:21
 * @className DebCredNewAuditPlugin
 * @description 贷记单审核(新)服务插件
 */
public class DebCredNewAuditPlugin extends AbstractOperationServicePlugIn {
    private static final Log log = LogFactory.getLog(DebCredNewAuditPlugin.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_groupcusfields");
    }

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

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        DynamicObject[] dataEnties = e.getDataEntities();
        for (DynamicObject temp : dataEnties) {
            temp = BusinessDataServiceHelper.loadSingle(temp.getPkValue(), temp.getDynamicObjectType().getName());
            String billtype = temp.getString("yem_billtype.number");
            DynamicObject yemCurrency = temp.getDynamicObject("yem_currency");
            if (yemCurrency !=null){
                String yemCurrencyString = yemCurrency.getString("number");
                BigDecimal yemLastusdamt = temp.getBigDecimal("yem_lastusdamt");//上次美元金额
                BigDecimal yemAmount = temp.getBigDecimal("yem_amount");//配件资金池增加金额
                BigDecimal yemAmountSub = temp.getBigDecimal("yem_amount_sub");//配件资金池扣减金额
                BigDecimal yemLastrmbamt = temp.getBigDecimal("yem_lastrmbamt");//上次人民币金额
                if ("USD".equals(yemCurrencyString)){
                    BigDecimal yem_remainingusdamount = yemLastusdamt.add(yemAmount).subtract(yemAmountSub);
                    temp.set("yem_remainingusdamount",yem_remainingusdamount);
                    temp.set("yem_remainingamount",yemLastrmbamt);
                }else if ("CNY".equals(yemCurrencyString)){
                    BigDecimal yem_remainingusdamount = yemLastrmbamt.add(yemAmount).subtract(yemAmountSub);
                    temp.set("yem_remainingusdamount",yemLastusdamt);
                    temp.set("yem_remainingamount",yem_remainingusdamount);
                }
            }
            long yem_spcapitalpoolid = temp.getLong("yem_spcapitalpoolid");//配件资金池id
            if (yem_spcapitalpoolid > 0) {
                return;
            }
            DynamicObject yem_groupcusfields = temp.getDynamicObject("yem_groupcusfields");
            DynamicObject products = temp.getDynamicObject("yem_bd_products");
            DynamicObject org = temp.getDynamicObject("org");
            if (yem_groupcusfields != null && products != null) {
                DynamicObjectCollection creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
                List<QFilter> list = new ArrayList<>();
                list.add(new QFilter("yem_customer.id", QCP.equals, yem_groupcusfields.getLong("id")));
                list.add(new QFilter("billstatus", QCP.equals, "C"));
                list.add(new QFilter("yem_bd_products.id", QCP.equals, products.getPkValue()));
                list.add(new QFilter("org.id", QCP.equals, org.getPkValue()));
                DynamicObject loadColl = BusinessDataServiceHelper.loadSingle("yem_spcapitalpool", "yem_spcapitalpool_o.yem_origintype", list.toArray(new QFilter[0]));
                if (loadColl != null) {
                    loadColl = BusinessDataServiceHelper.loadSingle(loadColl.getPkValue(), loadColl.getDynamicObjectType().getName());
                    DynamicObject object = null;
                    if (billtype.equals("yem_debcrednote_a")) {
                        object = DebCredUtils.Updatespcapitalpool_Adjust(temp, loadColl);
                    } else {
                        object = DebCredUtils.Updatespcapitalpool(temp, loadColl);
                    }
                    OperationResult Operate = OperationServiceHelper.executeOperate("save", object.getDynamicObjectType().getName(), new DynamicObject[]{object}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        DebCredUtils.updatespcapitalpool(temp, object);
                    } else {
                        String message = Operate.getMessage();
                        List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                        throw new KDBizException(String.format("《配件资金池》保存失败！，%s，%s", message, allErrorOrValidateInfo));
                    }
                } else {
                    DynamicObject addspcapitalpool = null;
                    if (billtype.equals("yem_debcrednote_a")) {

                    } else {
                        addspcapitalpool = DebCredUtils.Addspcapitalpool(temp);
                    }
                    OperationResult Operate = OperationServiceHelper.executeOperate("save", addspcapitalpool.getDynamicObjectType().getName(), new DynamicObject[]{addspcapitalpool}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        OperationResult submitResult = OperationServiceHelper.executeOperate("submit", addspcapitalpool.getDynamicObjectType().getName(), new Object[]{addspcapitalpool.getPkValue()}, OperateOption.create());
                        if (submitResult.isSuccess()) {
                            OperationResult auditResult = OperationServiceHelper.executeOperate("audit", addspcapitalpool.getDynamicObjectType().getName(), new Object[]{addspcapitalpool.getPkValue()}, OperateOption.create());
//                                OperationResult auditResult = OperationServiceHelper.executeOperate("zyestimated", addspcapitalpool.getDynamicObjectType().getName(), new Object[]{addspcapitalpool.getPkValue()}, OperateOption.create());
                            if (auditResult.isSuccess()) {
                                DebCredUtils.updatespcapitalpool(temp, addspcapitalpool);
                            } else {
                                List<IOperateInfo> allErrorOrValidateInfo = auditResult.getAllErrorOrValidateInfo();
                                String message = auditResult.getMessage();
                                throw new KDBizException("《配件资金池》审核失败，" + message + "，" + allErrorOrValidateInfo);
                            }
                        } else {
                            List<IOperateInfo> allErrorOrValidateInfo = submitResult.getAllErrorOrValidateInfo();
                            String message = submitResult.getMessage();
                            throw new KDBizException("《配件资金池》提交失败，" + message + "，" + allErrorOrValidateInfo);
                        }

                    } else {
                        String message = Operate.getMessage();
                        List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                        throw new KDBizException(String.format("《配件资金池》保存失败！，%s，%s", message, allErrorOrValidateInfo));
                    }
                }
            }
            //反写收款单、销售出库单
            backwriting(temp);
        }
    }

    /**
     * 反写收款单、销售出库单
     *
     * @param temp
     */
    public void backwriting(DynamicObject temp) {
        String yem_partscredit = temp.getString("yem_partscredit");
        if (yem_partscredit.equals("B")) {
            //更新销售出库单
            QFilter qFilter3 = new QFilter("billno", QCP.equals, temp.getString("yem_source"));
            DynamicObject yem_es_delivernotice = BusinessDataServiceHelper.loadSingle("yem_es_delivernotice", "id", qFilter3.toArray());
            if (yem_es_delivernotice != null) {
                DynamicObject object = BusinessDataServiceHelper.loadSingle(yem_es_delivernotice.getPkValue(), yem_es_delivernotice.getDynamicObjectType().getName());
                object.set("yem_debcreditid", temp.getString("id"));
                object.set("yem_debcreditno", temp.getString("billno"));
                SaveServiceHelper.update(new DynamicObject[]{object});
            }
        }
        //全额收款
        if (yem_partscredit.equals("C")) {
            //更新销售出库单
            //来源合同号
            String yem_sourcebillno = temp.getString("yem_sourcebillno");
            QFilter qFilter3 = new QFilter("yem_receiptdetail.yem_claimdetail.yem_salcontractno.billno", QCP.equals, yem_sourcebillno);
            DynamicObject[] yem_es_delivernotice = BusinessDataServiceHelper.load("yem_gathering", "id", qFilter3.toArray());
            if (yem_es_delivernotice.length > 0) {
                for (int i = 0; i < yem_es_delivernotice.length; i++) {
                    DynamicObject dynamicObject = yem_es_delivernotice[i];
                    DynamicObject object = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                    if (object != null) {
                        DynamicObjectCollection yem_receiptdetail = object.getDynamicObjectCollection("yem_receiptdetail");
                        for (int j = 0; j < yem_receiptdetail.size(); j++) {
                            DynamicObject dynamicObject1 = yem_receiptdetail.get(j);
                            DynamicObjectCollection yem_claimdetail = dynamicObject1.getDynamicObjectCollection("yem_claimdetail");
                            for (DynamicObject claimdetail : yem_claimdetail) {
                                DynamicObject yem_salcontractno = claimdetail.getDynamicObject("yem_salcontractno");
                                if (yem_salcontractno != null) {
                                    if (yem_sourcebillno.equals(yem_salcontractno.getString("billno"))) {
                                        claimdetail.set("yem_creditslipid", temp.getString("id"));
                                        claimdetail.set("yem_creditslipno", temp.getString("billno"));
                                    }
                                }
                            }
                        }
                    }
                    SaveServiceHelper.update(new DynamicObject[]{object});
                }
            }
        }
    }
}
