package com.yem.wm.es.exportcost.vaildator;

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;

public class ExportCostAmountValidator extends AbstractValidator {

    @Override
    public void validate() {
        ExtendedDataEntity[] extendedDataEntities = this.getDataEntities();
        for (ExtendedDataEntity extendedDataEntity : extendedDataEntities) {
            DynamicObject dataEntity = extendedDataEntity.getDataEntity();
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_csotdetail");
            StringBuilder sb = new StringBuilder();
            for (DynamicObject dynamicObject : collection) {
                int index = collection.indexOf(dynamicObject);
                // 总申请金额
                BigDecimal applyforamt = dynamicObject.getBigDecimal("yem_applyforamt");
                DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_splitcost");
                for (DynamicObject object : subCollection) {
                    BigDecimal applyamt = object.getBigDecimal("yem_applyamt_b");
                    applyforamt = applyforamt.subtract(applyamt);
                }
                if (applyforamt.compareTo(BigDecimal.ZERO) != 0) {
                    sb.append(String.format("费用明细第 [ %s ] 行，拆分后申请费用总和与费用明细申请金额不一致，请修改后提交！", index + 1)).append("\r\n");
                }
            }

            if (sb.length() > 0) {
                this.addErrorMessage(extendedDataEntity, sb.toString());
            }
        }
    }
}
