package nckd.jimin.jyyy.fi.plugin.operate;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import java.math.BigDecimal;
import java.util.List;

/**
 * 费用申请：nckd_er_dailyapplybil_ext
 * @author wanghaiwu_kd
 * @date 2025/09/26
 */
public class DailyApplyBillAmountOpPlugin extends AbstractOperationServicePlugIn {
    private static final Log logger = LogFactory.getLog(DailyApplyBillAmountOpPlugin.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);

        List<String> fieldKeys = e.getFieldKeys();

        fieldKeys.add("applyamount");
        fieldKeys.add("nckd_expenseitem");
        fieldKeys.add("nckd_limitamount");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        this.addDailyApplyAmountValidator(e);
    }

    protected void addDailyApplyAmountValidator(AddValidatorsEventArgs e) {
        e.addValidator(new DailyApplyAmountValiator());
    }

    private static class DailyApplyAmountValiator extends AbstractValidator {
        private DailyApplyAmountValiator() {
        }

        public void validate() {
            ExtendedDataEntity[] dataEntities = this.getDataEntities();
            ExtendedDataEntity[] var2 = dataEntities;
            int var3 = dataEntities.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                ExtendedDataEntity dataEntity = var2[var4];
                DynamicObject billObj = dataEntity.getDataEntity();

                BigDecimal applyAmount = billObj.getBigDecimal("applyamount");
                BigDecimal limitAmount = billObj.getBigDecimal("nckd_limitamount");

                DynamicObject expenseItem = billObj.getDynamicObject("nckd_expenseitem");
                if(expenseItem != null){
                    String number = expenseItem.getString("number");
                    String name = expenseItem.getString("name");

                    if("FYXM02.01.01".equals(number) || "业务招待费-个人".equals(name)){
                        if(applyAmount.compareTo(limitAmount) > 0){
                            this.addErrorMessage(dataEntity, ResManager.loadKDString("申请金额不能超过可用额度", "DailyApplyBillAmountOpPlugin_1", "fi-er-opplugin", new Object[0]));
                        }
                    }
                }
            }
        }
    }
}
