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

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.validate.AbstractValidator;
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 TODO
 * @Date 2024/1/31 10:29
 * @Created by ZZSLL
 */

public class ExportPresentSubmitValidator extends AbstractValidator
{
    @Override
    public void validate()
    {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity data : dataEntities) {
            DynamicObject dataEntity = data.getDataEntity();
            // 款项类型
            String paymenttype = dataEntity.getString("yem_paymenttype");
            if ("A".equals(paymenttype)) {
                arrearsVerification(dataEntity, data);
            }
        }
    }

    private void arrearsVerification(DynamicObject dataEntity, ExtendedDataEntity data)
    {
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_exportpre_erf");
        StringBuilder sb = new StringBuilder();
        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);
            if (thisRealityAmt.abs().compareTo(new BigDecimal("0.1")) > 0) {
                sb.append(String.format("单号为 [ %s ] 的发运明细单下有欠款，欠款金额为 [ %s ], 请核对后提交！", shipDetail.getString("billno"), thisRealityAmt.setScale(2, RoundingMode.HALF_UP)));
            }

            dynamicObject.set("yem_debtamt", thisRealityAmt.setScale(2, RoundingMode.HALF_UP));
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});

        }
        if (sb.length() > 0) {
            this.addErrorMessage(data, String.valueOf(sb));
        }
    }
}
