package nckd.jxccl.hr.psms.task;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
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.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.QueryEntityType;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
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.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.enums.AppraisalResultEnum;
import nckd.jxccl.base.common.enums.psms.JobSeqEnum;
import nckd.jxccl.base.common.enums.psms.ScoreIteMrankEnum;
import nckd.jxccl.base.common.enums.psms.ScoreItemEnum;
import nckd.jxccl.base.common.enums.psms.ScoreItemLevelEnum;
import nckd.jxccl.base.common.enums.psms.ScoreItemSubEnum;
import nckd.jxccl.base.common.enums.psms.TypeStateEnum;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.base.hrpi.helper.EmpPosOrgRelHelper;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.base.orm.helper.QFilterPersonHelper;
import nckd.jxccl.hr.hstu.plugin.operate.EvalQuestGenerateQuestOperationPlugin;
import nckd.jxccl.hr.psms.common.ContributionConstant;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 关键行为评价定时任务
* @author W.Y.C
* @date 2025/12/24 17:28
* @version 1.0
*/
public class KeyBeHavEvalTask extends AbstractTask implements Plugin {

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

    public final static Map<String,List<Integer>> jobSeqJobLevelMap = ImmutableMap.<String, List<Integer>>builder()
            .put(JobSeqEnum.TECHNICALS.getCode(), Lists.newArrayList(13,14,15))
            .put(JobSeqEnum.FUNCTIONAL.getCode(), Lists.newArrayList(13,14,15))
            .put(JobSeqEnum.SKILL.getCode(), Lists.newArrayList(13,14,15))
            .build();

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        logger.info("开始执行关键行为评价定时任务");

        //查询所有员工
        logger.info("开始查询所有员工信息");
        DynamicObject[] empPosOrgRelArray = EmpPosOrgRelHelper.allEmpPosOrgRel();
        if(empPosOrgRelArray == null || empPosOrgRelArray.length == 0){
            logger.warn("未查询到员工信息，任务结束");
            return;
        }
        logger.info("查询到员工信息总数: {}", empPosOrgRelArray.length);
        List<Long> personIds = Arrays.stream(empPosOrgRelArray).map(empPosOrgRel -> empPosOrgRel.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))).collect(Collectors.toList());
        List<Long> assignmentIds = Arrays.stream(empPosOrgRelArray).map(empPosOrgRel -> empPosOrgRel.getLong(String.join(".", FormConstant.ASSIGNMENT, FormConstant.ID_KEY))).collect(Collectors.toList());
        logger.info("员工ID数量: {}, 职务ID数量: {}", personIds.size(), assignmentIds.size());
        Map<Long, DynamicObject> empPosOrgRelMap = Arrays.stream(empPosOrgRelArray)
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY)),
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.isEmpty() ? null : list.get(0) // 取第一个，即最新记录
                        )
                ));
        logger.info("员工信息分组完成，分组后Map大小: {}", empPosOrgRelMap.size());


        //TODO 职称/技能

        //查询近3年考核结果
        logger.info("开始查询近3年考核结果");
        int threeYearsAgo = LocalDate.now().minusYears(3).getYear();
        Date beginDate = DateUtil.toDate(LocalDate.of(threeYearsAgo, 1, 1));
        int currentYear = LocalDate.now().getYear()-1;
        Date endDate = DateUtil.endOfYear(DateUtil.toDate(LocalDate.of(currentYear, 1, 1)));
        logger.info("考核结果查询时间范围: {} 到 {}", DateUtil.getYear(beginDate), DateUtil.getYear(endDate));
        //查询最近3年的数据
        QFilter perfManagerFilter = new QFilter(PositionStructureConstant.NCKD_BEGINYEAR, QCP.less_equals, endDate)
                .and(new QFilter(PositionStructureConstant.NCKD_ENDYEAR, QCP.large_equals, beginDate))
                .and(String.join(".",FormConstant.NCKD_PERSON,FormConstant.ID_KEY), QCP.in, personIds);
        QueryFieldBuilder perfManagerQueryField = QueryFieldBuilder.create()
                .addIdNumberName(PositionStructureConstant.NCKD_PERSON)
                .add(PositionStructureConstant.NCKD_PERFMANAGERENTRY,PositionStructureConstant.NCKD_APPRAISALYEAR)
                //考核结果（nckd.jxccl.base.common.enums.AppraisalResultEnum）
                .addIdNumberName(PositionStructureConstant.NCKD_PERFMANAGERENTRY,PositionStructureConstant.NCKD_APPRAISALRESULT);
        DynamicObjectCollection perfManagerColl = QueryServiceHelper.query(PositionStructureConstant.PERFMANAGER_ENTITYID, perfManagerQueryField.buildSelect(), new QFilter[]{perfManagerFilter}, perfManagerQueryField.buildOrder());
        logger.info("考核结果查询完成，查询结果数量: {}", perfManagerColl.size());
        Map<Long, List<DynamicObject>> perfManagerResultMap = perfManagerColl.stream()
                .collect(Collectors.groupingBy(obj ->
                        obj.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY))
                ));
        logger.info("考核结果分组完成，分组后Map大小: {}", perfManagerResultMap.size());


        //开始
        logger.info("开始处理员工数据，总员工数: {}", empPosOrgRelMap.size());
        List<DynamicObject> saveKeyBeHavEval = new ArrayList<>();
        int processedCount = 0;
        for (DynamicObject person : empPosOrgRelMap.values()) {
            long personId = person.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
            logger.debug("处理员工ID: {}", personId);
            int jobLevelSeq = -2;
            String jobSeqNumber = null;
            DynamicObject jobSeqObj = null;
            DynamicObject position = person.getDynamicObject(FormConstant.POSITION_KEY);
            if(position != null) {
                jobSeqObj = position.getDynamicObject(FormConstant.NCKD_JOBSEQ);
                if(jobSeqObj != null) {
                    jobSeqNumber = jobSeqObj.getString(FormConstant.NUMBER_KEY);
                }
            }
            if(StringUtils.isBlank(jobSeqNumber)){
                logger.debug("员工ID {} 的职位序列号为空，跳过处理", personId);
                continue;
            }
            
            List<DynamicObject> perfManagerResult = perfManagerResultMap.get(personId);
            logger.debug("员工ID {} 查询到考核结果数量: {}", personId, perfManagerResult != null ? perfManagerResult.size() : 0);
            String appraisalResultYear1 = null; // 最近一年的考核结果
            String appraisalResultYearName1 = null; // 最近一年的考核结果
            String appraisalResultYear2 = null; // 前一年的考核结果
            String appraisalResultYearName2 = null; // 前一年的考核结果
            String appraisalResultYear3 = null; // 再前一年的考核结果
            String appraisalResultYearName3 = null; // 再前一年的考核结果

            if (perfManagerResult != null && !perfManagerResult.isEmpty()) {
                // 分配最近3年的考核结果
                for (int i = 0; i < perfManagerResult.size(); i++) {
                    DynamicObject result = perfManagerResult.get(i);
                    Date appraisalYear = result.getDate(String.join(".", PositionStructureConstant.NCKD_PERFMANAGERENTRY, PositionStructureConstant.NCKD_APPRAISALYEAR));
                    String appraisalResult = result.getString(String.join(".", PositionStructureConstant.NCKD_PERFMANAGERENTRY, PositionStructureConstant.NCKD_APPRAISALRESULT, FormConstant.NUMBER_KEY));
                    String appraisalResultName = result.getString(String.join(".", PositionStructureConstant.NCKD_PERFMANAGERENTRY, PositionStructureConstant.NCKD_APPRAISALRESULT, FormConstant.NAME_KEY));
                    if(appraisalYear != null) {
                        int year = DateUtil.toLocalDateTime(appraisalYear).getYear();
                        if (year == currentYear) {
                            appraisalResultYear1 = appraisalResult;
                            appraisalResultYearName1 = StringUtils.isBlank(appraisalResultName) ? "无" : appraisalResultName;
                        } else if (year == currentYear - 1) {
                            appraisalResultYear2 = appraisalResult;
                            appraisalResultYearName2 = StringUtils.isBlank(appraisalResultName) ? "无" : appraisalResultName;
                        } else if (year == currentYear - 2) {
                            appraisalResultYear3 = appraisalResult;
                            appraisalResultYearName3 = StringUtils.isBlank(appraisalResultName) ? "无" : appraisalResultName;
                        }
                    }
                }
                logger.debug("员工ID {} 考核结果: 第一年({})={}, 第二年({})={}, 第三年({})={}", 
                    personId, currentYear, appraisalResultYearName1,
                    currentYear - 1, appraisalResultYearName2,
                    currentYear - 2, appraisalResultYearName3);
            }


            List<Integer> jobLevelList = jobSeqJobLevelMap.get(jobSeqNumber);
            if(jobLevelList == null){
                logger.debug("职位序列 {} 不在处理范围内，跳过", jobSeqNumber);
                //是这3个序列得人才要处理
                continue;
            }
            JobSeqEnum jobSeq = JobSeqEnum.getByCode(jobSeqNumber);
            logger.debug("员工ID {} 职位序列: {}, 处理职级列表: {}", personId, jobSeq.getName(), jobLevelList);
            for (Integer jobLevel : jobLevelList) {
                logger.debug("处理员工ID {} 的职级: {}", personId, jobLevel);
                boolean isAppraisalResult = false;
                boolean isAppoint = false;
                if(jobSeq == JobSeqEnum.TECHNICALS){
                    //技术
                    if(jobLevel == 13){
                        // 判断近3年绩效定格均在合格及以上
                        isAppraisalResult = isAllAppraisalQualifyOrAbove(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技术序列13级绩效条件判断结果: {}", personId, isAppraisalResult);


                    }else if(jobLevel == 14){
                        // 判断近3年绩效定格均在合格及以上，且至少有一次优秀
                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技术序列14级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }else if(jobLevel == 15){
                        logger.debug("员工ID {} 技术序列15级条件判断", personId);

                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技术序列15级绩效条件判断结果: {}", personId, isAppraisalResult);

                    }
                }else if(jobSeq == JobSeqEnum.FUNCTIONAL){
                    //职能序列
                    if(jobLevel == 13){
                        // 判断近3年绩效定格均在合格及以上
                        isAppraisalResult = isAllAppraisalQualifyOrAbove(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 职能序列13级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }else if(jobLevel == 14){
                        // 判断近3年绩效定格均在合格及以上，且至少有一次优秀
                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 职能序列14级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }else if(jobLevel == 15){
                        // 判断近3年绩效定格均在合格及以上，且至少有一次优秀
                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 职能序列15级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }
                }else if(jobSeq == JobSeqEnum.SKILL){
                    //技能序列
                    if(jobLevel == 12){
                        // 判断近3年绩效定格均在合格及以上
                        isAppraisalResult = isAllAppraisalQualifyOrAbove(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技能序列12级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }else if(jobLevel == 13){
                        // 判断近3年绩效定格均在合格及以上，且至少有一次优秀
                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技能序列13级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }else if(jobLevel == 14){
                        // 判断近3年绩效定格均在合格及以上，且至少有一次优秀
                        isAppraisalResult = isAllAppraisalQualifyOrAboveWithExcellent(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
                        logger.debug("员工ID {} 技能序列14级绩效条件判断结果: {}", personId, isAppraisalResult);
                    }
                }
                String appraisalResultsDisplay = String.join("、",
                        appraisalResultYearName1 != null ? appraisalResultYearName1 : "无",
                        appraisalResultYearName2 != null ? appraisalResultYearName2 : "无",
                        appraisalResultYearName3 != null ? appraisalResultYearName3 : "无");
                StringJoiner matchCondDescJoin = new StringJoiner(StrFormatter.LINE_SEPARATOR);
                matchCondDescJoin.add(StrFormatter.format("职位序列：{}",jobSeq.getName()));
                matchCondDescJoin.add(StrFormatter.format("绩效表现：【{}】，近三年考核结果：【{}】",(isAppraisalResult ? "满足" : "不满足"),appraisalResultsDisplay));
                DynamicObject keyBeHavEval = EntityHelper.newEntity(PositionStructureConstant.KEYBEHAVEVAL_ENTITYID);
                keyBeHavEval.set(FormConstant.NCKD_PERSON, person.getDynamicObject(FormConstant.EMPLOYEE_KEY));
                keyBeHavEval.set(FormConstant.NCKD_DEP, person.getDynamicObject(FormConstant.ADMINORG));
                keyBeHavEval.set(FormConstant.NCKD_POSITION_KEY, person.getDynamicObject(FormConstant.POSITION_KEY));
                keyBeHavEval.set(FormConstant.NCKD_JOBSEQ, jobSeqObj);
                keyBeHavEval.set(PositionStructureConstant.NCKD_JOBLEVEL, jobLevel);
                keyBeHavEval.set(PositionStructureConstant.NCKD_APPOINT, isAppoint ? EnableEnum.YES.getCode() : EnableEnum.NO.getCode());
                keyBeHavEval.set(PositionStructureConstant.NCKD_APPRAISALRESULT, isAppraisalResult ? EnableEnum.YES.getCode() : EnableEnum.NO.getCode());
                keyBeHavEval.set(PositionStructureConstant.NCKD_MATCHCONDDESC+"_tag", matchCondDescJoin.toString());
                keyBeHavEval.set(PositionStructureConstant.STATUS,  StatusEnum.C.toString());
                keyBeHavEval.set(PositionStructureConstant.ENABLE,  EnableEnum.YES.getCode());

                saveKeyBeHavEval.add(keyBeHavEval);
                processedCount++;
            }
        }
        
        logger.info("关键行为评价定时任务处理完成，总共处理员工记录数: {}", processedCount);
        logger.info("准备保存 {} 条关键行为评价记录", saveKeyBeHavEval.size());
        TXHandle txHandle = TX.requiresNew();
        try {
            //删除原数据
            logger.info("开始删除原数据");
            DynamicObjectCollection query = QueryServiceHelper.query(PositionStructureConstant.KEYBEHAVEVAL_ENTITYID, FormConstant.ID_KEY, new QFilter[]{new QFilter(FormConstant.ID_KEY, QCP.is_notnull, null)});
            List<Long> ids = query.stream().map(empPosOrgRel -> empPosOrgRel.getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
            logger.info("查询到需要删除的记录数量: {}", ids.size());
            if (!ids.isEmpty()) {
                MainEntityType keyBeHavEvalEntityType = EntityMetadataCache.getDataEntityType(PositionStructureConstant.KEYBEHAVEVAL_ENTITYID);
                DeleteServiceHelper.delete(keyBeHavEvalEntityType, ids.toArray(new Long[0]));
                logger.info("成功删除 {} 条原数据", ids.size());
            } else {
                logger.info("没有需要删除的原数据");
            }

            if (!saveKeyBeHavEval.isEmpty()) {
                OperationResult operationResult = SaveServiceHelper.saveOperate(PositionStructureConstant.KEYBEHAVEVAL_ENTITYID, saveKeyBeHavEval.toArray(new DynamicObject[0]), OperateOption.create());
                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());
                }
            }
        } catch (Exception e) {
            txHandle.markRollback();
            throw new RuntimeException(e);
        }finally {
            txHandle.close();
        }


    }

    private String getContribString(List<DynamicObject> contribList){
        logger.debug("开始获取贡献字符串，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        StringJoiner contribStringJoiner = new StringJoiner("；");
        if(contribList != null) {
            for (DynamicObject contrib : contribList) {
                Date date = contrib.getDate(ContributionConstant.NCKD_YEAR);
                String scoreItemNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEM, FormConstant.NUMBER_KEY));
                ScoreItemEnum scoreItem = ScoreItemEnum.getByCode(scoreItemNumber);
                if (scoreItem != null) {
                    String scoreItemSubNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMSUB, FormConstant.NUMBER_KEY));
                    ScoreItemSubEnum scoreItemSub = ScoreItemSubEnum.getByCode(scoreItemSubNumber);

                    String scoreItemLevelNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMSUB, ContributionConstant.NCKD_SCOREITEMLEVEL, FormConstant.NUMBER_KEY));
                    ScoreItemLevelEnum scoreItemLevel = ScoreItemLevelEnum.getByCode(scoreItemLevelNumber);

                    String scoreItemRankNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMRANK, FormConstant.NUMBER_KEY));
                    ScoreIteMrankEnum scoreItemRank = ScoreIteMrankEnum.getByCode(scoreItemRankNumber);

                    contribStringJoiner.add(StrFormatter.format("年度【{}】-项目【{}】-奖项级别【{}】-级别【{}】-获奖等级【{}】",
                            DateUtil.getYear(date),
                            scoreItem.getName(),
                            scoreItemSub != null ? scoreItemSub.getName() : "",
                            scoreItemLevel != null ? scoreItemLevel.getName() : "",
                            scoreItemRank != null ? scoreItemRank.getName() : ""));
                }
            }
        }
        String result = contribStringJoiner.toString();
        logger.debug("贡献字符串生成完成，内容: {}", result);
        return result;
    }

    /**
     * 判断近3年绩效定格是否均在合格及以上
     * @param appraisalResultYear1 最近一年的考核结果
     * @param appraisalResultYear2 前一年的考核结果
     * @param appraisalResultYear3 再前一年的考核结果
     * @return boolean
     */
    private boolean isAllAppraisalQualifyOrAbove(String appraisalResultYear1, String appraisalResultYear2, String appraisalResultYear3) {
        logger.info("检查考核结果是否均在合格及以上: 第一年={}, 第二年={}, 第三年={}", appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
        String[] appraisalResults = {appraisalResultYear1, appraisalResultYear2, appraisalResultYear3};

        // 检查是否所有年份都有考核结果
        for (String result : appraisalResults) {
            if (result == null) {
                logger.info("存在年份没有考核结果，不满足条件");
                return false;
            }
        }

        for (String result : appraisalResults) {
            if (result != null) { // 检查所有考核结果
                AppraisalResultEnum appraisalEnum = AppraisalResultEnum.getByCode(result);
                if (appraisalEnum != null) {
                    // 检查是否在合格及以上 (优秀、合格、基本合格、视同合格、良好、视同优秀)
                    boolean isQualifyOrAbove = appraisalEnum == AppraisalResultEnum.EXCELLENT ||
                            appraisalEnum == AppraisalResultEnum.QUALIFIED ||
                            appraisalEnum == AppraisalResultEnum.BASICALLY_QUALIFIED ||
                            appraisalEnum == AppraisalResultEnum.DEEMED_QUALIFIED ||
                            appraisalEnum == AppraisalResultEnum.GOOD ||
                            appraisalEnum == AppraisalResultEnum.DEEMED_EXCELLENT;

                    logger.info("考核结果 {} 解析为: {}，是否合格及以上: {}", result, appraisalEnum.getName(), isQualifyOrAbove);

                    if (!isQualifyOrAbove) {
                        logger.info("发现不合格考核结果: {}", result);
                        return false;
                    }
                } else {
                    logger.info("无法识别考核结果代码: {}", result);
                    return false; // 如果无法识别考核结果，认为不符合条件
                }
            }
        }
        logger.info("所有考核结果均合格及以上");
        return true;
    }

    /**
     * 判断近3年绩效定格是否均在合格及以上，且至少有一次优秀
     * @param appraisalResultYear1 最近一年的考核结果
     * @param appraisalResultYear2 前一年的考核结果
     * @param appraisalResultYear3 再前一年的考核结果
     * @return boolean
     */
    private boolean isAllAppraisalQualifyOrAboveWithExcellent(String appraisalResultYear1, String appraisalResultYear2, String appraisalResultYear3) {
        logger.info("检查考核结果是否均在合格及以上且至少有一次优秀: 第一年={}, 第二年={}, 第三年={}", appraisalResultYear1, appraisalResultYear2, appraisalResultYear3);
        // 首先检查是否所有考核结果都在合格及以上
        if (!isAllAppraisalQualifyOrAbove(appraisalResultYear1, appraisalResultYear2, appraisalResultYear3)) {
            logger.info("并非所有考核结果都在合格及以上或没有考核结果");
            return false;
        }

        // 然后检查是否至少有一次优秀（包括优秀、视同优秀、良好）
        String[] appraisalResults = {appraisalResultYear1, appraisalResultYear2, appraisalResultYear3};
        int excellentCount = 0;

        for (String result : appraisalResults) {
            if (result != null) { // 只检查非空的考核结果
                AppraisalResultEnum appraisalEnum = AppraisalResultEnum.getByCode(result);
                if (appraisalEnum != null) {
                    // 检查是否为优秀等级
                    boolean isExcellent = appraisalEnum == AppraisalResultEnum.EXCELLENT ||
                            appraisalEnum == AppraisalResultEnum.DEEMED_EXCELLENT ||
                            appraisalEnum == AppraisalResultEnum.GOOD;
                    
                    if (isExcellent) {
                        excellentCount++;
                        logger.info("发现优秀考核结果: {} ({})", result, appraisalEnum.getName());
                    }
                }
            }
        }
        
        boolean hasExcellent = excellentCount > 0;
        logger.info("至少有一次优秀的考核结果: {}, 优秀次数: {}", hasExcellent, excellentCount);
        return hasExcellent;
    }



    /**
     * 判断近3年是否获得厂矿科技进步、科学技术奖三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasFactoryTechInnovationThirdPrizeOrAbove(List<DynamicObject> contribList) {
        logger.debug("检查厂矿科技进步、科学技术奖三等奖及以上，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        boolean result = hasRequiredAwards(contribList,
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.FACTORY_LEVEL}
                )
        );
        logger.debug("厂矿科技进步、科学技术奖三等奖及以上检查结果: {}", result);
        return result;
    }

    /**
     * 判断近3年是否获得厂矿科技进步、科学技术奖二等奖及以上，公司科技进步、科学技术奖三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasFactoryTechSecondAndCompanyTechThird(List<DynamicObject> contribList) {
        logger.debug("检查厂矿科技进步、科学技术奖二等奖及以上，公司科技进步、科学技术奖三等奖及以上，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        boolean result = hasRequiredAwards(contribList,
                AwardCondition.secondPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.FACTORY_LEVEL}
                ),
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                )
        );
        logger.debug("厂矿科技进步、科学技术奖二等奖及以上，公司科技进步、科学技术奖三等奖及以上检查结果: {}", result);
        return result;
    }

    /**
     * 判断近3年是否获得公司科技进步、科学技术奖二等奖及以上，省科技进步、科学技术奖三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasCompanyTechSecondAndProvinceTechThird(List<DynamicObject> contribList) {
        logger.debug("检查公司科技进步、科学技术奖二等奖及以上，省科技进步、科学技术奖三等奖及以上，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        boolean result = hasRequiredAwards(contribList,
                AwardCondition.secondPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                ),
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.PROVINCIAL_LEVEL}
                )
        );
        logger.debug("公司科技进步、科学技术奖二等奖及以上，省科技进步、科学技术奖三等奖及以上检查结果: {}", result);
        return result;
    }

    /**
     * 判断近3年是否获得公司管理创新奖、全员创效奖三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasCompanyManagementInnovationThird(List<DynamicObject> contribList) {
        logger.debug("检查公司管理创新奖、全员创效奖三等奖及以上，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        boolean result = hasRequiredAwards(contribList,
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                )
        );
        logger.debug("公司管理创新奖、全员创效奖三等奖及以上检查结果: {}", result);
        return result;
    }

    /**
     * 判断近3年是否获得公司管理创新奖、全员创效奖二等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasCompanyManagementInnovationSecond(List<DynamicObject> contribList) {
        logger.debug("检查公司管理创新奖、全员创效奖二等奖及以上，贡献列表大小: {}", contribList != null ? contribList.size() : 0);
        boolean result = hasRequiredAwards(contribList,
                AwardCondition.secondPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                )
        );
        logger.debug("公司管理创新奖、全员创效奖二等奖及以上检查结果: {}", result);
        return result;
    }

    /**
     * 判断近3年是否获得公司管理创新奖、全员创效奖一等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasCompanyManagementInnovationFirst(List<DynamicObject> contribList) {
        return hasRequiredAwards(contribList,
                AwardCondition.firstPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                )
        );
    }

    /**
     * 判断近3年是否获得厂矿创新奖、全员创效奖三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasFactoryInnovationThird(List<DynamicObject> contribList) {
        return hasRequiredAwards(contribList,
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.FACTORY_LEVEL}
                )
        );
    }

    /**
     * 判断近3年是否获得厂矿创新奖、全员创效奖二等奖及以上，公司科技进步三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasFactoryInnovationSecondAndCompanyTechThird(List<DynamicObject> contribList) {
        return hasRequiredAwards(contribList,
                AwardCondition.secondPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.FACTORY_LEVEL}
                ),
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                )
        );
    }

    /**
     * 判断近3年是否获得公司创新奖、全员创效奖二等奖及以上，省科技进步三等奖及以上
     * @param contribList 贡献列表
     * @return boolean
     */
    private boolean hasCompanyInnovationSecondAndProvinceTechThird(List<DynamicObject> contribList) {
        return hasRequiredAwards(contribList,
                AwardCondition.secondPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.MANAGEMENT_INNOVATION_AWARD, ScoreItemSubEnum.EMPLOYEES_CREATIVE_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.COMPANY_LEVEL}
                ),
                AwardCondition.thirdPrizeOrAbove(
                        new ScoreItemSubEnum[]{ScoreItemSubEnum.TECHNOLOGY_AWARD},
                        new ScoreItemLevelEnum[]{ScoreItemLevelEnum.PROVINCIAL_LEVEL}
                )
        );
    }

    /**
     * 通用的奖励判断方法
     * @param contribList 贡献列表
     * @param requiredAwards 需要满足的奖项条件数组
     * @return boolean
     */
    private boolean hasRequiredAwards(List<DynamicObject> contribList, AwardCondition... requiredAwards) {
        if (contribList == null || contribList.isEmpty() || requiredAwards == null || requiredAwards.length == 0) {
            return false;
        }

        // 为每个奖项条件创建一个标记，表示是否已满足
        boolean[] satisfied = new boolean[requiredAwards.length];

        for (DynamicObject contrib : contribList) {
            String scoreItemNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEM, FormConstant.NUMBER_KEY));
            ScoreItemEnum scoreItem = ScoreItemEnum.getByCode(scoreItemNumber);

            if (scoreItem != null && scoreItem == ScoreItemEnum.RESEARCH_SCORE) {
                String scoreItemSubNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMSUB, FormConstant.NUMBER_KEY));
                ScoreItemSubEnum scoreItemSub = ScoreItemSubEnum.getByCode(scoreItemSubNumber);

                String scoreItemLevelNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMSUB, ContributionConstant.NCKD_SCOREITEMLEVEL, FormConstant.NUMBER_KEY));
                ScoreItemLevelEnum scoreItemLevel = ScoreItemLevelEnum.getByCode(scoreItemLevelNumber);

                String scoreItemRankNumber = contrib.getString(String.join(".", ContributionConstant.NCKD_SCOREITEMRANK, FormConstant.NUMBER_KEY));
                ScoreIteMrankEnum scoreItemRank = ScoreIteMrankEnum.getByCode(scoreItemRankNumber);

                // 检查当前奖项是否满足任一条件
                for (int i = 0; i < requiredAwards.length; i++) {
                    AwardCondition condition = requiredAwards[i];

                    if (condition.isMatch(scoreItemRank, scoreItemLevel, scoreItemSub)) {
                        satisfied[i] = true;
                    }
                }
            }
        }

        // 检查所有条件是否都已满足
        for (boolean isSatisfied : satisfied) {
            if (!isSatisfied) {
                return false;
            }
        }

        return true;
    }

    /**
     * 奖项条件类
     */
    private static class AwardCondition {
        private final ScoreIteMrankEnum[] rankEnums;
        private final ScoreItemLevelEnum[] levelEnums;
        private final ScoreItemSubEnum[] subEnums;

        public AwardCondition(ScoreIteMrankEnum[] rankEnums, ScoreItemLevelEnum[] levelEnums, ScoreItemSubEnum[] subEnums) {
            this.rankEnums = rankEnums;
            this.levelEnums = levelEnums;
            this.subEnums = subEnums;
        }

        /**
         * 检查当前奖项是否匹配条件
         */
        public boolean isMatch(ScoreIteMrankEnum rank, ScoreItemLevelEnum level, ScoreItemSubEnum sub) {
            if (rank == null || level == null || sub == null) {
                return false;
            }

            // 检查奖项类型是否匹配
            boolean rankMatch = false;
            for (ScoreIteMrankEnum requiredRank : rankEnums) {
                if (rank == requiredRank) {
                    rankMatch = true;
                    break;
                }
            }

            // 检查级别是否匹配
            boolean levelMatch = false;
            for (ScoreItemLevelEnum requiredLevel : levelEnums) {
                if (level == requiredLevel) {
                    levelMatch = true;
                    break;
                }
            }

            // 检查等级是否匹配
            boolean subMatch = false;
            for (ScoreItemSubEnum requiredSub : subEnums) {
                if (sub == requiredSub) {
                    subMatch = true;
                    break;
                }
            }

            return rankMatch && levelMatch && subMatch;
        }

        /**
         * 创建三等奖及以上的条件
         */
        public static AwardCondition thirdPrizeOrAbove(ScoreItemSubEnum[] subEnums, ScoreItemLevelEnum[] levelEnums) {
            ScoreIteMrankEnum[] rankEnums = {ScoreIteMrankEnum.THIRD_PRIZE, ScoreIteMrankEnum.SECOND_PRIZE, ScoreIteMrankEnum.FIRST_PRIZE};
            return new AwardCondition(rankEnums, levelEnums, subEnums);
        }

        /**
         * 创建二等奖及以上的条件
         */
        public static AwardCondition secondPrizeOrAbove(ScoreItemSubEnum[] subEnums, ScoreItemLevelEnum[] levelEnums) {
            ScoreIteMrankEnum[] rankEnums = {ScoreIteMrankEnum.SECOND_PRIZE, ScoreIteMrankEnum.FIRST_PRIZE};
            return new AwardCondition(rankEnums, levelEnums, subEnums);
        }

        /**
         * 创建一等奖及以上的条件
         */
        public static AwardCondition firstPrizeOrAbove(ScoreItemSubEnum[] subEnums, ScoreItemLevelEnum[] levelEnums) {
            ScoreIteMrankEnum[] rankEnums = {ScoreIteMrankEnum.FIRST_PRIZE};
            return new AwardCondition(rankEnums, levelEnums, subEnums);
        }
    }
}