package nckd.jxccl.swc.hcss.formplugin;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.datamodel.IDataModel;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.sdk.swc.hsas.business.internal.spi.CalResultQueryService;
import kd.swc.hcss.formplugin.web.AbstractHcssBaseFormPlugin;
import nckd.jxccl.swc.constants.SwcConstant;
import nckd.jxccl.swc.utils.SwcUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义收入证明项目列表
 * 系统服务云-公共设置-系统参数-自定义参数
 * 参数名称为 INCOMEPROOFBILL_CUSTOMITEMS 收入证明办理单，自定义收入证明项目编码 参数值为  000001,000002
 * 参数名称为 INCOMEPROOFBILL_SALARYITEMS 收入证明办理单，自定义收入证明获取员工薪酬金额的薪酬项目编码 参数值为  JT_283,JT_477  示例
 * @author turborao
 * @date 2025-12-03
 * @desc
 */
public class IncomeProofBillExPlugin extends AbstractHcssBaseFormPlugin {

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

    public void initialize() {

        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");

    }


    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {

        FormOperate source = (FormOperate)args.getSource();
        OperateOption option = source.getOption();
        String formOp = source.getOperateKey();
        Long id = this.getModel().getDataEntity().getLong("id");
        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);
        }

        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, BigDecimal.ROUND_HALF_UP);
                //赋值
                dealIncomeInfo(amount, monthlyAmount);
            }
        }
    }


    /**
     * 根据薪员工 +日期范围获取薪资明细
     * @return
     */
    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());
        DynamicObjectCollection cols = ORM.create().toPlainDynamicObjectCollection(dataSet);
        return cols;

    }

    private void dealIncomeInfo(BigDecimal amount, BigDecimal monthlyAmount) {
        List<String> customItems = getCustomItems();
        IDataModel model = this.getModel();
        int rowCount = model.getEntryRowCount("entryentity");
        String regex = "[^0-9.]";
        for(int i = 0; i < rowCount; i++) {
            String revenueFieldNum = model.getValue("frevenuefieldid.number", i).toString();
            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 false;
            }
        }
        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 "''"; // 返回空字符串的 SQL 格式
        }

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

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

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

}
