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

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;

public class CompleteMachineNumberValidator 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 materialInfos = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            String billtype = dataEntity.getString("yem_billtype.number");
            if ("yem_shippingdetails_zj".equals(billtype) || "yem_shippingdetails_nmzj".equals(billtype)) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < materialInfos.size(); i++) {
                    DynamicObject materialInfo = materialInfos.get(i);
                    String businesssort = materialInfo.getString("yem_businesssort");
                    if ("Z".equals(businesssort)) {
                        BigDecimal qty = materialInfo.getBigDecimal("yem_qty");
                        DynamicObject resourceNog = materialInfo.getDynamicObject("yem_resourcenog");
                        String resourceNogNumber = YEM.isNotEmpty(resourceNog) ? resourceNog.getString("number") : "";
                        DynamicObjectCollection completeProductions = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
                        int completeProductionRows = completeProductions.size();
                        if (qty.compareTo(new BigDecimal(completeProductionRows)) != 0) {
                            sb.append(String.format("明细信息第 %s 行 %s 资源号的出运数量与对应的整机数量不一致，请检查数据！！\r\n", i + 1, resourceNogNumber));
                        }
                    }
                }
                if (sb.length() > 0) {
                    this.addErrorMessage(extendedDataEntity, sb.toString());
                }
            }
        }
    }
}
