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

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.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

public class DeclareDocxSubmitValidator extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity extendedDataEntity : dataEntities) {
            DynamicObject dataEntity = extendedDataEntity.getDataEntity();
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());


            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_declare_ec");
            if (collection.isEmpty()) {
                this.addErrorMessage(extendedDataEntity, "报关商品未生成，请处理后提交单据!");
            }

            // 商品明细的每一行的出库报关金额差是否等于0，只要有一行为0，就要给出提示
            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            Map<Integer, BigDecimal> map = new HashMap<>();
            for (DynamicObject dynamicObject : materialinfo) {
                int index = materialinfo.indexOf(dynamicObject);
                BigDecimal exportmat = dynamicObject.getBigDecimal("yem_exportmat");
                map.put(index, exportmat);
            }
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<Integer, BigDecimal> entry : map.entrySet()) {
                Integer idx = entry.getKey();
                BigDecimal amt = entry.getValue();
                if (amt.compareTo(BigDecimal.ZERO) != 0) {
                    sb.append(String.format("商品明细第 [ %s ] 行，出库金额跟报关金额差值 [ %s ]不允许提交，请修改后重试。", idx + 1, amt.setScale(2, RoundingMode.HALF_UP)));
                }
            }

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