package nckd.jxccl.swc.hcss.formplugin;

import kd.bos.algo.DataSet;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.param.CustomParam;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import nckd.jxccl.swc.utils.SwcUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


/**
 * 自定义收入证明项目列表
 * 系统服务云-公共设置-系统参数-自定义参数
 * 参数名称为 INCOMEPROOFBILL_CUSTOMITEMS 收入证明办理单，自定义收入证明项目编码 参数值为  000001,000002
 * 参数名称为 INCOMEPROOFBILL_SALARYITEMS 收入证明办理单，自定义收入证明获取员工薪酬金额的薪酬项目编码 参数值为  JT_283,JT_331  示例
 *
 * @author turborao
 * 创建时间 2026-01-07
 * 描述 自定义收入证明项目获取计算
 */
@SuppressWarnings("unused")
public class IncomeProofBillExPlugin extends AbstractBillPlugIn {

    private static String IncomeProofBill_CustomItems;
    private static String IncomeProofBill_SalaryItems;
    private static final Log logger = LogFactory.getLog(IncomeProofBillExPlugin.class);

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);

        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("INCOMEPROOFBILL_CUSTOMITEMS");
        customParam.getSearchKeySet().add("INCOMEPROOFBILL_SALARYITEMS");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        IncomeProofBill_CustomItems  = cusTomMap.get("INCOMEPROOFBILL_CUSTOMITEMS");
        IncomeProofBill_SalaryItems  = cusTomMap.get("INCOMEPROOFBILL_SALARYITEMS");

        this.getView().setEnable(Boolean.FALSE, "nckd_daterange");
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {

        FormOperate source = (FormOperate)args.getSource();
        String formOp = source.getOperateKey();
        DynamicObject data = this.getModel().getDataEntity();
        Long empId = data.getLong("employee.id");
        Date startDate = data.getDate("nckd_startdate");
        Date endDate = data.getDate("nckd_enddate");

        boolean isExistCustomItems = false;
        if ("checkapprove".equals(formOp)) {
            isExistCustomItems = isExistCustomItems(data);
        } else if ("modify".equals(formOp)) {
            this.getView().setEnable(Boolean.TRUE, "nckd_daterange");
        }

        super.beforeDoOperation(args);

        /// 以上需要保留标准产品计算逻辑，有自定义收入证明项目时才取数
        if(isExistCustomItems){
            String salaryitem = getSalaryItemsForSql();
            DynamicObjectCollection salaryDetail = querySalaryDetailByEmp(empId, salaryitem, startDate, endDate);
            if(salaryDetail.size() > 0){
                DynamicObject salaryDetailObj = salaryDetail.get(0);
                BigDecimal amount = salaryDetailObj.getBigDecimal("amount");
                BigDecimal monthCount = salaryDetailObj.getBigDecimal("monthCount");
                BigDecimal monthlyAmount = amount.divide(monthCount, 2, RoundingMode.HALF_UP);
                //赋值
                if(amount.compareTo(BigDecimal.ZERO) > 0 && monthCount.compareTo(BigDecimal.ZERO) > 0) {
                    dealIncomeInfo(amount.setScale(2, RoundingMode.HALF_UP), monthlyAmount);
                }
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();

        if(StringUtils.equals(this.getPageCache().get("noChange"), "true")){
            return;
        }

        if (StringUtils.equals("nckd_startdate", fieldKey) || StringUtils.equals("nckd_enddate", fieldKey)){
            IDataModel model = this.getModel();
            int rowCount = model.getEntryRowCount("entryentity");
            this.getPageCache().put("noChange", "true");
            for(int i = 0; i < rowCount; i++) {
                model.setValue("checkvalue", BigDecimal.ZERO.toString(), i);
            }
            this.getPageCache().put("noChange", "false");
        }
    }

    /**
     * 根据薪员工 +日期范围获取薪资明细
     * @return  DynamicObjectCollection
     */
    public DynamicObjectCollection querySalaryDetailByEmp(Long empId,String salaryitem, Date startDate, Date endDate) {
        StringBuilder sb = SwcUtils.getSalaryDetailSqlByEmp(empId, salaryitem,startDate, endDate);
        DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("swc"), sb.toString());
        logger.info("IncomeProofBillExPlugin 开始查询薪资数据，参数：{},{},{},{}", empId, salaryitem,startDate,endDate);
        return ORM.create().toPlainDynamicObjectCollection(dataSet);

    }

    private void dealIncomeInfo(BigDecimal amount, BigDecimal monthlyAmount) {
        List<String> customItems = getCustomItems();
        IDataModel model = this.getModel();
        int rowCount = model.getEntryRowCount("entryentity");
        for(int i = 0; i < rowCount; i++) {
            if(model.getValue("revenuefield", i) != null){
                DynamicObject revenuefieldDyn = (DynamicObject)model.getValue("revenuefield", i);
                String revenueFieldNum = revenuefieldDyn.getString("number");
                if(revenueFieldNum.equals(customItems.get(0))){
                    model.setValue("calvalue", amount.toString(), i);
                    model.setValue("checkvalue", amount.toString(), i);
                }
                if(revenueFieldNum.equals(customItems.get(1))){
                    model.setValue("calvalue", monthlyAmount.toString(), i);
                    model.setValue("checkvalue", monthlyAmount.toString(), i);
                }
            }
        }
    }


    /**
     * 判断 收入证明办理单中是否包含自定义收入证明项目
     */
    public boolean isExistCustomItems(DynamicObject data) {
        List<String> customItems = getCustomItems();
        // 如果没有自定义项目配置，直接返回 true（或根据业务需求决定）
        if (customItems.isEmpty()) {
            return false;
        }
        List<String> entryNumbers = new ArrayList<>();
        DynamicObjectCollection dynamicObjectCollection = data.getDynamicObjectCollection("entryentity");
        for (DynamicObject dynamicObject : dynamicObjectCollection) {
            DynamicObject revenueField = dynamicObject.getDynamicObject("revenuefield");
            String number = revenueField.getString("number");
            entryNumbers.add(number);

        }
        for (String customItem : customItems) {
            if (entryNumbers.contains(customItem)) {
                return true;
            }
        }
        return false;
    }

    public List<String> getCustomItems() {
        if (IncomeProofBill_CustomItems == null || IncomeProofBill_CustomItems.trim().isEmpty()) {
            return new java.util.ArrayList<>();
        }
        return java.util.Arrays.asList(IncomeProofBill_CustomItems.split(","));
    }

    public String getSalaryItemsForSql() {
        if (IncomeProofBill_SalaryItems == null || IncomeProofBill_SalaryItems.trim().isEmpty()) {
            return "''";
        }

        String[] items = IncomeProofBill_SalaryItems.split(",");
        List<String> quotedItems = new ArrayList<>();

        for (String item : items) {
            quotedItems.add("'" + item.trim() + "'");
        }

        return String.join(",", quotedItems);
    }

}
