package com.yem.wm.es.exportpresent.op;

import com.yem.wm.es.exportpresent.validator.ExportPresentSubmitValidator;
import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;

import static com.yem.wm.es.contractamtlist.util.FunUtil.getPayBills;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getShipBills;

/**
 * @Description 寄单放单申请提交
 * @Date 2024/1/31 10:28
 * @Created by ZZSLL
 */

public class ExportPresentSubmitOp extends AbstractOperationServicePlugIn
{
    @Override
    public void onAddValidators(AddValidatorsEventArgs e)
    {
        super.onAddValidators(e);
        e.addValidator(new ExportPresentSubmitValidator());
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e)
    {
        super.endOperationTransaction(e);
        DynamicObject[] eDataEntities = e.getDataEntities();
        String operationKey = e.getOperationKey();
        if ("submit".equals(operationKey)) {
            for (DynamicObject dataEntity : eDataEntities) {
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_exportpre_erf");
                for (DynamicObject dynamicObject : collection) {
                    DynamicObject saleOrder = dynamicObject.getDynamicObject("yem_saleorder");
                    if (saleOrder == null) continue;
                    DynamicObject shipDetail = dynamicObject.getDynamicObject("yem_shipbill");
                    if (shipDetail == null) continue;
                    shipDetail = BusinessDataServiceHelper.loadSingle(shipDetail.getPkValue(), shipDetail.getDataEntityType().getName());
                    saleOrder = BusinessDataServiceHelper.loadSingle(saleOrder.getPkValue(), saleOrder.getDataEntityType().getName());
                    DynamicObject[] shipBills = getShipBills(saleOrder, dataEntity, "A");//出运
                    DynamicObject[] payBills = getPayBills(saleOrder, dataEntity, "B");//收款单

                    BigDecimal thisRealityAmt = PaymentControlUtil.getThisRealityAmt(saleOrder, shipBills, payBills, shipDetail);
                    dynamicObject.set("yem_debtamt", thisRealityAmt.setScale(2, RoundingMode.HALF_UP));
                }
            }
            SaveServiceHelper.save(eDataEntities);
        }
    }
}
