package nckd.jxccl.hr.hstu.business.helper;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
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.enums.AppraisalResultEnum;
import nckd.jxccl.base.common.enums.PerfPlanRoleEnum;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hr.hstu.business.algo.RankMapFunction;
import nckd.jxccl.hr.hstu.business.algo.UnitRankMapFunction;
import nckd.jxccl.hr.hstu.common.HonorStudentConstant;
import nckd.jxccl.hr.hstu.common.bo.EvalQuestResultBO;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
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/7/23 16:18
* @version 1.0
*/
public class HonorStudentHelper {

    private static final Log logger = LogFactory.getLog(HonorStudentHelper.class);

    /**
     * 获取地区差异分（从当前组织向上找最近的一个组织）
     * @param orgId 组织ID
     * @return: java.lang.Integer
     * @author W.Y.C
     * @date: 2025/07/23 15:50
     */
    public static Integer getOrgDifference(Long orgId) {
        //获取组织上下级结构长编码
        DynamicObject adminOrgHr = BusinessDataServiceHelper.loadSingle(FormConstant.ADMINORG_ENTITYID, FormConstant.STRUCTLONGNUMBER, new QFilter[]{QFilterCommonHelper.getIdEqFilter(orgId)});
        String structLongNumber = adminOrgHr.getString(FormConstant.STRUCTLONGNUMBER);
        String[] structLongNumbers = structLongNumber.split("!");

        QFilter[] filters = new QFilter[]{
                new QFilter(HonorStudentConstant.NCKD_ORG+"."+FormConstant.STRUCTLONGNUMBER, QCP.in, Arrays.asList(structLongNumbers)),
                new QFilter(HonorStudentConstant.NCKD_ORG+"."+FormConstant.IS_CURRENT_VERSION, QCP.equals, EnableEnum.YES.getCode()),
                new QFilter(HonorStudentConstant.NCKD_ORG+"."+FormConstant.DATA_STATUS, QCP.equals, EnableEnum.YES.getCode()),
                new QFilter(HonorStudentConstant.NCKD_ORG+"."+FormConstant.ENABLE, QCP.equals, EnableEnum.YES.getCode()),
                new QFilter(HonorStudentConstant.NCKD_ORG+"."+FormConstant.STATUS, QCP.equals, StatusEnum.C.toString())
        };
        DynamicObject[] load = BusinessDataServiceHelper.load(HonorStudentConstant.ORGDIFFERENCE_ENTITYID, HonorStudentConstant.NCKD_DIFFERENCESCORE, filters,"nckd_org.level desc");
        return load.length > 0 ? load[0].getInt(HonorStudentConstant.NCKD_DIFFERENCESCORE) : null;
    }
    /**
     * 统计问卷已评分人数
     * @param evalQuestId 问卷ID
     * @return: java.lang.Integer
     * @author W.Y.C
     * @date: 2025/07/23 16:53
     */
    public static Integer getQuestScorePersonCount(Long evalQuestId) {
        QFilter[] filters = new QFilter[]{
                new QFilter(HonorStudentConstant.NCKD_PERFPLANSTATE, QCP.in, Lists.newArrayList("2")),
                new QFilter(HonorStudentConstant.NCKD_EVALQUEST, QCP.equals, evalQuestId),
        };
        DynamicObject dynamicObject = QueryServiceHelper.queryOne(HonorStudentConstant.NCKD_EVALRESULT_ENTITYID, "count(id) as count", filters);
        return dynamicObject.getInt("count");
    }

    /**
     * 问卷未评分人数
     * @param evalQuestId 问卷ID
     * @return: java.lang.Integer
     * @author W.Y.C
     * @date: 2025/07/23 16:53
     */
    public static Integer getQuestNotScorePersonCount(Long evalQuestId) {
        QFilter[] filters = new QFilter[]{
                new QFilter(HonorStudentConstant.NCKD_PERFPLANSTATE, QCP.in, Lists.newArrayList("0", "1")),
                new QFilter(HonorStudentConstant.NCKD_EVALQUEST, QCP.equals, evalQuestId),
        };
        DynamicObject dynamicObject = QueryServiceHelper.queryOne(HonorStudentConstant.NCKD_EVALRESULT_ENTITYID, "count(id) as count", filters);
        return dynamicObject.getInt("count");
    }

    /**
     * 根据问卷查询未评分人员
     * @param evalQuestIds 问卷ID（支持多个）
     * @return: kd.bos.dataentity.entity.DynamicObject[]
     * @author W.Y.C
     * @date: 2025/07/23 20:53
     */
    public static DynamicObject[] getQuestNotScorePerson(Long... evalQuestIds) {
        QFilter[] filters = new QFilter[]{
                new QFilter(HonorStudentConstant.NCKD_PERFPLANSTATE, QCP.in, Lists.newArrayList("0", "1")),
                new QFilter(HonorStudentConstant.NCKD_EVALQUEST, QCP.in, Arrays.asList(evalQuestIds)),
        };
        StringJoiner fields = new StringJoiner(",");
        fields.add(FormConstant.ID_KEY);
        //评价对象
        fields.add(HonorStudentConstant.NCKD_PERSON+"."+FormConstant.PERSON+"."+FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_PERSON+"."+FormConstant.PERSON+"."+FormConstant.NUMBER_KEY);
        fields.add(HonorStudentConstant.NCKD_PERSON+"."+FormConstant.PERSON+"."+FormConstant.NAME_KEY);
        //评分人
        fields.add(HonorStudentConstant.NCKD_SCORER+"."+FormConstant.PERSON+"."+FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_SCORER+"."+FormConstant.PERSON+"."+FormConstant.NUMBER_KEY);
        fields.add(HonorStudentConstant.NCKD_SCORER+"."+FormConstant.PERSON+"."+FormConstant.NAME_KEY);
        return BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_EVALRESULT_ENTITYID, fields.toString(), filters);
    }

    /**
     * 更新问卷测评结果（同级评分人数、上级评分人数、上级评分人数、同级评分总分、上级评分总分、领导评分总分、已评分总分、已评分人数、未评分人数、不了解人数、绩效得分、业绩贡献分、综合测评得分、更新排名、定格等级）
     * @param evalQuestIds 问卷ID（支持多个）
     * @return: void
     * @author W.Y.C
     * @date: 2025/08/07 19:48
     */
    public static void updateQuestResult(Long... evalQuestIds) {
        logger.info("【优秀生考评】-更新问卷测评结果-开始，问卷ID：{}", Arrays.toString(evalQuestIds));
        QFilter[] filters = new QFilter[]{
                //new QFilter(HonorStudentConstant.NCKD_PERFPLANSTATE, QCP.equals, "2"),
                new QFilter(FormConstant.ID_KEY, QCP.in, evalQuestIds),
        };
        StringJoiner fields = new StringJoiner(",");
        fields.add(FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_PERFSCORESPART);
        fields.add(HonorStudentConstant.NCKD_PEEK);
        fields.add(HonorStudentConstant.NCKD_SUPERIOR);
        fields.add(HonorStudentConstant.NCKD_LEAD);
        fields.add(HonorStudentConstant.NCKD_PEEKSCORESSUM);
        fields.add(HonorStudentConstant.NCKD_SUPERIORSCORESSUM);
        fields.add(HonorStudentConstant.NCKD_LEADSCORESSUM);
        fields.add(HonorStudentConstant.NCKD_SUMENTRYSCORE);
        fields.add(HonorStudentConstant.NCKD_HAVEDO);
        fields.add(HonorStudentConstant.NCKD_NODO);
        fields.add(HonorStudentConstant.NCKD_UNCLEARS);
        fields.add(HonorStudentConstant.NCKD_SUMSCORE);
        fields.add(HonorStudentConstant.NCKD_DIFFERENCESCORE);
        fields.add(HonorStudentConstant.NCKD_ALLYEARSCORESUM);
        fields.add(HonorStudentConstant.NCKD_TOPRANKSCORE);
        //获取评价对象组织
        fields.add(HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.ADMINORG+"."+FormConstant.ID_KEY);
        //-------------------------- 评价规则数据 begin--------------------------
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
        //所属年度
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_BIZYEAR);
        //领导评分权重占比
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_LEADPROPORTION);
        //上级评分权重占比
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_SUPERIORRATIO);
        //同级评分权重占比
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_PEEKPROPORTION);
        //综合测评权重占比
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_PERFPROPORTION);
        //综合测评封顶分
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_PERFMAX);
        //优秀评优排名基准（%）
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_COMMARKPERCENTAGE);
        //所在单位评优排名基准（%）
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_HRMARKPERCENTAGE);
        //-------------------------- 评价规则数据 end--------------------------
        //查询需要生成结果的问卷数据
        DynamicObject[] evalQuestArray = BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_EVALQUEST_ENTITYID, fields.toString(), filters);
        //记录问卷中的评价活动（key：评价活动ID，Value：评价活动对象）
        Map<Long,DynamicObject> evaluationRuleMap = new HashMap<>();
        //=================================== 1.获取考评结果 ===================================
        //同级评分人数、上级评分人数、上级评分人数、同级评分总分、上级评分总分、领导评分总分、已评分总分、已评分人数、未评分人数、不了解人数
        Map<Long, EvalQuestResultBO> scoreResults = calculateScore(evalQuestIds);
        logger.info("【优秀生考评】-更新问卷测评结果-同级评分人数、上级评分人数、上级评分人数、同级评分总分、上级评分总分、领导评分总分、已评分总分、已评分人数、未评分人数、不了解人数：{}", JSON.toJSONString(scoreResults));
        for (DynamicObject evalQuest : evalQuestArray) {
            //NOTE: 原SHR逻辑有重新更新地区差异分（本次不更新，原因：生成问卷时已经赋值）

            DynamicObject evaluationRule = evalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE);
            long evaluationRuleId = evaluationRule.getLong(FormConstant.ID_KEY);
            evaluationRuleMap.put(evaluationRuleId, evaluationRule);

            long evalQuestId = evalQuest.getLong(FormConstant.ID_KEY);
            EvalQuestResultBO evalQuestResult = scoreResults.get(evalQuestId);
            //=================================== 2.计算综合测评得分 并 更新 问卷综合测评得分 ===================================
            double score = evalQuestResult.calculateComprehensiveScore(evaluationRule.getInt(HonorStudentConstant.NCKD_LEADPROPORTION),
                    evaluationRule.getInt(HonorStudentConstant.NCKD_SUPERIORRATIO),
                    evaluationRule.getInt(HonorStudentConstant.NCKD_PEEKPROPORTION),
                    evaluationRule.getInt(HonorStudentConstant.NCKD_PERFPROPORTION),
                    evaluationRule.getInt(HonorStudentConstant.NCKD_PERFMAX));
            logger.info("【优秀生考评】-更新问卷测评结果-计算综合测评得分：{}，问卷ID：{}，规则ID：{}", score,evalQuestId,evaluationRuleId);
            //设置综合测评得分
            evalQuest.set(HonorStudentConstant.NCKD_PERFSCORESPART, score);

            //同级评分人数
            evalQuest.set(HonorStudentConstant.NCKD_PEEK, evalQuestResult.getPeerRatingCount());
            //上级评分人数
            evalQuest.set(HonorStudentConstant.NCKD_SUPERIOR, evalQuestResult.getSuperiorRatingCount());
            //同级评分总分
            evalQuest.set(HonorStudentConstant.NCKD_LEAD, evalQuestResult.getLeaderRatingCount());
            //同级评分总分
            evalQuest.set(HonorStudentConstant.NCKD_PEEKSCORESSUM, evalQuestResult.getPeerRatingTotal());
            //上级评分总分
            evalQuest.set(HonorStudentConstant.NCKD_SUPERIORSCORESSUM, evalQuestResult.getSuperiorRatingTotal());
            //领导评分总分
            evalQuest.set(HonorStudentConstant.NCKD_LEADSCORESSUM, evalQuestResult.getLeaderRatingTotal());
            //已评分总分
            evalQuest.set(HonorStudentConstant.NCKD_SUMENTRYSCORE, evalQuestResult.getRatedTotal());
            //已评分人数
            evalQuest.set(HonorStudentConstant.NCKD_HAVEDO, evalQuestResult.getRatedCount());
            //未评分人数
            evalQuest.set(HonorStudentConstant.NCKD_NODO, evalQuestResult.getUnratedPersonnel());
            //不了解人数
            evalQuest.set(HonorStudentConstant.NCKD_UNCLEARS, evalQuestResult.getNotUnderstandCount());

            /*TODO 3.计算员工绩效得分（需要取绩效排名，待职位体系开发之后补充这部分逻辑），参考SHR：OrginsPerfPlanListHandler.gettoprankscore
            影响字段：nckd_toprankscore（员工绩效得分）
            具体计算逻辑：
            取当前考评年上一年的绩效排名结果，计算公式：
                1.计算该分组中的总人数
                2.用排名除以总人数，得到排名比例
                3.用1减去排名比例（确保排名越靠前（数字越小），得分应该越高）
                4.乘以100得到最终得分
                例子
                    假设某组有10个人，某个员工排名第3：
                    排名比例 = 3/10 = 0.3
                    得分 = (1 - 0.3) * 100 = 70分
             */


            /*TODO 4.计算业绩贡献分（需要取年度贡献分，待职位体系开发之后补充这部分逻辑），参考SHR：OrginsPerfPlanListHandler.getallyearscoresum
            影响字段：nckd_allyearscoresum（业绩贡献分）
            取当前考评年上一年的绩效排名结果，具体计算过程：
                按类型分组统计每类得分总和
                对有上限的类型应用分数限制（如A类超过60分按60分计算）
                对无上限类型保持原得分
              第二步：特殊规则处理
                对于有科研与创新类(A类)得分的情况，还需要根据获奖级别进行额外限制：
                1.统计不同级别的获奖情况：
                    国家级(gj)
                    省部级(sb)
                    公司级(gs)
                2.应用特殊规则：
                    如果只有公司级奖项且科研创新分超过20分，则限制为20分
                    如果只有省部级奖项且科研创新分超过40分，则限制为40分
              第三步：返回总分
                最终得分 = 科研与创新类得分 + 其他类别总分

              分数限制
                1. **A类（科研与创新）**：上限60分
                2. **B类（专利申报）**：上限10分
                3. **C类（论文发表）**：上限2分
                4. **E类（培训教材）**：上限5分
                5. **G类（管理规范）**：上限15分
                6. **H类（师带徒）**：上限6分
                7. **I类（培训授课）**：上限5分
                以下单据类型**没有**分数上限限制：
                    - **D类（技能竞赛）**
                    - **F类（技术标准）**
                此外，对于A类（科研与创新）还有额外的特殊规则限制：
                    - 如果员工只有公司级奖项，且该类得分超过20分，则限制为20分
                    - 如果员工只有省部级奖项，且该类得分超过40分，则限制为40分
             */

            //=================================== 4.计算优秀生评价积分 ===================================
            // 计算公式：nckd_differencescore（地区差异分）+nckd_allyearscoresum（业绩贡献分）+nckd_toprankscore（员工绩效得分）+nckd_perfscorespart（综合测评得分）
            int differenceScore = evalQuest.getInt(HonorStudentConstant.NCKD_DIFFERENCESCORE);
            int allYearScoreSum = evalQuest.getInt(HonorStudentConstant.NCKD_ALLYEARSCORESUM);
            int topRankScore = evalQuest.getInt(HonorStudentConstant.NCKD_TOPRANKSCORE);
            int perfScoresPart = evalQuest.getInt(HonorStudentConstant.NCKD_PERFSCORESPART);
            evalQuest.set(HonorStudentConstant.NCKD_SUMSCORE, differenceScore+allYearScoreSum+topRankScore+perfScoresPart);
            logger.info("【优秀生考评】-更新问卷测评结果-计算优秀生评价积分-问卷ID：{}，规则ID：{}，地区差异分：{}，业绩贡献分：{}，员工绩效得分：{}，综合测评得分：{}", evalQuestId,evaluationRuleId,differenceScore,allYearScoreSum,topRankScore,perfScoresPart);

        }
        SaveServiceHelper.save(evalQuestArray);

        //=================================== 5.《更新排名》和《定格等级》（注：全员更新，即同一个评测活动下的问卷都会更新） ===================================
        Set<Long> evaluationRuleIds = evaluationRuleMap.keySet();
        //获取排名结果（key：问卷ID，value：问卷排名结果  ）
        Map<Long, EvalQuestResultBO> rankingResultMap = getRankingResult(evaluationRuleIds.toArray(new Long[0]));
        logger.info("【优秀生考评】-更新问卷测评结果-排名结果：{}",JSON.toJSONString(rankingResultMap));
        //获取需要更新排名的问卷（按评测活动获取）
        String join = String.join(",", FormConstant.ID_KEY,
                HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.ID_KEY,
                HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY,
                HonorStudentConstant.NCKD_EVALUATIONRULE+"."+HonorStudentConstant.NCKD_BIZYEAR,
                HonorStudentConstant.NCKD_COMPERSONS,
                HonorStudentConstant.NCKD_HRPERSONS,
                HonorStudentConstant.NCKD_COMRANKING,
                HonorStudentConstant.NCKD_HRRANKING,
                HonorStudentConstant.NCKD_RANKINGANDCOM,
                HonorStudentConstant.NCKD_RANKINGANDHR,
                HonorStudentConstant.NCKD_COMPERCENTAGE,
                HonorStudentConstant.NCKD_HRPERCENTAGE,
                HonorStudentConstant.NCKD_APPRAISALRESULT);
        //根据评测活动获取所有问卷
        DynamicObject[] allEvalQuestArray = BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_EVALQUEST_ENTITYID, join, new QFilter[]{QFilterCommonHelper.getIdInFilter(new ArrayList<>(rankingResultMap.keySet()))});

        //获取考核结果基础数据（用于定格等级的基础数据）
        DynamicObject[] appraisalResultList = BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_APPRAISALRESULT_ENTITYID,
                String.join(",", FormConstant.ID_KEY,FormConstant.NUMBER_KEY),
                new QFilter[]{new QFilter(FormConstant.NUMBER_KEY, QCP.in, Arrays.asList(AppraisalResultEnum.EXCELLENT.getCode(),AppraisalResultEnum.QUALIFIED.getCode(),AppraisalResultEnum.UN_QUALIFIED.getCode()))});
        //优秀
        DynamicObject excellent = null;
        //合格
        DynamicObject qualified = null;
        //不合格
        DynamicObject unQualified = null;
        for (DynamicObject appraisalResult : appraisalResultList) {
            String number = appraisalResult.getString(FormConstant.NUMBER_KEY);
            if (AppraisalResultEnum.EXCELLENT.getCode().equals(number)) {
                excellent = appraisalResult;
            } else if (AppraisalResultEnum.QUALIFIED.getCode().equals(number)) {
                qualified = appraisalResult;
            } else if (AppraisalResultEnum.UN_QUALIFIED.getCode().equals(number)) {
                unQualified = appraisalResult;
            }
        }
        if(excellent == null || qualified == null || unQualified == null){
            logger.warn("【优秀生考评】-更新问卷测评结果：未找到优秀、合格或不合格等级基础数据，请检查是否配置了（01：优秀，02：合格，04：不合格）考评结果");
            throw new ValidationException("未找到优秀、合格或不合格等级基础数据，请检查是否配置了（01：优秀，02：合格，04：不合格）考评结果");
        }

        //---------------------- 获取员工上年度考核结果 ----------------------
        //key为："人员ID-考核年份"，value：为考核结果编号
        Map<String, String> lastYearEvaluationResult = getLastYearAssessmentResult(allEvalQuestArray);
        logger.info("【优秀生考评】-更新问卷测评结果-上年度考核结果：{}",JSON.toJSONString(lastYearEvaluationResult));

        for (DynamicObject allEvalQuest : allEvalQuestArray) {

            EvalQuestResultBO evalQuestResult = rankingResultMap.get(allEvalQuest.getLong(FormConstant.ID_KEY));
            //有积分得才排名
            if(evalQuestResult.getSumScore() != null && evalQuestResult.getSumScore() > 0) {
                allEvalQuest.set(HonorStudentConstant.NCKD_COMPERSONS,evalQuestResult.getComPersons());
                allEvalQuest.set(HonorStudentConstant.NCKD_HRPERSONS,evalQuestResult.getHrPersons());
                allEvalQuest.set(HonorStudentConstant.NCKD_COMRANKING,evalQuestResult.getComRanking());
                allEvalQuest.set(HonorStudentConstant.NCKD_HRRANKING,evalQuestResult.getHrRanking());
                allEvalQuest.set(HonorStudentConstant.NCKD_RANKINGANDCOM,evalQuestResult.getComRanking()+"/"+evalQuestResult.getComPersons());
                allEvalQuest.set(HonorStudentConstant.NCKD_RANKINGANDHR,evalQuestResult.getHrRanking()+"/"+evalQuestResult.getHrPersons());

                /*定格等级
                    1.获取该员工上年度绩效考核结果，如果为【基本合格】或【不合格】定格为：不合格
                    2.计算公司排名百分比和所在单位排名百分比
                        公司排名百分比 = (公司排名 / 公司总人数) * 100%
                        所在单位排名百分比 = (所在单位排名 / 所在单位总人数) * 100%
                    3.判断是否符合排名基准
                        如果：（评价规则.优秀评优排名基准（%） >= 公司排名百分比 并且 评价规则.所在单位评优排名基准（%） >= 所在单位排名百分比）=优秀
                        否则：合格
                 */
                //公司排名百分比
                Double comPercentage = evalQuestResult.calculateComPercentage();
                allEvalQuest.set(HonorStudentConstant.NCKD_COMPERCENTAGE, comPercentage != 0 ? Math.round(comPercentage) + "%" : null);
                //所在单位排名百分比
                Double hrPercentage = evalQuestResult.calculateHrPercentage();
                allEvalQuest.set(HonorStudentConstant.NCKD_HRPERCENTAGE, hrPercentage != 0 ? Math.round(hrPercentage) + "%" : null);

                Long evaluationRuleId = evalQuestResult.getEvaluationRuleId();
                DynamicObject evaluationRule = evaluationRuleMap.get(evaluationRuleId);
                //优秀评优排名基准（%）
                int commArkPercentage = evaluationRule.getInt(HonorStudentConstant.NCKD_COMMARKPERCENTAGE);
                //所在单位评优排名基准（%）
                int hrmArkPercentage = evaluationRule.getInt(HonorStudentConstant.NCKD_HRMARKPERCENTAGE);

                //上年度绩效考核结果
                long personId = allEvalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getLong(FormConstant.ID_KEY);
                Date yearDate = allEvalQuest.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getDate(HonorStudentConstant.NCKD_BIZYEAR);
                LocalDateTime lastYear = DateUtil.minusYears(DateUtil.toLocalDateTime(yearDate), 1);
                int year = DateUtil.getYear(lastYear);
                String appraisalResultNumber = lastYearEvaluationResult.get(personId + "-" + year);
                //定格等级
                if(StringUtils.isNotBlank(appraisalResultNumber) && StringUtils.equalsAny(appraisalResultNumber,AppraisalResultEnum.BASICALLY_QUALIFIED.getCode(),AppraisalResultEnum.UN_QUALIFIED.getCode())) {
                    //不合格
                    allEvalQuest.set(HonorStudentConstant.NCKD_APPRAISALRESULT, unQualified);
                }else if (commArkPercentage >= comPercentage && hrmArkPercentage >= hrPercentage) {
                    //优秀
                    allEvalQuest.set(HonorStudentConstant.NCKD_APPRAISALRESULT, excellent);
                } else {
                    //合格
                    allEvalQuest.set(HonorStudentConstant.NCKD_APPRAISALRESULT, qualified);
                }
            }else{
                allEvalQuest.set(HonorStudentConstant.NCKD_COMPERSONS,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_HRPERSONS,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_COMRANKING,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_HRRANKING,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_RANKINGANDCOM,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_RANKINGANDHR,null);
                allEvalQuest.set(HonorStudentConstant.NCKD_COMPERCENTAGE, null);
                allEvalQuest.set(HonorStudentConstant.NCKD_HRPERCENTAGE, null);
                allEvalQuest.set(HonorStudentConstant.NCKD_APPRAISALRESULT, null);
            }
        }
        SaveServiceHelper.save(allEvalQuestArray);
        logger.info("【优秀生考评】-更新问卷测评结果-结束");
    }

    /**
     * 获取上一年度考评结果
     * @param allEvalQuestArray 需要获取年度考评的问卷
     * @return: java.util.Map<java.lang.String, java.lang.String> key为"人员ID-考核年份"，value为考核结果编号
     * @author W.Y.C
     * @date: 2025/08/13 16:19
     */
    private static Map<String, String> getLastYearAssessmentResult(DynamicObject[] allEvalQuestArray) {
        //获取本次计算的所有评测活动和年份
        List<Map<String, Object>> allEvaluationRuleList = Arrays.stream(allEvalQuestArray)
                .map(dynamicObject -> {
                    Map<String, Object> info = new HashMap<>();
                    info.put("evalRuleId", dynamicObject.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getLong(FormConstant.ID_KEY));
                    info.put("bizYear", dynamicObject.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getDate(HonorStudentConstant.NCKD_BIZYEAR));
                    return info;
                }).distinct().collect(Collectors.toList());
        //构建查询年度绩效结果的查询条件
        List<QFilter> perfManagerFilterList = new ArrayList<>(allEvaluationRuleList.size());
        for (Map<String, Object> allEvaluationRule : allEvaluationRuleList) {
            Long evalRuleId = ConvertUtil.toLong(allEvaluationRule.get("evalRuleId"));
            Date bizYear = ConvertUtil.toDate(allEvaluationRule.get("bizYear"));
            // 减一年获取上年度考核结果
            Date lastYearBizYear = DateUtil.toDate(DateUtil.minusYears(DateUtil.toLocalDateTime(bizYear), 1));
            LocalDateTime beginYear = DateUtil.beginOfYear(DateUtil.toLocalDateTime(lastYearBizYear));
            LocalDateTime ednYear = DateUtil.endOfYear(DateUtil.toLocalDateTime(lastYearBizYear));

            List<Long> personIds = Arrays.stream(allEvalQuestArray).filter(d -> d.getDynamicObject(HonorStudentConstant.NCKD_EVALUATIONRULE).getLong(FormConstant.ID_KEY) == evalRuleId)
                    .map(dynamicObject -> dynamicObject.getDynamicObject(HonorStudentConstant.NCKD_EVALPERSON).getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
            QFilter filter = new QFilter(HonorStudentConstant.NCKD_PERSON, QCP.in, personIds)
                    .and(new QFilter(FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.NCKD_APPRAISALYEAR, QCP.large_equals, beginYear)
                            .and(new QFilter(FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.NCKD_APPRAISALYEAR, QCP.less_equals, ednYear))
                    );
            perfManagerFilterList.add(filter);
        }

        QFilter perfManagerFilter = null;
        for (QFilter filter : perfManagerFilterList) {
            if(perfManagerFilter == null){
                perfManagerFilter = filter;
            }else{
                perfManagerFilter = perfManagerFilter.or(filter);
            }
        }
        DynamicObjectCollection perfManagerArray = QueryServiceHelper.query(HonorStudentConstant.NCKD_PERFMANAGER_ENTITYID,
                String.join(",", HonorStudentConstant.NCKD_PERSON,
                        FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.APPRAISAL_YEAR_KEY,
                        FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.NCKD_APPRAISALRESULT,
                        FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.NCKD_APPRAISALRESULT+"."+FormConstant.NUMBER_KEY),
                new QFilter[]{perfManagerFilter});
        // 创建映射关系：key为"人员ID-考核年份"，value为考核结果编号
        Map<String, String> appraisalResultMap = new HashMap<>();
        for (DynamicObject perfManager : perfManagerArray) {
            Long personId = perfManager.getLong(HonorStudentConstant.NCKD_PERSON);
            String appraisalResultNumber = perfManager.getString(FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.NCKD_APPRAISALRESULT+"."+FormConstant.NUMBER_KEY);
            Date yearDate = perfManager.getDate(FormConstant.ENTRY_ENTITY_KEY+"."+HonorStudentConstant.APPRAISAL_YEAR_KEY);
            int year = DateUtil.getYear(yearDate);
            if (StringUtils.isNotBlank(appraisalResultNumber)) {
                appraisalResultMap.put(personId + "-" + year, appraisalResultNumber);
            }
        }
        return appraisalResultMap;
    }

    /**
     * 获取排名结果<br/>
     * 1.根据评测活动获取排名人数<br/>
     * 2.根据评测活动+单位获取排名人数<br/>
     * 3.根据评测活动按优秀生积分确定各问卷排名<br/>
     * 4.根据评测活动+单位按优秀生积分确定各问卷排名<br/>
     * @param evaluationRuleIds 评价规则ID（支持多个）
     * @return: java.util.Map<Long, EvalQuestResultBO> 返回评价活动内的所有问卷排名结果。key：问卷ID，value：问卷排名结果
     * @author W.Y.C
     * @date: 2025/08/09 14:46
     */
    public static Map<Long,EvalQuestResultBO> getRankingResult(Long... evaluationRuleIds) {
        QFilter[] filters = new QFilter[] {
                new QFilter(HonorStudentConstant.NCKD_EVALUATIONRULE, QCP.in, evaluationRuleIds)
        };
        StringJoiner fields = new StringJoiner(",");
        fields.add(FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
        //所属单位
        fields.add(HonorStudentConstant.USEORG_KEY+"."+FormConstant.ID_KEY);
        //优秀生评价积分
        fields.add(HonorStudentConstant.NCKD_SUMSCORE);
        //测评状态
        fields.add(HonorStudentConstant.NCKD_PERIODSTATE);
        Map<Long, EvalQuestResultBO> resultMap = new HashMap<>();
        //根据评价规则查询所有问卷
        try(DataSet dataSet = QueryServiceHelper.queryDataSet(HonorStudentHelper.class.getName(), HonorStudentConstant.NCKD_EVALQUEST_ENTITYID,
                fields.toString(), filters,
                HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY+","+HonorStudentConstant.USEORG_KEY+"."+FormConstant.ID_KEY+","+HonorStudentConstant.NCKD_SUMSCORE + " desc")){

            //获取评测活动所有问卷。key：评测活动id，value：对应问卷ID
            Map<Long,List<Long>> evalQuestMap = new HashMap<>();
            DataSet allDataSet = dataSet.copy();
            while (allDataSet.hasNext()) {
                Row row = allDataSet.next();
                Long id = row.getLong(FormConstant.ID_KEY);
                Long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
                List<Long> evalQuestIdList = evalQuestMap.computeIfAbsent(evaluationRuleId, k -> new ArrayList<>());
                evalQuestIdList.add(id);
            }
            try (DataSet dsCount = dataSet.copy()
                    .filter(HonorStudentConstant.NCKD_PERIODSTATE+" <> '4'")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY})
                    .count()
                    .finish()) {
                //获取公司（评价活动维度）总排名人数
                while (dsCount.hasNext()) {
                    Row row = dsCount.next();
                    Long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
                    Integer comPersons = row.getInteger("count");

                    List<Long> evalQuestIdList = evalQuestMap.get(evaluationRuleId);
                    for (Long evalQuestId : evalQuestIdList) {
                        //设置当前评测活动所有公司排名人数
                        EvalQuestResultBO evalQuestResult = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                        evalQuestResult.setComPersons(comPersons);
                        evalQuestResult.setEvaluationRuleId(evaluationRuleId);
                    }
                }
            }
            try (DataSet dsCount = dataSet.copy()
                    .filter(HonorStudentConstant.NCKD_PERIODSTATE+" <> '4'")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY,HonorStudentConstant.USEORG_KEY+"."+FormConstant.ID_KEY})
                    .count()
                    .finish()) {
                //获取单位（评价活动+单位维度）总排名人数
                while (dsCount.hasNext()) {
                    Row row = dsCount.next();
                    Long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
                    Long useOrg = row.getLong(HonorStudentConstant.USEORG_KEY+"."+FormConstant.ID_KEY);
                    Integer perfScores = row.getInteger("count");

                    List<Long> evalQuestIdList = evalQuestMap.get(evaluationRuleId);
                    for (Long evalQuestId : evalQuestIdList) {
                        //设置当前评测活动所有单位排名人数
                        EvalQuestResultBO evalQuestResult = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                        evalQuestResult.setHrPersons(perfScores);
                        evalQuestResult.setEvaluationRuleId(evaluationRuleId);
                    }
                }
            }
            //按公司（评价活动维度）排名
            DataSet rankDataSet = dataSet.copy();
            rankDataSet = rankDataSet.map(new RankMapFunction(dataSet.getRowMeta()));
            while (rankDataSet.hasNext()) {
                Row row = rankDataSet.next();
                Long id = row.getLong(FormConstant.ID_KEY);
                long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
                Integer sumScore = row.getInteger(HonorStudentConstant.NCKD_SUMSCORE);
                Integer rank = row.getInteger("rank");

                EvalQuestResultBO evalQuestResult = resultMap.computeIfAbsent(id, k -> new EvalQuestResultBO());
                evalQuestResult.setSumScore(sumScore);
                evalQuestResult.setComRanking(rank);
                evalQuestResult.setEvaluationRuleId(evaluationRuleId);
            }

            //按单位（评价活动+单位维度）排名
            DataSet unitRankDataSet = dataSet.copy();
            unitRankDataSet = unitRankDataSet.map(new UnitRankMapFunction(dataSet.getRowMeta()));
            while (unitRankDataSet.hasNext()) {
                Row row = unitRankDataSet.next();
                Long id = row.getLong(FormConstant.ID_KEY);
                long evaluationRuleId = row.getLong(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
                Integer useOrgId = row.getInteger(HonorStudentConstant.USEORG_KEY+"."+FormConstant.ID_KEY);
                Integer sumScore = row.getInteger(HonorStudentConstant.NCKD_SUMSCORE);
                Integer rank = row.getInteger("rank");

                EvalQuestResultBO evalQuestResult = resultMap.computeIfAbsent(id, k -> new EvalQuestResultBO());
                evalQuestResult.setSumScore(sumScore);
                evalQuestResult.setHrRanking(rank);
                evalQuestResult.setEvaluationRuleId(evaluationRuleId);
            }
        }

        return resultMap;



    }

    /**
     * 计算考评结果（同级评分人数、上级评分人数、上级评分人数、同级评分总分、上级评分总分、领导评分总分、已评分总分、已评分人数、未评分人数、不了解人数）
     * @param evalQuestIds 问卷ID（支持多个）
     * @return: java.util.Map<Long, nckd.jxccl.hr.hstu.common.dto.EvalQuestResultDTO>
     * @author W.Y.C
     * @date: 2025/08/06 22:23
     */
    public static Map<Long, EvalQuestResultBO> calculateScore(Long... evalQuestIds) {
        if(evalQuestIds == null || evalQuestIds.length == 0){
            return new HashMap<>();
        }
        QFilter[] filters = new QFilter[]{
                //new QFilter(HonorStudentConstant.NCKD_PERFPLANSTATE, QCP.equals, "2"),
                new QFilter(HonorStudentConstant.NCKD_EVALQUEST, QCP.in, evalQuestIds),
        };

        StringJoiner selectFields = new StringJoiner(",");
        //答卷ID
        selectFields.add(FormConstant.ID_KEY);
        //问卷ID
        selectFields.add(HonorStudentConstant.NCKD_EVALQUEST);
        //问卷分录ID
        selectFields.add(HonorStudentConstant.NCKD_EVALQUESTENTRY);
        //评分状态
        selectFields.add(HonorStudentConstant.NCKD_PERFPLANSTATE);
        //评分人
        selectFields.add(HonorStudentConstant.NCKD_SCORER);
        //不了解
        selectFields.add(HonorStudentConstant.NCKD_UNCLEAR);
        //评分角色
        selectFields.add(StrFormatter.format("{}.{} as {}",HonorStudentConstant.NCKD_EVALQUESTENTRY,HonorStudentConstant.NCKD_PERFPLANROLE,HonorStudentConstant.NCKD_PERFPLANROLE));
        //评分分数
        selectFields.add(StrFormatter.format("{}.{} as {}",HonorStudentConstant.NCKD_EVALRESULTENTRY,HonorStudentConstant.NCKD_PERFSCORES,HonorStudentConstant.NCKD_PERFSCORES));
        Map<Long, EvalQuestResultBO> resultMap = new HashMap<>(evalQuestIds.length);
        try(DataSet dataSet = QueryServiceHelper.queryDataSet(HonorStudentHelper.class.getName(), HonorStudentConstant.NCKD_EVALRESULT_ENTITYID, selectFields.toString(), filters, null)){
            //统计：同级评分人数、上级评分人数、领导评分人数。统计条件：已评分 并且 非不了解
            try (DataSet dsCount = dataSet.copy()
                    .filter(HonorStudentConstant.NCKD_PERFPLANSTATE+" = '2' and "+HonorStudentConstant.NCKD_UNCLEAR+" = false")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST,HonorStudentConstant.NCKD_SCORER,HonorStudentConstant.NCKD_PERFPLANROLE})
                    .count()
                    .finish()) {
                try(DataSet numberCount = dsCount.copy()
                        .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST,HonorStudentConstant.NCKD_PERFPLANROLE})
                        .count()
                        .finish()){
                    while (numberCount.hasNext()) {
                        Row row = numberCount.next();
                        Long evalQuestId = row.getLong(HonorStudentConstant.NCKD_EVALQUEST);
                        String perfPlanRole = row.getString(HonorStudentConstant.NCKD_PERFPLANROLE);
                        Integer perfScores = row.getInteger("count");

                        EvalQuestResultBO evalQuestResultBO = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                        if(perfPlanRole.equals(PerfPlanRoleEnum.PEERS.getCode())){
                            //同级评分人数
                            evalQuestResultBO.addPeerRatingCount(perfScores);
                        }else if(perfPlanRole.equals(PerfPlanRoleEnum.SUPERIOR.getCode())){
                            //上级评分人数
                            evalQuestResultBO.addSuperiorRatingCount(perfScores);
                        }else if(perfPlanRole.equals(PerfPlanRoleEnum.LEAD.getCode())){
                            //领导评分人数
                            evalQuestResultBO.addLeaderRatingCount(perfScores);
                        }
                    }
                }

            }
            //统计：同级评分总分、上级评分总分、领导评分总分、已评分总分。统计条件：已评分 并且 非不了解
            try (DataSet dsSum = dataSet.copy().select(HonorStudentConstant.NCKD_PERFPLANSTATE,HonorStudentConstant.NCKD_EVALQUEST,
                            HonorStudentConstant.NCKD_PERFPLANROLE,HonorStudentConstant.NCKD_UNCLEAR,
                            StrFormatter.format("cast((case when {} is null or {} = '' then '0' else {} end) as Integer) as {}",
                                    HonorStudentConstant.NCKD_PERFSCORES,HonorStudentConstant.NCKD_PERFSCORES,HonorStudentConstant.NCKD_PERFSCORES,HonorStudentConstant.NCKD_PERFSCORES+"Num"))
                    .filter(HonorStudentConstant.NCKD_PERFPLANSTATE+" = '2' and "+HonorStudentConstant.NCKD_UNCLEAR+" = false")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST,HonorStudentConstant.NCKD_PERFPLANROLE})
                    .sum(HonorStudentConstant.NCKD_PERFSCORES+"Num")
                    .finish()) {
                while (dsSum.hasNext()) {
                    Row row = dsSum.next();
                    Long evalQuestId = row.getLong(HonorStudentConstant.NCKD_EVALQUEST);
                    String perfPlanRole = row.getString(HonorStudentConstant.NCKD_PERFPLANROLE);
                    Integer perfScores = row.getInteger(HonorStudentConstant.NCKD_PERFSCORES+"Num");

                    EvalQuestResultBO evalQuestResultBO = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                    if(perfPlanRole.equals(PerfPlanRoleEnum.PEERS.getCode())){
                        //同级评分总分
                        evalQuestResultBO.addPeerRatingTotal(perfScores);
                    }else if(perfPlanRole.equals(PerfPlanRoleEnum.SUPERIOR.getCode())){
                        //上级评分总分
                        evalQuestResultBO.addSuperiorRatingTotal(perfScores);

                    }else if(perfPlanRole.equals(PerfPlanRoleEnum.LEAD.getCode())){
                        //领导评分总分
                        evalQuestResultBO.addLeaderRatingTotal(perfScores);
                    }
                }
                for (Map.Entry<Long, EvalQuestResultBO> entry : resultMap.entrySet()) {
                    EvalQuestResultBO evalQuestResultBO = entry.getValue();
                    //同级评分总分+上级评分总分+领导评分总分=已评分总分
                    int totalScore = (evalQuestResultBO.getPeerRatingTotal() == null ? 0 : evalQuestResultBO.getPeerRatingTotal()) +
                            (evalQuestResultBO.getSuperiorRatingTotal() == null ? 0 : evalQuestResultBO.getSuperiorRatingTotal()) +
                            (evalQuestResultBO.getLeaderRatingTotal() == null ? 0 : evalQuestResultBO.getLeaderRatingTotal());
                    //已评分总分
                    evalQuestResultBO.setRatedTotal(totalScore);
                }
            }
            //统计：已评分人数、未评分人数。统计条件：【评分状态为含：（未开始、待评分）=未评分人数、已评分=已评分人数】
            try (DataSet dsCount = dataSet.copy()
                    .filter(HonorStudentConstant.NCKD_PERFPLANSTATE+" in ('0','1','2')")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST,HonorStudentConstant.NCKD_SCORER,HonorStudentConstant.NCKD_PERFPLANSTATE})
                    .count()
                    .finish()) {
                try (DataSet scoresDs = dsCount.groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST, HonorStudentConstant.NCKD_PERFPLANSTATE}).count().finish()){
                    while (scoresDs.hasNext()) {
                        Row row = scoresDs.next();
                        Long evalQuestId = row.getLong(HonorStudentConstant.NCKD_EVALQUEST);
                        String perfPlanState = row.getString(HonorStudentConstant.NCKD_PERFPLANSTATE);
                        Integer count = row.getInteger("count");

                        EvalQuestResultBO evalQuestResultBO = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                        if(perfPlanState.contains("0") || perfPlanState.contains("1")){
                            //未评分人数
                            evalQuestResultBO.addUnratedPersonnel(count);
                        }else{
                            //已评分人数
                            evalQuestResultBO.addRatedCount(count);
                        }
                    }
                }
            }
            //不了解人数
            try (DataSet dsCount = dataSet.copy()
                    .filter(HonorStudentConstant.NCKD_UNCLEAR+" = true")
                    .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST,HonorStudentConstant.NCKD_SCORER,HonorStudentConstant.NCKD_UNCLEAR})
                    .count()
                    .finish()) {
                try(DataSet unclearDs = dsCount
                        .groupBy(new String[]{HonorStudentConstant.NCKD_EVALQUEST, HonorStudentConstant.NCKD_UNCLEAR})
                        .count()
                        .finish()){
                    while (unclearDs.hasNext()) {
                        Row row = unclearDs.next();
                        Long evalQuestId = row.getLong(HonorStudentConstant.NCKD_EVALQUEST);
                        Integer count = row.getInteger("count");
                        EvalQuestResultBO evalQuestResultBO = resultMap.computeIfAbsent(evalQuestId, k -> new EvalQuestResultBO());
                        evalQuestResultBO.addNotUnderstandCount(count);
                    }
                }
            }
        }
        return resultMap;
     }


    /**
     * 查询问卷信息
     * @param
     * @return: nckd.jxccl.hr.hstu.business.helper.HonorStudentHelper.Result
     * @author W.Y.C
     * @date: 2025/07/23 21:20
     */
    @NotNull
    public static HonorStudentHelper.Result getEvalQuest(List<Long> selectedRowIds) {

        StringJoiner fields = new StringJoiner(",");
        fields.add(FormConstant.ID_KEY);
        //评测状态
        fields.add(HonorStudentConstant.NCKD_PERIODSTATE);
        //地区差异分
        fields.add(HonorStudentConstant.NCKD_DIFFERENCESCORE);
        //已评分人数
        fields.add(HonorStudentConstant.NCKD_HAVEDO);
        //未评分人数
        fields.add(HonorStudentConstant.NCKD_NODO);
        //评价规则
        fields.add(HonorStudentConstant.NCKD_EVALUATIONRULE+"."+FormConstant.ID_KEY);
        //被评价人
        fields.add(HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.PERSON+"."+FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.PERSON+"."+FormConstant.NAME_KEY);
        //被评价人部门
        fields.add(HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.ADMINORG+"."+FormConstant.ID_KEY);
        fields.add(HonorStudentConstant.NCKD_EVALPERSON+"."+FormConstant.ADMINORG+"."+FormConstant.NAME_KEY);
        DynamicObject[] evalQuestArray = BusinessDataServiceHelper.load(HonorStudentConstant.NCKD_EVALQUEST_ENTITYID,
                fields.toString(),
                new QFilter[]{QFilterCommonHelper.getIdInFilter(selectedRowIds)});
        return new HonorStudentHelper.Result(selectedRowIds, evalQuestArray);
    }

    public static class Result {
        public final List<Long> selectedRowIds;
        public final DynamicObject[] evalQuestArray;

        public Result(List<Long> selectedRowIds, DynamicObject[] evalQuestArray) {
            this.selectedRowIds = selectedRowIds;
            this.evalQuestArray = evalQuestArray;
        }
    }
}