package com.yem.wm.fm.gathering.validator;

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.YEM;
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 java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xwudd
 * @Description
 * @date 11:49
 **/
public class CreatePlusMinusValidator extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for(ExtendedDataEntity dataEntitie : dataEntities){
            DynamicObject dataEntity = dataEntitie.getDataEntity();
            Set<Long> ids = new HashSet<>();
            DynamicObjectCollection receiptDetails = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
            for (int i = 0; i < receiptDetails.size(); i++) {
                DynamicObject receiptDetail = receiptDetails.get(i);
                DynamicObjectCollection claimDetails = receiptDetail.getDynamicObjectCollection("yem_claimdetail");
                for (int j = 0; j < claimDetails.size(); j++) {
                    DynamicObject claimDetail = claimDetails.get(j);
                    DynamicObject salContract = claimDetail.getDynamicObject("yem_salcontractno");
                    if(YEM.isNotEmpty(salContract)){
                        ids.add(salContract.getLong("id"));
                    }
                }
            }
            for(Long id : ids){
                DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle(id,"yem_es_salesorder");
                String billNo = salesOrder.getString("billno");
                BigDecimal rapRate = PaymentControlUtil.getRapRate(salesOrder);
                BigDecimal collection = PaymentControlUtil.getCollection(salesOrder,dataEntity.getLong("id"));//该合同全部认领金额
                BigDecimal contractPayment = PaymentControlUtil.getAdvancePayment(PaymentControlUtil.getContractPayment(salesOrder),rapRate);
                BigDecimal allDeliverPayment = PaymentControlUtil.getBalancePayment(PaymentControlUtil.getAllDeliverPayment(salesOrder.getDynamicObjectType().getName(), id),rapRate);
                if(collection.subtract(contractPayment).subtract(allDeliverPayment).compareTo(BigDecimal.ZERO) < 0){
                    this.addErrorMessage(dataEntitie,String.format("外销合同号%s如果进行收款调整，则不满足已发货金额，请调整数据之后进行重试！",billNo));
                }
            }
        }
    }
}
