package com.yem.wm.es.contactbook.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.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;

/**
 * @Classname ContactBookSaveValidator
 * @Description TODO
 * @Date 2024/1/2 19:27
 * @Created by ZZSLL
 */

public class ContactBookSaveValidator extends AbstractValidator
{
    @Override
    public void validate()
    {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity entry : dataEntities) {
            DynamicObject dataEntity = entry.getDataEntity();
            String billno = dataEntity.getString("billno");

            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
            if (dynamicObject != null) {
                DynamicObjectCollection materialinfo = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject object : collection) {
                    int index = collection.indexOf(object);
                    for (DynamicObject materialinfoEntry : materialinfo) {
                        Long pkValue = (Long) materialinfoEntry.getPkValue();
                        if (object.getLong("yem_sourceentryid") == pkValue) {
                            // 发货联系书数量
                            BigDecimal qty = object.getBigDecimal("yem_qty");
                            // 订舱通知单数量
                            BigDecimal decimal = materialinfoEntry.getBigDecimal("yem_qty");
                            if (qty.compareTo(decimal) > 0) {
                                throw new KDBizException("商品明细第 " + (index + 1) + " 行中，数量不允许超出对应订舱通知单商品明细中的数量");
                            }
                        }
                    }
                }
                dynamicObject.set("yem_secdeliverytime", dataEntity.get("yem_secdeliverytime"));
                SaveServiceHelper.update(dynamicObject);
            }
        }
    }
}
