package nckd.jxccl.swc.init.business;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.param.CustomParam;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.bos.servicehelper.permission.PermissionServiceHelper;
import kd.sdk.swc.hsas.business.extpoint.payroll.ICalPersonCalResultCoverExtPlugin;
import kd.sdk.swc.hsas.common.events.calperson.CalResultCoverSalaryItemEventArgs;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.swc.helper.SWCHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述: 计算结果覆盖薪酬项目扩展接口(排除非财务薪酬项目)
 * @author turborao
 * @date 2025/10/31 10:05
 */
public class CalResultCoverSalaryItemExtPlugin implements ICalPersonCalResultCoverExtPlugin {

    private static final Log logger = LogFactory.getLog(CalResultCoverSalaryItemExtPlugin.class);
    @Override
    public void onFillExtSalaryItem(CalResultCoverSalaryItemEventArgs event) {
        logger.info("进入计算结果覆盖薪酬项目扩展埋点");
        ArrayList excludeItemIdList = new ArrayList<Long>();
        /**
         * 获取当前用户
         */
        Long userId = RequestContext.getOrCreate().getCurrUserId();
        /**
         * 获取 公共自定义参数  WTC_CAL_ACCOUNT
         */
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("WTC_CAL_ACCOUNT");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        String wtc_cal_account  = cusTomMap.get("WTC_CAL_ACCOUNT");
        /**
         * 获取角色中的用户LIST
         */
        List<Long> userIdList = PermissionServiceHelper.getUsersByRoleNum(wtc_cal_account);

        Long taskId = event.getCalTaskId();
        DynamicObject task = SWCHelper.queryTaskInfoById(taskId);
        DynamicObject calRuleHisObj = task.getDynamicObject("calrulev");
        if (calRuleHisObj != null && calRuleHisObj.getLong("id") > 0L && userIdList.contains(userId)) {

            DynamicObject calRulev = SWCHelper.queryOne(FormConstant.HSAS_CALRULE,calRuleHisObj.getLong("id"));
            if (calRulev != null && !SWCHelper.isEmpty(calRulev.getDynamicObjectCollection("calruleitementry"))) {
                DynamicObjectCollection calRuleItemEntry = calRulev.getDynamicObjectCollection("calruleitementry");
                for (DynamicObject dataItem: calRuleItemEntry ) {
                    boolean isAccount = dataItem.getBoolean("nckd_cbaccount");
                    if (!isAccount) {
                        excludeItemIdList.add(dataItem.getLong("salaryitem.id"));
                    }
                }
                event.setExcludeItemIdList(excludeItemIdList);
            }
        }
    }
}
