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

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Label;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.fi.er.business.daily.service.model.CurrencyBO;
import kd.fi.er.business.reimamountctl.mode.QuotaCtrlMode;
import kd.fi.er.business.reimamountctl.mode.QuotaCtrlModeFactory;
import kd.fi.er.business.reimamountctl.model.QuotaAmountBO;
import kd.fi.er.business.reimamountctl.utils.QuotaCtrlUtil;
import kd.fi.er.business.utils.ErCommonUtils;
import kd.fi.er.business.utils.ErEntityTypeUtils;
import kd.fi.er.business.utils.ErStdConfig;
import kd.fi.er.business.utils.ReimburseControlUtils;
import kd.fi.er.formplugin.daily.web.ReimburseAmountControlFormPlugin;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.time.YearMonth;
import java.util.*;

/**
 * 单据标识：费用申请单(nckd_er_dailyapplybil_ext)
 * @author wanghaiwu_kd
 * @date 2025/09/03
 */
public class DailyApplyBillAmountEditPlugin extends AbstractBillPlugIn {
    private static final Log log = LogFactory.getLog(DailyApplyBillAmountEditPlugin.class);
    private String quotaDateField = ErStdConfig.get("quotaDateField");

    public DailyApplyBillAmountEditPlugin() {
    }

    public void registerListener(EventObject e) {
        this.addEntryRowClick();
    }

    private void addEntryRowClick() {
        EntryGrid expenseEntry = (EntryGrid)this.getControl("expenseentryentity");
        expenseEntry.addRowClickListener(new RowClickEventListener() {
            public void entryRowClick(RowClickEvent evt) {
                int row = evt.getRow();
                DailyApplyBillAmountEditPlugin.this.getPageCache().put("currentExpenseEntryIndex", String.valueOf(row));
                showHeadBalanceAmount();
            }
        });
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        String fieldKey = e.getProperty().getName();

        //费用类型
        if("nckd_expenseitem".equals(fieldKey) || "happendate".equals(fieldKey)){
            showHeadBalanceAmount();
        }
    }

    private void showHeadBalanceAmount(){
        ((Label)this.getControl("nckd_reimbursecontrolinfo")).setText("");
        this.getModel().setValue("nckd_limitamount", BigDecimal.ZERO);

        DynamicObject dataEntity = this.getModel().getDataEntity(true);
//        DynamicObjectCollection expenseEntries = dataEntity.getDynamicObjectCollection("expenseentryentity");
//        String rowIndexStr = this.getPageCache().get("currentExpenseEntryIndex");
//        int currentRowIndex;
//        if (StringUtils.isNotBlank(rowIndexStr)) {
//            currentRowIndex = Integer.parseInt(rowIndexStr);
//        } else {
//            currentRowIndex = this.getModel().getEntryCurrentRowIndex("expenseentryentity");
//        }

//        if (currentRowIndex >= 0 && expenseEntries.size() > 0) {
//            if (currentRowIndex >= expenseEntries.size()) {
//                currentRowIndex = 0;
//            }

//            DynamicObject expenseEntry = (DynamicObject)expenseEntries.get(currentRowIndex);
//            if (!this.validRow(expenseEntry)) {
//                ((Label)this.getControl("nckd_reimbursecontrolinfo")).setText("");
//            } else {
                IDataModel model = this.getModel();
                Long companyId = ErCommonUtils.getPk((DynamicObject)model.getValue("company"));
                String personCtrlCurrency = (String)ErCommonUtils.getEMParameter(companyId, "personctlcurrency");
                String deptCtrlCurrency = (String)ErCommonUtils.getEMParameter(companyId, "deptctlcurrency");
                List<String> empCltList = this.getEmpCltBill();
                List<String> deptCltList = this.getDeptCltBill();
                DynamicObject currency = (DynamicObject)model.getValue("currency");
                Long currencyId = currency == null ? 0L : (Long)currency.getPkValue();
                DynamicObject amountControlCompanyDO = ReimburseControlUtils.getReimburseControlCompany(model.getDataEntity());

                QuotaAmountBO reimAmountBO = new QuotaAmountBO();
                reimAmountBO.setCompanyId((Long)amountControlCompanyDO.getPkValue());
                reimAmountBO.setEmpCtlBill(empCltList);
                reimAmountBO.setDeptCtlBill(deptCltList);
                DynamicObject expenseitem = dataEntity.getDynamicObject("nckd_expenseitem");

                expenseitem = BusinessDataServiceHelper.loadSingle(expenseitem.getPkValue(), expenseitem.getDynamicObjectType().getName());

                if(expenseitem == null){
                    return;
                }
                String isreimburseamountctl = expenseitem.getString("isreimburseamountctl");

                if (!"1".equals(isreimburseamountctl)) {
                    return;
                }
                reimAmountBO.setExpenseItemId((Long)expenseitem.getPkValue());
                reimAmountBO.setCtrlCount(expenseitem.getInt("reimburseamountctlcount"));
                reimAmountBO.setCtrlMethod(expenseitem.getString("reimburseamountctlmethod"));
                reimAmountBO.setCtrlType(expenseitem.getString("reimctltype"));


                reimAmountBO.setCtrlMode(isreimburseamountctl);

                Long oriCurrencyId = (Long)dataEntity.getDynamicObject("currency").getPkValue();
                reimAmountBO.setUserOrDeptId((Long)dataEntity.getDynamicObject("applier").getPkValue());
                QuotaCtrlUtil.genQuotaCurrency(reimAmountBO, personCtrlCurrency, oriCurrencyId, currencyId);
                String showName = dataEntity.getDynamicObject("applier").getLocaleString("name").getLocaleValue();

                Date date = (Date)model.getValue("bizdate");
//                if ("2".equals(this.quotaDateField)) {
//                    date = (Date)model.getValue("bizdate");
//                }

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                reimAmountBO.setHappenDate(YearMonth.of(calendar.get(1), calendar.get(2) + 1));

//                boolean isAduit = false;
//                if (Arrays.asList("B", "C").contains((String)model.getValue("billstatus"))) {
//                    isAduit = true;
//                }

                List<Long> excludeReimbureBillIds = new ArrayList();
//                if (isAduit) {
//                    excludeReimbureBillIds.add((Long)model.getDataEntity().getPkValue());
//                    log.info("是审核状态, 排除的单据为: " + excludeReimbureBillIds);
//                }

                reimAmountBO.setNotInIds(excludeReimbureBillIds);
                QuotaCtrlMode quotaCtrlMode = QuotaCtrlModeFactory.getQuotaCtrlMode(reimAmountBO);
                BigDecimal balanceAmount = quotaCtrlMode.getBalanceAmount(reimAmountBO);
                if ("2".equals(reimAmountBO.getCtrlType()) && balanceAmount == null) {
                    ((Label)this.getControl("nckd_reimbursecontrolinfo")).setText("");
                } else {
                    if (balanceAmount == null) {
                        balanceAmount = BigDecimal.ZERO;
                    }

                    String balanceAmountStr = ErCommonUtils.getMoneyStringWithSymbol(balanceAmount, new CurrencyBO(reimAmountBO.getCurrencyId()));
                    String expenseItemName = expenseitem.getLocaleString("name").getLocaleValue();
                    String template = ResManager.loadKDString("可用额度: %1$s|%2$s|%3$s", "ReimburseAmountControlFormPlugin_0", "fi-er-formplugin", new Object[0]);
                    String reimburseControlInfo = String.format(template, showName, expenseItemName, balanceAmountStr);
                    ((Label)this.getControl("nckd_reimbursecontrolinfo")).setText(reimburseControlInfo);

                    this.getModel().setValue("nckd_limitamount", balanceAmount);
                }
//            }
//        } else {
//            ((Label)this.getControl("nckd_reimbursecontrolinfo")).setText("");
//        }
    }

    private boolean validRow(DynamicObject entry) {
        DynamicObject expenseitem = entry.getDynamicObject("expenseitem");
        boolean on = expenseitem != null && entry.getDynamicObject("entrycurrency") != null && entry.getDate("happendate") != null;
        if (!on) {
            return false;
        } else {
            String isreimburseamountctl = expenseitem.getString("isreimburseamountctl");
            DynamicObject reimburser;

            if ("1".equals(isreimburseamountctl)) {
                reimburser = this.getModel().getDataEntity().getDynamicObject("applier");

                if (reimburser == null) {
                    return false;
                }
            }

            return true;
        }
    }

    private List<String> getEmpCltBill() {
        String pageEmpCltBill = this.getPageCache().get("empCltBill");
        if (StringUtils.isNotBlank(pageEmpCltBill)) {
            List<String> empCltList = Arrays.asList(pageEmpCltBill.split(","));
            return empCltList;
        } else {
            DynamicObject company = (DynamicObject)this.getModel().getValue("company");
            if (company == null) {
                return new ArrayList();
            } else {
                String empCltBill = (String)ErCommonUtils.getEMParameter((Long)company.getPkValue(), "empquotaapplicablebill");
                this.getPageCache().put("empCltBill", empCltBill);
                return Arrays.asList(empCltBill.split(","));
            }
        }
    }

    private List<String> getDeptCltBill() {
        String pageDeptCltBill = this.getPageCache().get("deptCltBill");
        if (StringUtils.isNotBlank(pageDeptCltBill)) {
            List<String> deptCltList = Arrays.asList(pageDeptCltBill.split(","));
            return deptCltList;
        } else {
            DynamicObject company = (DynamicObject)this.getModel().getValue("company");
            if (company == null) {
                return new ArrayList();
            } else {
                String deptCltBill = (String)ErCommonUtils.getEMParameter((Long)company.getPkValue(), "deptquotaapplicablebill");
                this.getPageCache().put("deptCltBill", deptCltBill);
                return Arrays.asList(deptCltBill.split(","));
            }
        }
    }
}
