package nckd.jxccl.hr.psms.business;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 管理人员津贴业务逻辑
 *
 * @author W.Y.C
 * @date 2025/12/6 16:27
 * @version 1.0
 */
public class ManagerAllowanceService {


    /**
     * 生成职位津贴，根据职位津贴配置的条件
     *
     * @param data 职位档案数据列表
     */
    public static void generateMgrPostAllow(List<DynamicObject> data) {
        if (data == null || data.isEmpty()) {
            return;
        }

        // 获取必要的ID列表
        DataIds dataIds = extractDataIds(data);

        // 加载必要的数据
        LoadedData loadedData = loadRequiredData(dataIds);

        List<DynamicObject> addOrExpireMgrPostAllowList = new ArrayList<>();

        for (DynamicObject datum : data) {
            long personId = datum.getLong(String.join(".", PositionStructureConstant.NCKD_PERSON, FormConstant.ID_KEY));
            DynamicObject person = datum.getDynamicObject(PositionStructureConstant.NCKD_PERSON);

            List<DynamicObject> managerAllowanceList = loadedData.managerAllowanceMap.get(personId);

            // 判断人员是否符合职位津贴条件
            QualificationResult qualificationResult = checkQualification(
                    personId, loadedData.mgrPostAllowConfList, loadedData.adminOrgMap,
                    loadedData.jobLevelMap, loadedData.personPosFileArchivesMap);

            if (!loadedData.mgrPostAllowConfList.isEmpty()) {
                if (qualificationResult.isQualified) {
                    // 符合条件
                    if (managerAllowanceList == null || managerAllowanceList.isEmpty()) {
                        // 符合条件但尚无津贴记录，新增职位津贴
                        DynamicObject newEntity = EntityHelper.newEntity(PositionStructureConstant.MANAGERALLOWANCE_ENTITYID);
                        newEntity.set(FormConstant.NCKD_PERSON, person);
                        newEntity.set(FormConstant.NCKD_STARTDATE, qualificationResult.beginDate == null ? new Date() : qualificationResult.beginDate);
                        newEntity.set(PositionStructureConstant.NCKD_JOBLEVELHR, qualificationResult.jobLevelObj);
                        newEntity.set(PositionStructureConstant.NCKD_PROTITLELEVEL, qualificationResult.protitleLeveObj);
                        newEntity.set(FormConstant.DESCRIPTION_KEY, "符合【职位津贴条件】，系统自动生成");
                        addOrExpireMgrPostAllowList.add(newEntity);
                    }
                    // 如果已有津贴记录且符合条件，则不做处理
                } else {
                    // 不符合条件
                    handleDisqualification(managerAllowanceList, qualificationResult.beginDate, addOrExpireMgrPostAllowList);
                }
            } else {
                // 连配置都没有了，直接失效职位津贴
                handleNoConfiguration(managerAllowanceList, addOrExpireMgrPostAllowList);
            }
        }

        // 保存变更
        saveChanges(addOrExpireMgrPostAllowList);
    }

    /**
     * 失效职位津贴
     *
     * @param data 职位档案数据列表
     */
    public static void expireMgrPostAllow(List<DynamicObject> data) {
        if (data == null || data.isEmpty()) {
            return;
        }

        // 获取必要的ID列表
        DataIds dataIds = extractDataIds(data);

        // 加载必要的数据
        LoadedData loadedData = loadRequiredData(dataIds);

        List<DynamicObject> addOrExpireMgrPostAllowList = new ArrayList<>();

        for (DynamicObject datum : data) {
            long currentId = datum.getLong(FormConstant.ID_KEY);
            long personId = datum.getLong(String.join(".", PositionStructureConstant.NCKD_PERSON, FormConstant.ID_KEY));

            List<DynamicObject> managerAllowanceList = loadedData.managerAllowanceMap.get(personId);

            // 判断人员是否符合职位津贴条件（排除当前变更的档案）
            QualificationResult qualificationResult = checkQualificationExcludeCurrent(
                    personId, currentId, loadedData.mgrPostAllowConfList, loadedData.adminOrgMap,
                    loadedData.jobLevelMap, loadedData.personPosFileArchivesMap);

            if (!loadedData.mgrPostAllowConfList.isEmpty()) {
                if (!qualificationResult.isQualified) {
                    // 其他档案不符合条件，失效职位津贴
                    handleDisqualification(managerAllowanceList, qualificationResult.beginDate, addOrExpireMgrPostAllowList);
                }
                // 其他档案还是符合条件的，不处理
            } else {
                // 连配置都没有了，直接失效职位津贴
                handleNoConfiguration(managerAllowanceList, addOrExpireMgrPostAllowList);
            }
        }

        // 保存变更
        saveChanges(addOrExpireMgrPostAllowList);
    }

    /**
     * 提取数据中的各种ID
     */
    private static DataIds extractDataIds(List<DynamicObject> data) {
        DataIds dataIds = new DataIds();
        dataIds.adminIds = new ArrayList<>();
        dataIds.jobLevelIds = new ArrayList<>();
        dataIds.personIds = new ArrayList<>();

        for (DynamicObject datum : data) {
            dataIds.adminIds.add(datum.getLong(String.join(".", FormConstant.NCKD_DEP, FormConstant.ID_KEY)));
            dataIds.jobLevelIds.add(datum.getLong(String.join(".", PositionStructureConstant.NCKD_JOBLEVELHR, FormConstant.ID_KEY)));
            dataIds.personIds.add(datum.getLong(String.join(".", PositionStructureConstant.NCKD_PERSON, FormConstant.ID_KEY)));
        }

        return dataIds;
    }

    /**
     * 加载所需的各类数据
     */
    private static LoadedData loadRequiredData(DataIds dataIds) {
        LoadedData loadedData = new LoadedData();

        // 加载职位津贴配置
        loadedData.mgrPostAllowConfList = findMgrPostAllowConf();

        // 加载组织信息
        loadedData.adminOrgMap = loadAndGroupAdminOrgs(dataIds.adminIds);

        // 加载职级信息
        loadedData.jobLevelMap = loadAndGroupJobLevels(dataIds.jobLevelIds);

        // 加载有效的职位津贴数据
        loadedData.managerAllowanceMap = loadAndGroupManagerAllowance(dataIds.personIds);

        // 加载人员所有有效中的职位档案
        loadedData.personPosFileArchivesMap = loadPersonPosFileArchives(dataIds.personIds);

        return loadedData;
    }

    /**
     * 检查人员是否符合职位津贴条件
     */
    private static QualificationResult checkQualification(long personId,
                                                          List<DynamicObject> mgrPostAllowConfList,
                                                          Map<Long, DynamicObject> adminOrgMap,
                                                          Map<Long, DynamicObject> jobLevelMap,
                                                          Map<Long, List<DynamicObject>> personPosFileArchivesMap) {
        QualificationResult result = new QualificationResult();
        result.isQualified = false;

        List<DynamicObject> personPosFileArchives = personPosFileArchivesMap.get(personId);
        if (personPosFileArchives != null && !personPosFileArchives.isEmpty()) {
            for (DynamicObject personPosFileArchive : personPosFileArchives) {
                long adminOrgId = personPosFileArchive.getLong(String.join(".", FormConstant.NCKD_DEP, FormConstant.ID_KEY));
                long jobSeqId = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_JOBSEQHR, FormConstant.ID_KEY));
                long jobLevel = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_JOBLEVELHR, FormConstant.ID_KEY));
                long protitleLevelId = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_PROTITLELEVEL, FormConstant.ID_KEY));

                result.protitleLeveObj = EntityHelper.newEntity(FormConstant.HBSS_PROTITLELEVEL, protitleLevelId);
                result.beginDate = personPosFileArchive.getDate(PositionStructureConstant.NCKD_BEGINDATE);

                for (DynamicObject mgrPostAllowConf : mgrPostAllowConfList) {
                    // 序列是否符合
                    long confJobSeqId = mgrPostAllowConf.getLong(String.join(".", PositionStructureConstant.NCKD_JOBSEQHR, FormConstant.ID_KEY));
                    if (confJobSeqId != jobSeqId) {
                        continue;
                    }

                    // 组织是否符合
                    if (!isAdminOrgMatch(adminOrgId, mgrPostAllowConf, adminOrgMap)) {
                        continue;
                    }

                    // 职称级别是否符合
                    if (!isProtitleLevelMatch(protitleLevelId, mgrPostAllowConf)) {
                        continue;
                    }

                    // 职级是否符合
                    JobLevelMatchResult jobLevelMatchResult = isJobLevelMatch(jobLevel, mgrPostAllowConf, jobLevelMap);
                    if (!jobLevelMatchResult.isMatch) {
                        continue;
                    }

                    result.isQualified = true;
                    result.jobLevelObj = jobLevelMatchResult.jobLevelObj;
                    break;
                }

                if (result.isQualified) {
                    // 有符合的就不找下一个档案了
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 检查人员是否符合职位津贴条件（排除指定的档案ID）
     */
    private static QualificationResult checkQualificationExcludeCurrent(long personId,
                                                                       long excludeId,
                                                                       List<DynamicObject> mgrPostAllowConfList,
                                                                       Map<Long, DynamicObject> adminOrgMap,
                                                                       Map<Long, DynamicObject> jobLevelMap,
                                                                       Map<Long, List<DynamicObject>> personPosFileArchivesMap) {
        QualificationResult result = new QualificationResult();
        result.isQualified = false;

        List<DynamicObject> personPosFileArchives = personPosFileArchivesMap.get(personId);
        if (personPosFileArchives != null && !personPosFileArchives.isEmpty()) {
            for (DynamicObject personPosFileArchive : personPosFileArchives) {
                long id = personPosFileArchive.getLong(FormConstant.ID_KEY);
                // 因为这条职位档案是删除/生效的，所以不能判断当前职位档案是否满足职位津贴条件
                if (id != excludeId) {
                    long adminOrgId = personPosFileArchive.getLong(String.join(".", FormConstant.NCKD_DEP, FormConstant.ID_KEY));
                    long jobSeqId = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_JOBSEQHR, FormConstant.ID_KEY));
                    long jobLevel = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_JOBLEVELHR, FormConstant.ID_KEY));
                    long protitleLevelId = personPosFileArchive.getLong(String.join(".", PositionStructureConstant.NCKD_PROTITLELEVEL, FormConstant.ID_KEY));

                    result.beginDate = personPosFileArchive.getDate(PositionStructureConstant.NCKD_BEGINDATE);

                    for (DynamicObject mgrPostAllowConf : mgrPostAllowConfList) {
                        // 序列是否符合
                        long confJobSeqId = mgrPostAllowConf.getLong(String.join(".", PositionStructureConstant.NCKD_JOBSEQHR, FormConstant.ID_KEY));
                        if (confJobSeqId != jobSeqId) {
                            continue;
                        }

                        // 组织是否符合
                        if (!isAdminOrgMatch(adminOrgId, mgrPostAllowConf, adminOrgMap)) {
                            continue;
                        }

                        // 职称级别是否符合
                        if (!isProtitleLevelMatch(protitleLevelId, mgrPostAllowConf)) {
                            continue;
                        }

                        // 职级是否符合
                        JobLevelMatchResult jobLevelMatchResult = isJobLevelMatch(jobLevel, mgrPostAllowConf, jobLevelMap);
                        if (!jobLevelMatchResult.isMatch) {
                            continue;
                        }

                        result.isQualified = true;
                        result.jobLevelObj = jobLevelMatchResult.jobLevelObj;
                        break;
                    }
                }

                if (result.isQualified) {
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 检查组织是否匹配
     */
    private static boolean isAdminOrgMatch(long adminOrgId,
                                          DynamicObject mgrPostAllowConf,
                                          Map<Long, DynamicObject> adminOrgMap) {
        long confAdminOrgId = mgrPostAllowConf.getLong(String.join(".", PositionStructureConstant.NCKD_ORG, FormConstant.ID_KEY));
        DynamicObject adminOrg = adminOrgMap.get(adminOrgId);

        if (adminOrg == null || confAdminOrgId <= 0) {
            return false;
        }

        long firstOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_FIRSTORG, FormConstant.ID_KEY));
        long secondOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_SECONDORG, FormConstant.ID_KEY));
        long thirdOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_THIRDORG, FormConstant.ID_KEY));
        long fourthOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_FOURTHORG, FormConstant.ID_KEY));
        long fifthOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_FIFTHORG, FormConstant.ID_KEY));
        long sixthOrg = adminOrg.getLong(String.join(".", FormConstant.NCKD_SIXTHORG, FormConstant.ID_KEY));

        // 人员职位档案中的组织与职位津贴配置的组织是否符合
        Set<Long> orgSet = new HashSet<>(Arrays.asList(firstOrg, secondOrg, thirdOrg, fourthOrg, fifthOrg, sixthOrg));
        return orgSet.contains(confAdminOrgId);
    }

    /**
     * 检查职称级别是否匹配
     */
    private static boolean isProtitleLevelMatch(long protitleLevelId, DynamicObject mgrPostAllowConf) {
        DynamicObjectCollection protitleLevelColl = mgrPostAllowConf.getDynamicObjectCollection(PositionStructureConstant.NCKD_PROTITLELEVEL);
        for (DynamicObject protitleLevel : protitleLevelColl) {
            DynamicObject mulData = protitleLevel.getDynamicObject(FormConstant.BASEDATAID_KEY);
            long confProtitleLevelId = mulData.getLong(FormConstant.ID_KEY);
            if (confProtitleLevelId == protitleLevelId) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查职级是否匹配
     */
    private static JobLevelMatchResult isJobLevelMatch(long jobLevel,
                                                       DynamicObject mgrPostAllowConf,
                                                       Map<Long, DynamicObject> jobLevelMap) {
        JobLevelMatchResult result = new JobLevelMatchResult();
        result.isMatch = false;

        if (jobLevel > 0) {
            DynamicObject jobLevelObj = jobLevelMap.get(jobLevel);
            if (jobLevelObj != null) {
                int jobLevelSeq = jobLevelObj.getInt(PositionStructureConstant.JOBLEVELSEQ);
                DynamicObject confMinJobLevel = mgrPostAllowConf.getDynamicObject(PositionStructureConstant.NCKD_MINJOBLEVEL);
                DynamicObject confMaxJobLevel = mgrPostAllowConf.getDynamicObject(PositionStructureConstant.NCKD_MAXJOBLEVEL);

                if (confMinJobLevel != null) {
                    int min = confMinJobLevel.getInt(PositionStructureConstant.JOBLEVELSEQ);
                    int max = confMaxJobLevel == null ? Integer.MAX_VALUE : confMaxJobLevel.getInt(PositionStructureConstant.JOBLEVELSEQ);
                    if (jobLevelSeq >= min && jobLevelSeq <= max) {
                        result.isMatch = true;
                        result.jobLevelObj = jobLevelObj;
                    }
                }
            }
        }

        return result;
    }

    /**
     * 处理不符合条件的情况
     */
    private static void handleDisqualification(List<DynamicObject> managerAllowanceList,
                                              Date beginDate,
                                              List<DynamicObject> addOrExpireMgrPostAllowList) {
        if (managerAllowanceList != null) {
            // 不符合条件，失效职位津贴
            for (DynamicObject managerAllowance : managerAllowanceList) {
                Date startDate = managerAllowance.getDate(FormConstant.NCKD_STARTDATE);
                Date endDate = beginDate == null ? new Date() : beginDate;
                if (startDate != null && beginDate != null && beginDate.before(startDate)) {
                    // 如果beginDate在职位津贴开始日期之前，则结束使用津贴开始日期
                    endDate = startDate;
                }
                managerAllowance.set(FormConstant.NCKD_ENDDATE, endDate);
                String description = managerAllowance.getString(FormConstant.DESCRIPTION_KEY);
                if (StringUtils.isNotEmpty(description)) {
                    managerAllowance.set(FormConstant.DESCRIPTION_KEY, description + "；" + "不符合【职位津贴条件】，系统自动失效");
                } else {
                    managerAllowance.set(FormConstant.DESCRIPTION_KEY, "不符合【职位津贴条件】，系统自动失效");
                }
                addOrExpireMgrPostAllowList.add(managerAllowance);
            }
        }
    }

    /**
     * 处理无配置的情况
     */
    private static void handleNoConfiguration(List<DynamicObject> managerAllowanceList,
                                             List<DynamicObject> addOrExpireMgrPostAllowList) {
        if (managerAllowanceList != null) {
            // 连配置都没有了，直接失效职位津贴
            for (DynamicObject managerAllowance : managerAllowanceList) {
                Date endDate = new Date();
                managerAllowance.set(FormConstant.NCKD_ENDDATE, endDate);
                String description = managerAllowance.getString(FormConstant.DESCRIPTION_KEY);
                if (StringUtils.isNotEmpty(description)) {
                    managerAllowance.set(FormConstant.DESCRIPTION_KEY, description + "；" + "不符合【职位津贴条件】，系统自动失效");
                } else {
                    managerAllowance.set(FormConstant.DESCRIPTION_KEY, "不符合【职位津贴条件】，系统自动失效");
                }
                addOrExpireMgrPostAllowList.add(managerAllowance);
            }
        }
    }

    /**
     * 保存变更
     */
    private static void saveChanges(List<DynamicObject> addOrExpireMgrPostAllowList) {
        if (!addOrExpireMgrPostAllowList.isEmpty()) {
            OperateOption option = OperateOption.create();
            // 跳过状态校验
            option.setVariableValue("forceNoAudit","true");
            OperationResult operationResult = SaveServiceHelper.saveOperate(
                    PositionStructureConstant.MANAGERALLOWANCE_ENTITYID,
                    addOrExpireMgrPostAllowList.toArray(new DynamicObject[0]),
                    option);

            if (!operationResult.isSuccess()) {
                StringJoiner errorMsg = new StringJoiner("\n");
                for (IOperateInfo error : operationResult.getAllErrorOrValidateInfo()) {
                    errorMsg.add(error.getMessage());
                }
                if (!ObjectUtils.isEmpty(operationResult.getMessage())) {
                    errorMsg.add(operationResult.getMessage());
                }
                throw new ValidationException("同步【职位津贴管理人员失败】，原因：" + errorMsg.toString());
            }
        }
    }

    /**
     * 获取有效的职位津贴配置
     *
     * @return 有效的职位津贴配置列表
     */
    public static List<DynamicObject> findMgrPostAllowConf() {
        // 查询职位津贴配置条件
        QueryFieldBuilder queryField = QueryFieldBuilder.create().add(FormConstant.ID_KEY);
        QFilter filter = QFilterCommonHelper.getStatusFilter()
                .and(QFilterCommonHelper.getEnableFilter())
                .and(QFilterCommonHelper.getValidDateFilter(FormConstant.NCKD_STARTDATE, FormConstant.NCKD_ENDDATE));
        
        DynamicObjectCollection query = QueryServiceHelper.query(
                PositionStructureConstant.MGRPOSTALLOWCONF_ENTITYID,
                queryField.buildSelect(),
                new QFilter[]{filter});

        // 获取所有ID
        List<Long> ids = new ArrayList<>();
        if (query != null && !query.isEmpty()) {
            ids = query.stream()
                    .map(obj -> obj.getLong(FormConstant.ID_KEY))
                    .collect(Collectors.toList());
        }

        if (ids.isEmpty()) {
            return new ArrayList<>();
        }

        MainEntityType mainEntityType = EntityMetadataCache.getDataEntityType(PositionStructureConstant.MGRPOSTALLOWCONF_ENTITYID);
        DynamicObject[] load = BusinessDataServiceHelper.load(ids.toArray(new Long[0]), mainEntityType);

        return Arrays.asList(load);
    }

    /**
     * 根据ID列表加载并按ID分组行政组织信息
     *
     * @param adminIds 行政组织ID列表
     * @return 按ID分组的行政组织映射
     */
    private static Map<Long, DynamicObject> loadAndGroupAdminOrgs(List<Long> adminIds) {
        if (adminIds.isEmpty()) {
            return new java.util.HashMap<>();
        }

        QueryFieldBuilder adminOrgQueryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.NAME_KEY)
                .add(FormConstant.NUMBER_KEY)
                .addIdNumberName(FormConstant.NCKD_FIRSTORG)
                .addIdNumberName(FormConstant.NCKD_SECONDORG)
                .addIdNumberName(FormConstant.NCKD_THIRDORG)
                .addIdNumberName(FormConstant.NCKD_FOURTHORG)
                .addIdNumberName(FormConstant.NCKD_FIFTHORG)
                .addIdNumberName(FormConstant.NCKD_SIXTHORG);

        // 这里要从数据库加载一下组织，不然没有1、2、3、4、5、6级组织
        DynamicObject[] adminOrgArray = BusinessDataServiceHelper.load(
                FormConstant.ADMINORG_ENTITYID,
                adminOrgQueryFieldBuilder.buildSelect(),
                new QFilter[]{QFilterCommonHelper.getIdInFilter(adminIds)});

        return java.util.Arrays.stream(adminOrgArray)
                .collect(Collectors.toMap(
                        obj -> obj.getLong(FormConstant.ID_KEY),
                        obj -> obj
                ));
    }

    /**
     * 根据ID列表加载并按ID分组职级信息
     *
     * @param jobLevelIds 职级ID列表
     * @return 按ID分组的职级映射
     */
    private static Map<Long, DynamicObject> loadAndGroupJobLevels(List<Long> jobLevelIds) {
        if (jobLevelIds.isEmpty()) {
            return new java.util.HashMap<>();
        }

        QueryFieldBuilder jobLevelQueryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.NAME_KEY)
                .add(FormConstant.NUMBER_KEY)
                .add(FormConstant.JOBLEVELSEQ);

        // 这里要从数据库加载一下职级，不然没有序号
        DynamicObject[] jobLevelArray = BusinessDataServiceHelper.load(
                FormConstant.HBJM_JOBLEVELHR,
                jobLevelQueryFieldBuilder.buildSelect(),
                new QFilter[]{QFilterCommonHelper.getIdInFilter(jobLevelIds)});

        return java.util.Arrays.stream(jobLevelArray)
                .collect(Collectors.toMap(
                        obj -> obj.getLong(FormConstant.ID_KEY),
                        obj -> obj
                ));
    }

    /**
     * 获取人员有效的职位津贴
     *
     * @param personIds 人员ID列表
     * @return 按人员ID分组的职位津贴映射
     */
    private static Map<Long, List<DynamicObject>> loadAndGroupManagerAllowance(List<Long> personIds) {
        if (personIds.isEmpty()) {
            return new java.util.HashMap<>();
        }

        QueryFieldBuilder managerAllowanceQueryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY);

        QFilter qFilter = new QFilter(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY), QCP.in, personIds)
                .and(QFilterCommonHelper.getValidDateFilter(FormConstant.NCKD_STARTDATE, FormConstant.NCKD_ENDDATE));

        DynamicObjectCollection query = QueryServiceHelper.query(
                PositionStructureConstant.MANAGERALLOWANCE_ENTITYID,
                managerAllowanceQueryFieldBuilder.buildSelect(),
                new QFilter[]{qFilter});

        List<Long> ids = query.stream()
                .map(obj -> obj.getLong(FormConstant.ID_KEY))
                .collect(Collectors.toList());

        if (ids.isEmpty()) {
            return new java.util.HashMap<>();
        }

        MainEntityType mainEntityType = EntityMetadataCache.getDataEntityType(PositionStructureConstant.MANAGERALLOWANCE_ENTITYID);
        DynamicObject[] load = BusinessDataServiceHelper.load(ids.toArray(new Long[0]), mainEntityType);

        return Arrays.stream(load)
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY))
                ));
    }

    /**
     * 获取人员所有的职位档案
     *
     * @param personIds 人员ID列表
     * @return 按人员ID分组的职位档案映射
     */
    private static Map<Long, List<DynamicObject>> loadPersonPosFileArchives(List<Long> personIds) {
        if (personIds.isEmpty()) {
            return new java.util.HashMap<>();
        }

        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(PositionStructureConstant.NCKD_PERSON)
                .add(PositionStructureConstant.NCKD_BEGINDATE)
                .add(PositionStructureConstant.NCKD_ADJUSSTATUS)
                .add(PositionStructureConstant.NCKD_DEP)
                .add(PositionStructureConstant.NCKD_JOBLEVELHR)
                .add(PositionStructureConstant.NCKD_JOBSEQHR)
                .add(PositionStructureConstant.NCKD_PROTITLELEVEL)
                .orderDesc(PositionStructureConstant.NCKD_BEGINDATE);

        QFilter qFilter = new QFilter(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY), QCP.in, personIds)
                .and(PositionStructureConstant.NCKD_DISABLE, QCP.equals, EnableEnum.NO.getCode());

        DynamicObject[] load = BusinessDataServiceHelper.load(
                PositionStructureConstant.PERSONPOSFILE_ENTITYID,
                queryFieldBuilder.buildSelect(),
                new QFilter[]{qFilter});

        // 按人员ID分组
        return Arrays.stream(load)
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY))
                ));
    }

    // 内部类定义
    private static class DataIds {
        List<Long> adminIds;
        List<Long> jobLevelIds;
        List<Long> personIds;
    }

    private static class LoadedData {
        List<DynamicObject> mgrPostAllowConfList;
        Map<Long, DynamicObject> adminOrgMap;
        Map<Long, DynamicObject> jobLevelMap;
        Map<Long, List<DynamicObject>> managerAllowanceMap;
        Map<Long, List<DynamicObject>> personPosFileArchivesMap;
    }

    private static class QualificationResult {
        boolean isQualified = false;
        Date beginDate;
        DynamicObject jobLevelObj;
        DynamicObject protitleLeveObj;
    }

    private static class JobLevelMatchResult {
        boolean isMatch = false;
        DynamicObject jobLevelObj;
    }
}