package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.cultivate.mapper.CultivateExamMapper;
import jnpf.cultivate.mapper.FtbCultivateCertificateResultMapper;
import jnpf.cultivate.mapper.FtbCultivateExamUserMapper;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskAssignmentMapper;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.*;
import jnpf.entity.cultivate.*;
import jnpf.enums.cultivate.ApplyStatusEnum;
import jnpf.enums.cultivate.task.TaskStateEnum;
import jnpf.model.cultivate.po.course.FtbCultivateCertificateResult;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTask;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.po.task.FtbCultivateLearnTaskPhase;
import jnpf.model.cultivate.po.task.FtbCultivateTaskLog;
import jnpf.model.cultivate.v2.exam.po.CultivateExam;
import jnpf.model.cultivate.v2.exam.po.CultivateExamDrawRule;
import jnpf.model.cultivate.v2.mq.CultivateMqDTO;
import jnpf.model.cultivate.v2.task.vo.*;
import jnpf.model.cultivate.vo.identify.UserOrgInfoAll1Vo;
import jnpf.model.enums.CourseEnums;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.ConstantUtil;
import jnpf.util.QuestionAnalysisUtil;
import jnpf.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class V2CultivateTaskStudyServiceImpl implements V2CultivateTaskStudyService {


    @Autowired
    private V2CultivateBatchQueryService v2CultivateBatchQueryService;

    @Autowired
    private FtbCultivateLearnTaskService ftbCultivateLearnTaskService;

    @Autowired
    private FtbCultivateLearnTaskPhaseService ftbCultivateLearnTaskPhaseService;

    @Autowired
    private FtbCultivateLearnTaskCourseService ftbCultivateLearnTaskCourseService;

    @Autowired
    private FtbCultivateLearnTaskExamService ftbCultivateLearnTaskExamService;

    @Autowired
    private FtbCultivateLearnTaskIdentificationService ftbCultivateLearnTaskIdentificationService;

    @Autowired
    private FtbCultivateLearnTaskCertificateService ftbCultivateLearnTaskCertificateService;

    @Autowired
    private FtbCultivateLearnTaskPracticeService ftbCultivateLearnTaskPracticeService;


    @Autowired
    private FtbCultivateTaskLogService ftbCultivateTaskLogService;


    @Autowired
    private CultivateIdentifyTableService identifyTableService;

    @Autowired
    private CultivateIdentifyItemsService identifyItemsService;

    @Autowired
    private CultivateIdentifyApplyDetailsService applyDetailsService;

    @Autowired
    private CultivateIdentifyApplyService identifyApplyService;

    @Autowired
    private CultivateIdentifyApplyTableBackupsService applyTableBackupsService;

    @Autowired
    private CultivateIdentifyApplyDetailsBackupsService applyDetailsBackupsService;


    @Autowired
    private V2CultivateCertificateService v2CultivateCertificateService;


    @Autowired
    private CultivateExamDrawRuleService examDrawRuleService;


    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    @Autowired
    private FtbCultivateLearnTaskAssignmentMapper learnTaskAssignmentMapper;

    @Autowired
    private FtbCultivateCertificateResultMapper ftbCultivateCertificateResultMapper;


    @Autowired
    private CultivateExamMapper v2CultivateExamMapper;


    @Autowired
    private ApplicationContext applicationContext;

    private V2CultivateTaskStudyService selfProxy;

    @PostConstruct
    public void init() {
        this.selfProxy = applicationContext.getBean(V2CultivateTaskStudyService.class);
    }


    /**
     * 任务学习
     *
     * @param message 培训信息
     */
    @Override
    public void dealTaskCourseStudy(CultivateMqDTO message) {
        String userId = message.getUserId();
        String courseId = message.getBusinessId();
        String taskId = message.getBusinessSourceId();//岗位学习id
        String tenantId = message.getTenantId();
        if (StringUtils.isEmpty(taskId) || StringUtils.isEmpty(courseId) || StringUtils.isEmpty(userId)) {
            return;
        }

        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userPrimaryBoundOne == null) {
            log.error("用户查询未null，examId={}, userId={}", userId);
            return;
        }
        this.selfProxy.dealTaskStudyItem(userPrimaryBoundOne, taskId, tenantId);
    }


    /**
     * 检查用户课程学习完成状态
     *
     * @param userId    用户ID
     * @param courseIds 课程ID列表
     * @return 课程是否全部完成学习(true - 全部完成 ， false - 未全部完成)
     */
    private boolean checkUserCourseCompleteStatus(String userId, List<String> courseIds, String taskId, String phaseId) {
        if (CollUtil.isEmpty(courseIds)) {
            ftbCultivateTaskLogService.saveCourseTaskPhase(userId, taskId, phaseId, TaskStateEnum.NOT_CONFIGURED.getCode());
            return true; // 如果没有课程，认为已完成
        }

        boolean phaseCourseCompleteStatus = true;
        Map<String, FtbCultivatePositionCourceLearning> courseLearnStatusMap = v2CultivateBatchQueryService.batchQueryUserCourseLearnStatus(userId, courseIds);
        for (String id : courseIds) {
            FtbCultivatePositionCourceLearning courseLearnStatus = courseLearnStatusMap.get(id);
            if (courseLearnStatus == null) {
                phaseCourseCompleteStatus = false;
                break;
            }
            if (courseLearnStatus.getState() != 1) {
                phaseCourseCompleteStatus = false;
                break;
            }
        }
        if (phaseCourseCompleteStatus) {
            ftbCultivateTaskLogService.saveCourseTaskPhase(userId, taskId, phaseId, TaskStateEnum.COMPLETED.getCode());
        }
        return phaseCourseCompleteStatus;
    }

    /**
     * 评估阶段的考试、技能和鉴定状态
     */
    private PhaseStatusResultVo evaluatePhaseStatus(String userId, String taskId, String tenantId, List<String> examIds, List<String> practiceIds, List<String> identityIds, FtbCultivateLearnTaskPhase phaseEntity, Map<String, FtbCultivateExamUser> userExamStatusMap, Map<String, CultivateIdentifyApply> userIdentificationStatusMap, Map<String, FtbCultivateLearnTaskPracticeVo> practiceTaskMap, Map<String, List<String>> userSkillStatusMap) {
        boolean isExam = true;//false-未完成  true-已完成
        boolean isPractice = true;//false-未完成  true-已完成
        boolean isIdentification = true; //false-未完成  true-已完成

        boolean isExamDone = true;//考试是否做了 false-未做  true-已做
        boolean isIdentificationDone = true; //鉴定是否做了 false-未做  true-已做

        Integer examStatus = 3;//3-优秀 2-合格 1-不合格 0-未考试
        Integer identificationStatus = 3;//3-优秀 2-合格 1-不合格 0-未鉴定
        String userExamId = "";
        String userIdentifyId = "";

        // 处理考试状态
        if (CollUtil.isNotEmpty(examIds)) {
            PhaseExamStatusVo examStatusResult = evaluateExamStatus(userId, taskId, examIds, userExamStatusMap, tenantId);
            isExam = examStatusResult.isCompleted();
            isExamDone = examStatusResult.isDone();
            examStatus = examStatusResult.getStatus();
            if (examStatusResult.getExamUser() != null) {
                userExamId = examStatusResult.getExamUser().getId();
            }
            ftbCultivateTaskLogService.saveExamTaskPhase(userId, taskId, phaseEntity.getId(), isExam ? 1 : 0, examStatusResult.getExamUser());

        } else {
            ftbCultivateTaskLogService.saveExamTaskPhase(userId, taskId, phaseEntity.getId(), TaskStateEnum.NOT_CONFIGURED.getCode(), null);
        }

        // 处理技能状态
        if (CollUtil.isNotEmpty(practiceIds)) {
            isPractice = evaluatePracticeStatus(practiceIds, practiceTaskMap, userSkillStatusMap);
            if (isPractice) {
                ftbCultivateTaskLogService.savePracticeTaskPhase(userId, taskId, phaseEntity.getId(), TaskStateEnum.COMPLETED.getCode());
            }
        } else {
            ftbCultivateTaskLogService.savePracticeTaskPhase(userId, taskId, phaseEntity.getId(), TaskStateEnum.NOT_CONFIGURED.getCode());
        }

        // 处理鉴定状态
        if (CollUtil.isNotEmpty(identityIds)) {
            PhaseIdentificationStatusVo identificationStatusResult = evaluateIdentificationStatus(userId, taskId, identityIds, phaseEntity, userIdentificationStatusMap, isExam, isPractice, tenantId);
            isIdentification = identificationStatusResult.isCompleted();
            isIdentificationDone = identificationStatusResult.isDone();
            identificationStatus = identificationStatusResult.getStatus();
            ftbCultivateTaskLogService.saveIdentificationTaskPhase(userId, taskId, phaseEntity.getId(), isIdentificationDone ? 1 : 0, identificationStatusResult.getCultivateIdentifyApply());
        } else {
            ftbCultivateTaskLogService.saveIdentificationTaskPhase(userId, taskId, phaseEntity.getId(), TaskStateEnum.NOT_CONFIGURED.getCode(), null);
        }

        return new PhaseStatusResultVo(isExam, isPractice, isIdentification, isExamDone, isIdentificationDone, examStatus, identificationStatus, userExamId, userIdentifyId);
    }

    /**
     * 评估考试状态
     */
    private PhaseExamStatusVo evaluateExamStatus(String userId, String taskId, List<String> examIds, Map<String, FtbCultivateExamUser> userExamStatusMap, String tenantId) {
        //false-未完成  true-已完成
        boolean isExam = true;
        //考试是否做了 false-未做  true-已做
        boolean isExamDone = true;//必须有结果
        //3-优秀 2-合格 1-不合格 0-未考试
        int examStatus = 3;

        FtbCultivateExamUser ftbCultivateExamUser = userExamStatusMap.get(examIds.get(0));
        if (ftbCultivateExamUser == null) {
            ftbCultivateExamUser = triggerExam(userId, examIds.get(0), 4, taskId, tenantId);
            if (ftbCultivateExamUser == null) {
                isExamDone = false;
                isExam = false;
            }
        }
        if (ftbCultivateExamUser != null) {
            Integer status = ftbCultivateExamUser.getStatus();
            if (status.equals(0) || status.equals(1) || status.equals(2) || status.equals(4)) {
                isExam = false;
                examStatus = 1;
            }
            if (status.equals(0) || status.equals(1) || status.equals(2)) {
                isExamDone = false;
            }
            if (status.equals(3)) {
                examStatus = 2;
            }
        }

        return new PhaseExamStatusVo(isExam, isExamDone, examStatus, ftbCultivateExamUser);
    }

    /**
     * 评估技能状态
     */
    private boolean evaluatePracticeStatus(List<String> practiceIds, Map<String, FtbCultivateLearnTaskPracticeVo> practiceTaskMap, Map<String, List<String>> userSkillStatusMap) {
        for (String practiceId : practiceIds) {
            FtbCultivateLearnTaskPracticeVo ftbCultivateLearnTaskPractice = practiceTaskMap.get(practiceId);
            List<String> count = userSkillStatusMap.get(practiceId);
            if (ftbCultivateLearnTaskPractice == null || count == null || count.size() < ftbCultivateLearnTaskPractice.getNum()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 评估鉴定状态
     */
    private PhaseIdentificationStatusVo evaluateIdentificationStatus(String userId, String taskId, List<String> identityIds, FtbCultivateLearnTaskPhase phaseEntity, Map<String, CultivateIdentifyApply> userIdentificationStatusMap, boolean isExam, boolean isPractice, String tenantId) {
        boolean isIdentification = true; //false-未完成  true-已完成
        boolean isIdentificationDone = true; //鉴定是否做了 false-未做  true-已做
        int identificationStatus = 3;//3-优秀 2-合格 1-不合格 0-未鉴定


        Integer qualified = phaseEntity.getQualified(); //考试合格和练习满足才能完成鉴定【0-否 1-是】

        boolean shouldCheckIdentification = true;
        CultivateIdentifyApply cultivateIdentifyApply = null;
        if (qualified.equals(1)) { // 需要考试和练习都完成才能鉴定
            shouldCheckIdentification = isExam;
        }

        if (shouldCheckIdentification) {
            cultivateIdentifyApply = userIdentificationStatusMap.get(identityIds.get(0));
            if (cultivateIdentifyApply == null) {
                cultivateIdentifyApply = triggerIdentification(userId, identityIds.get(0), 4, taskId, phaseEntity.getId(), tenantId);
                isIdentification = false;
                isIdentificationDone = false;
                identificationStatus = 0;
            } else {

                if (cultivateIdentifyApply.getStatus().equals(0) || cultivateIdentifyApply.getStatus().equals(2)) {
                    isIdentification = false;
                    isIdentificationDone = false;
                    identificationStatus = 0;
                } else {
                    if (cultivateIdentifyApply.getResult().equals(2)) {
                        isIdentification = false;
                        identificationStatus = 1;
                    } else if (cultivateIdentifyApply.getResult().equals(0)) {
                        identificationStatus = 2;
                    } else if (cultivateIdentifyApply.getResult().equals(1)) {
                        identificationStatus = 3;
                    }
                }
            }
        } else {
            isIdentification = false;
            isIdentificationDone = false;
            identificationStatus = 0;
        }

        return new PhaseIdentificationStatusVo(isIdentification, isIdentificationDone, identificationStatus, cultivateIdentifyApply);
    }

    /**
     * 处理阶段完成逻辑（证书和日志记录）
     */
    private void handlePhaseCompletion(String userId, String taskId, String tenantId, FtbCultivateLearnTaskPhase phaseEntity, List<String> certificateIds, PhaseStatusResultVo phaseStatusResult) {
        boolean isExam = phaseStatusResult.isExam();
        boolean isPractice = phaseStatusResult.isPractice();
        boolean isIdentification = phaseStatusResult.isIdentification();
        boolean isExamDone = phaseStatusResult.isExamDone();
        boolean isIdentificationDone = phaseStatusResult.isIdentificationDone();
        Integer examStatus = phaseStatusResult.getExamStatus();
        Integer identificationStatus = phaseStatusResult.getIdentificationStatus();
        String userExamId = phaseStatusResult.getUserExamId();
        String userIdentifyId = phaseStatusResult.getUserIdentifyId();

        // 是否有证书
        if (phaseEntity.getIsPassComplete().equals(1)) {
            if (isExam && isPractice && isIdentification) {
                Integer issuedCertificate = processCertificateIssuance(certificateIds, phaseEntity, examStatus, identificationStatus, userId, tenantId);
                ftbCultivateTaskLogService.saveOrUpdateByCondition(userId, taskId, phaseEntity.getId(), issuedCertificate);
                // 保存考试结果状态、鉴定结果状态、用户考试ID和用户鉴定ID
                saveExamAndIdentifyResultState(userId, taskId, phaseEntity.getId(), examStatus, identificationStatus, userExamId, userIdentifyId);
            }
        } else {
            if (isExamDone && isIdentificationDone) {
                Integer issuedCertificate = processCertificateIssuance(certificateIds, phaseEntity, examStatus, identificationStatus, userId, tenantId);
                ftbCultivateTaskLogService.saveOrUpdateByCondition(userId, taskId, phaseEntity.getId(), issuedCertificate);
                // 保存考试结果状态、鉴定结果状态、用户考试ID和用户鉴定ID
                saveExamAndIdentifyResultState(userId, taskId, phaseEntity.getId(), examStatus, identificationStatus, userExamId, userIdentifyId);
            }
        }
    }

    /**
     * 保存考试结果状态、鉴定结果状态、用户考试ID和用户鉴定ID
     *
     * @param userId               用户ID
     * @param taskId               任务ID
     * @param phaseId              阶段ID
     * @param examStatus           考试状态（0待考试，1待批阅，2已逾期，3合格，4不合格，5优秀）
     * @param identificationStatus 鉴定状态（0-合格，1-优秀，2-不合格）
     * @param userExamId           用户考试ID
     * @param userIdentifyId       用户鉴定ID
     */
    private void saveExamAndIdentifyResultState(String userId, String taskId, String phaseId, Integer examStatus, Integer identificationStatus, String userExamId, String userIdentifyId) {
        // 转换考试状态：3-合格 -> 3, 4-不合格 -> 4, 5-优秀 -> 5
        if (examStatus != null && examStatus >= 3) {
            ftbCultivateTaskLogService.saveExamResultState(userId, taskId, phaseId, examStatus);
        }

        // 转换鉴定状态：2-合格 -> 0, 3-优秀 -> 1, 1-不合格 -> 2
        if (identificationStatus != null && identificationStatus >= 1) {
            Integer identifyResult;
            if (identificationStatus == 2) {
                identifyResult = 0; // 合格
            } else if (identificationStatus == 3) {
                identifyResult = 1; // 优秀
            } else if (identificationStatus == 1) {
                identifyResult = 2; // 不合格
            } else {
                identifyResult = -1; // 未配置
            }
            ftbCultivateTaskLogService.saveIdentifyResultState(userId, taskId, phaseId, identifyResult);
        }

        // 保存用户考试ID
        if (userExamId != null && !userExamId.isEmpty()) {
            ftbCultivateTaskLogService.saveUserExamId(userId, taskId, phaseId, userExamId);
        }

        // 保存用户鉴定ID
        if (userIdentifyId != null && !userIdentifyId.isEmpty()) {
            ftbCultivateTaskLogService.saveUserIdentifyId(userId, taskId, phaseId, userIdentifyId);
        }
    }

    /**
     * 处理证书颁发逻辑
     */
    private Integer processCertificateIssuance(List<String> certificateIds, FtbCultivateLearnTaskPhase phaseEntity, Integer examStatus, Integer identificationStatus, String userId, String tenantId) {
        if (CollUtil.isEmpty(certificateIds)) {
            return TaskStateEnum.NOT_CONFIGURED.getCode();
        }
        boolean isCanIssueCertificate = isCanIssueCertificate(phaseEntity, examStatus, identificationStatus);
        if (isCanIssueCertificate) {
            if (!checkIsTriggerTaskCertificate(userId, certificateIds.get(0), phaseEntity.getTaskId(), phaseEntity.id)) {
                triggerCertificate(userId, certificateIds.get(0), tenantId);
                recordTriggerTaskCertificate(userId, certificateIds.get(0), phaseEntity.getTaskId(), phaseEntity.id);
                return TaskStateEnum.COMPLETED.getCode();
            } else {
                return TaskStateEnum.COMPLETED.getCode();
            }

        }
        return TaskStateEnum.INCOMPLETE.getCode();
    }


    private boolean isCanIssueCertificate(FtbCultivateLearnTaskPhase phaseEntity, Integer examStatus, Integer identificationStatus) {
//        Integer examStatus;//3-优秀 2-合格 1-不合格 0-未考试
//        Integer identificationStatus;//3-优秀 2-合格 1-不合格 0-未鉴定
        boolean isExam = false;
        if (phaseEntity.getCertificateExam() == null || phaseEntity.getCertificateExam().equals(0)) {
            isExam = true;
        } else if (phaseEntity.getCertificateExam().equals(1)) {
            if (examStatus >= 2) {
                isExam = true;
            }
        } else if (phaseEntity.getCertificateExam().equals(2)) {
            if (examStatus >= 3) {
                isExam = true;
            }
        }

        boolean isIdentification = false;
        if (phaseEntity.getCertificateIdentification() == null || phaseEntity.getCertificateIdentification().equals(0)) {
            isIdentification = true;
        } else if (phaseEntity.getCertificateIdentification().equals(1)) {
            if (identificationStatus >= 2) {
                isIdentification = true;
            }
        } else if (phaseEntity.getCertificateIdentification().equals(2)) {
            if (identificationStatus >= 3) {
                isIdentification = true;
            }
        }
        return isExam && isIdentification;
    }

    private void checkTaskComplete(String taskId, String userId) {

        List<FtbCultivateLearnTaskPhase> phaseList = getFtbCultivateLearnTaskPhases(taskId);
        if (CollUtil.isEmpty(phaseList)) {
            return;
        }
        List<FtbCultivateTaskLog> completePhaseList = ftbCultivateTaskLogService.queryCompleteTaskPhase(taskId, userId);
        if (CollUtil.isEmpty(completePhaseList)) {
            return;
        }
        List<String> completePhaseIds = new ArrayList<>();
        boolean isGetCert = false;
        for (FtbCultivateTaskLog ftbCultivateTaskLog : completePhaseList) {
            completePhaseIds.add(ftbCultivateTaskLog.getPhaseId());
            if (ftbCultivateTaskLog.getIssuedCertificate().equals(1)) {
                isGetCert = true;
            }
        }
        List<String> phaseIds = phaseList.stream().map(FtbCultivateLearnTaskPhase::getId).collect(Collectors.toList());
        if (UserApiV2Util.areListsEqual(completePhaseIds, phaseIds)) {
            //任务完成
            recordTaskComplete(userId, taskId, isGetCert);
        }
    }


    /**
     * 记录任务完成
     *
     * @param userId           用户ID
     * @param taskId           任务ID
     * @param isGetCertificate 是否获取证书
     */
    private void recordTaskComplete(String userId, String taskId, boolean isGetCertificate) {
        // 任务记录证书颁发
        LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(FtbCultivateLearnTaskAssignment::getStudyStats, 2).set(FtbCultivateLearnTaskAssignment::getLearningEndTime, new Date()).eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0).eq(FtbCultivateLearnTaskAssignment::getUserId, userId).eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        if (isGetCertificate) {
            updateWrapper.set(FtbCultivateLearnTaskAssignment::getIssuedCertificate, 1);
        } else {
            updateWrapper.set(FtbCultivateLearnTaskAssignment::getIssuedCertificate, 0);
        }
        learnTaskAssignmentMapper.update(null, updateWrapper);
    }


    /**
     * 任务考试学习
     *
     * @param message 培训信息
     */
    @Override
    public void dealTaskExamStudy(CultivateMqDTO message) {
        String userId = message.getUserId();
        String examId = message.getBusinessId();
        String tenantId = message.getTenantId();
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userPrimaryBoundOne == null) {
            log.error("用户查询未null，examId={}, userId={}", examId, userId);
            return;
        }
        if (StringUtils.isEmpty(examId) || StringUtils.isEmpty(userId)) {
            log.error("dealTaskExamStudy参数不完整，examId={}, userId={}", examId, userId);
            return;
        }
        List<V2MyCultivateLearnTaskListVo> taskListVoList = ftbCultivateLearnTaskService.queryMyNoCompleteTaskListForUserId(userId);
        if (CollUtil.isEmpty(taskListVoList)) {
            return;
        }
        List<String> taskIds = taskListVoList.stream().map(V2MyCultivateLearnTaskListVo::getTaskId).collect(Collectors.toList());
        //过滤有改考试的任务
        taskIds = ftbCultivateLearnTaskService.queryTaskHasExam(taskIds, examId);
        if (CollUtil.isEmpty(taskIds)) {
            return;
        }
        for (String taskId : taskIds) {
            // 查询任务阶段表
            this.selfProxy.dealTaskStudyItem(userPrimaryBoundOne, taskId, tenantId);
        }

    }

    @Transactional
    @Override
    public void dealTaskStudyItem(UserBoundVO userPrimaryBoundOne, String taskId, String tenantId) {
        String userId = userPrimaryBoundOne.getId();

        // 验证任务有效性
        if (!validateTask(taskId, userId)) {
            return;
        }

        List<FtbCultivateLearnTaskPhase> phaseList = getFtbCultivateLearnTaskPhases(taskId);
        // 如果没有阶段，则直接返回
        if (CollUtil.isEmpty(phaseList)) {
            return;
        }
        //查询已经完成的阶段
        List<String> completePhaseIds = new ArrayList<>();
        List<FtbCultivateTaskLog> completePhaseList = ftbCultivateTaskLogService.queryCompleteTaskPhase(taskId, userId);
        if (CollUtil.isNotEmpty(completePhaseList)) {
            completePhaseIds = completePhaseList.stream().map(FtbCultivateTaskLog::getPhaseId).distinct().collect(Collectors.toList());
        }

        List<FtbCultivateLearnTaskCourseVo> courseEntities = ftbCultivateLearnTaskCourseService.listByTaskId(taskId, 0);
        List<FtbCultivateLearnTaskExamVo> examEntities = ftbCultivateLearnTaskExamService.listByTaskId(taskId);
        List<FtbCultivateLearnTaskIdentificationVo> identificationEntities = ftbCultivateLearnTaskIdentificationService.listByTaskId(taskId);
        List<FtbCultivateLearnTaskCertificateVo> certificateEntities = ftbCultivateLearnTaskCertificateService.listByTaskId(taskId);
        List<FtbCultivateLearnTaskPracticeVo> practiceEntities = ftbCultivateLearnTaskPracticeService.listByTaskId(taskId);

        //课程按照阶段分组
        Map<String, List<FtbCultivateLearnTaskCourseVo>> phaseCourseMap = courseEntities.stream().filter(course -> course.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskCourseVo::getPhaseId));
        //考试按阶段分组
        Map<String, List<FtbCultivateLearnTaskExamVo>> phaseExamMap = examEntities.stream().filter(exam -> exam.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskExamVo::getPhaseId));
        //鉴定按阶段分组
        Map<String, List<FtbCultivateLearnTaskIdentificationVo>> phaseIdentificationMap = identificationEntities.stream().filter(identification -> identification.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskIdentificationVo::getPhaseId));
        //证书按阶段分组
        Map<String, List<FtbCultivateLearnTaskCertificateVo>> phaseCertificateMap = certificateEntities.stream().filter(certificate -> certificate.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskCertificateVo::getPhaseId));
        //练习按阶段分组
        Map<String, List<FtbCultivateLearnTaskPracticeVo>> phasePracticeMap = practiceEntities.stream().filter(practice -> practice.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskPracticeVo::getPhaseId));

        //确定是那个阶段
        for (FtbCultivateLearnTaskPhase phaseEntity : phaseList) {

            if (completePhaseIds.contains(phaseEntity.getId())) {
                continue;
            }
            List<FtbCultivateLearnTaskCourseVo> taskCourseList = phaseCourseMap.get(phaseEntity.getId());
            if (CollUtil.isEmpty(taskCourseList)) {
                break;
            }
            //设置为开始，如果没有开始就设置为开始
            checkAndSetTaskPhaseStart(userId, taskId, phaseEntity.getId());
            List<String> courseIds = CollUtil.isNotEmpty(taskCourseList) ? taskCourseList.stream().map(FtbCultivateLearnTaskCourseVo::getCourseId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            boolean phaseCourseCompleteStatus = checkUserCourseCompleteStatus(userId, courseIds, phaseEntity.getTaskId(), phaseEntity.getId());
            if (!phaseCourseCompleteStatus) {
                break;
            }
            List<FtbCultivateLearnTaskExamVo> taskExamList = phaseExamMap.get(phaseEntity.getId());
            List<FtbCultivateLearnTaskIdentificationVo> taskIdentificationList = phaseIdentificationMap.get(phaseEntity.getId());
            List<FtbCultivateLearnTaskCertificateVo> taskCertificateList = phaseCertificateMap.get(phaseEntity.getId());
            List<FtbCultivateLearnTaskPracticeVo> taskPracticeList = phasePracticeMap.get(phaseEntity.getId());
            Map<String, FtbCultivateLearnTaskPracticeVo> practiceTaskMap = new HashMap<>();
            if (CollUtil.isNotEmpty(taskPracticeList)) {
                for (FtbCultivateLearnTaskPracticeVo practice : taskPracticeList) {
                    practiceTaskMap.put(practice.getBusinessId(), practice);
                }
            }

            List<String> examIds = CollUtil.isNotEmpty(taskExamList) ? taskExamList.stream().map(FtbCultivateLearnTaskExamVo::getExamId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            List<String> identityIds = CollUtil.isNotEmpty(taskIdentificationList) ? taskIdentificationList.stream().map(FtbCultivateLearnTaskIdentificationVo::getIdentificationId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            List<String> certificateIds = CollUtil.isNotEmpty(taskCertificateList) ? taskCertificateList.stream().map(FtbCultivateLearnTaskCertificateVo::getCertificateId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            List<String> practiceIds = CollUtil.isNotEmpty(taskPracticeList) ? taskPracticeList.stream().map(FtbCultivateLearnTaskPracticeVo::getBusinessId).distinct().collect(Collectors.toList()) : new ArrayList<>();


            Map<String, FtbCultivateExamUser> userExamStatusMap = v2CultivateBatchQueryService.batchQueryUserExamStatus(userId, examIds);
            Map<String, CultivateIdentifyApply> userIdentificationStatusMap = v2CultivateBatchQueryService.batchQueryUserIdentificationStatus(userId, identityIds, 4, phaseEntity.getTaskId());
//            Map<String, FtbCertificateUserEntity> userCertificateStatusMap = v2CultivateBatchQueryService.batchQueryUserCertificateStatus(userId, certificateIds);
            Map<String, List<String>> userSkillStatusMap = v2CultivateBatchQueryService.batchQueryUserSkillStatus(userId, practiceIds);

            // 检查考试、技能和鉴定状态
            PhaseStatusResultVo phaseStatusResult = evaluatePhaseStatus(userId, taskId, tenantId, examIds, practiceIds, identityIds, phaseEntity, userExamStatusMap, userIdentificationStatusMap, practiceTaskMap, userSkillStatusMap);

            // 根据阶段完成条件处理证书和日志记录
            handlePhaseCompletion(userId, taskId, tenantId, phaseEntity, certificateIds, phaseStatusResult);
            List<FtbCultivateTaskLog> taskLogList = ftbCultivateTaskLogService.queryTaskPhaseLogs(userId, taskId, phaseEntity.getId());
            if (CollUtil.isNotEmpty(taskLogList)) {
                if (!taskLogList.get(0).getState().equals(2)) {
                    break;
                }
            }
        }
        //检查任务是否完成
        checkTaskComplete(taskId, userId);
    }

    private void checkAndSetTaskPhaseStart(String userId, String taskId, String phaseId) {
        ftbCultivateTaskLogService.checkAndSetTaskPhaseStart(userId, taskId, phaseId);
    }

    @Override
    public void preTaskCourseStudy(String userId, String courseId, String currTaskId, String tenantId) {
        List<String> taskIds = List.of(currTaskId);
        for (String taskId : taskIds) {
            // 验证任务有效性
            if (!validateTask(taskId, userId)) {
                return;
            }
            List<FtbCultivateLearnTaskPhase> phaseList = getFtbCultivateLearnTaskPhases(taskId);
            // 如果没有阶段，则直接返回
            if (CollUtil.isEmpty(phaseList)) {
                return;
            }
            //查询已经完成的阶段
            List<String> completePhaseIds = new ArrayList<>();
            List<FtbCultivateTaskLog> completePhaseList = ftbCultivateTaskLogService.queryCompleteTaskPhase(taskId, userId);
            if (CollUtil.isNotEmpty(completePhaseList)) {
                completePhaseIds = completePhaseList.stream().map(FtbCultivateTaskLog::getPhaseId).distinct().collect(Collectors.toList());
            }

            List<FtbCultivateLearnTaskCourseVo> courseEntities = ftbCultivateLearnTaskCourseService.listByTaskId(taskId, 0);
            List<FtbCultivateLearnTaskExamVo> examEntities = ftbCultivateLearnTaskExamService.listByTaskId(taskId);
            //课程按照阶段分组
            Map<String, List<FtbCultivateLearnTaskCourseVo>> phaseCourseMap = courseEntities.stream().filter(course -> course.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskCourseVo::getPhaseId));
            //考试按阶段分组
            Map<String, List<FtbCultivateLearnTaskExamVo>> phaseExamMap = examEntities.stream().filter(exam -> exam.getPhaseId() != null).collect(Collectors.groupingBy(FtbCultivateLearnTaskExamVo::getPhaseId));

            //确定是那个阶段
            for (FtbCultivateLearnTaskPhase phaseEntity : phaseList) {

                if (completePhaseIds.contains(phaseEntity.getId())) {
                    continue;
                }
                List<FtbCultivateLearnTaskCourseVo> taskCourseList = phaseCourseMap.get(phaseEntity.getId());
                if (CollUtil.isEmpty(taskCourseList)) {
                    break;
                }
                List<String> courseIds = CollUtil.isNotEmpty(taskCourseList) ? taskCourseList.stream().map(FtbCultivateLearnTaskCourseVo::getCourseId).distinct().collect(Collectors.toList()) : new ArrayList<>();
                boolean phaseCourseCompleteStatus = checkUserCourseCompleteStatus(userId, courseIds, phaseEntity.getTaskId(), phaseEntity.getId());
                if (!phaseCourseCompleteStatus) {
                    break;
                }
                List<FtbCultivateLearnTaskExamVo> taskExamList = phaseExamMap.get(phaseEntity.getId());
                List<String> examIds = CollUtil.isNotEmpty(taskExamList) ? taskExamList.stream().map(FtbCultivateLearnTaskExamVo::getExamId).distinct().collect(Collectors.toList()) : new ArrayList<>();
                Map<String, FtbCultivateExamUser> userExamStatusMap = v2CultivateBatchQueryService.batchQueryUserExamStatus(userId, examIds);
                // 处理考试状态
                if (CollUtil.isNotEmpty(examIds)) {
                    checkAndTriggerExam(userId, taskId, phaseEntity, examIds, userExamStatusMap, tenantId);
                } else {
                    ftbCultivateTaskLogService.saveExamTaskPhase(userId, taskId, phaseEntity.getId(), TaskStateEnum.NOT_CONFIGURED.getCode(), null);
                }
            }
        }
    }




    @Override
    public FtbCultivateExamUser checkAndTriggerExam(String userId, String taskId, FtbCultivateLearnTaskPhase phaseEntity, List<String> examIds, Map<String, FtbCultivateExamUser> userExamStatusMap, String tenantId) {
        PhaseExamStatusVo examStatusResult = evaluateExamStatus(userId, taskId, examIds, userExamStatusMap, tenantId);
        ftbCultivateTaskLogService.saveExamTaskPhase(userId, taskId, phaseEntity.getId(), examStatusResult.isCompleted() ? 1 : 0, examStatusResult.getExamUser());

        return examStatusResult.getExamUser();
    }

    private List<FtbCultivateLearnTaskPhase> getFtbCultivateLearnTaskPhases(String taskId) {
        LambdaQueryWrapper<FtbCultivateLearnTaskPhase> phaseWrapper = Wrappers.lambdaQuery();
        phaseWrapper.eq(FtbCultivateLearnTaskPhase::getTaskId, taskId);
        phaseWrapper.eq(FtbCultivateLearnTaskPhase::getEnableMark, 0); // 只查询有效的
        phaseWrapper.orderByAsc(FtbCultivateLearnTaskPhase::getCreatorTime);
        return ftbCultivateLearnTaskPhaseService.list(phaseWrapper);
    }

    /**
     * 验证任务有效性
     *
     * @param taskId 任务 ID
     * @param userId 用户 ID
     * @return 任务有效返回 true，否则返回 false
     */
    private boolean validateTask(String taskId, String userId) {
        FtbCultivateLearnTask task = ftbCultivateLearnTaskService.getById(taskId);
        if (task == null) {
            return false;
        }
        if (task.getEnableMark().equals(1)) {
            log.error("任务已删除，taskId={}, userId={}", taskId, userId);
            return false;
        }
        if (task.getTaskType().equals(1) && task.getStatus().equals(3)) {
            log.error("任务已结束，taskId={}, userId={}", taskId, userId);
            return false;
        }
        if (task.getStatus().equals(4)) {
            log.error("任务已终止，taskId={}, userId={}", taskId, userId);
            return false;
        }
        return true;
    }

    /**
     * 岗位鉴定学习
     *
     * @param message 培训信息
     */
    @Override
    public void dealTaskIdentityStudy(CultivateMqDTO message) {
        String userId = message.getUserId();
        String identityId = message.getBusinessId();
        String tenantId = message.getTenantId();
        if (StringUtils.isEmpty(identityId) || StringUtils.isEmpty(userId)) {
            log.error("dealTaskIdentityStudy参数异常，identityId={}, userId={}", identityId, userId);
            return;
        }
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userPrimaryBoundOne == null) {
            log.error("用户查询未null，identityId={}, userId={}", identityId, userId);
            return;
        }
        List<V2MyCultivateLearnTaskListVo> taskListVoList = ftbCultivateLearnTaskService.queryMyNoCompleteTaskListForUserId(userId);
        if (CollUtil.isEmpty(taskListVoList)) {
            return;
        }
        List<String> taskIds = taskListVoList.stream().map(V2MyCultivateLearnTaskListVo::getTaskId).collect(Collectors.toList());
        //过滤有改考试的任务
        taskIds = ftbCultivateLearnTaskService.queryTaskHasIdentityId(taskIds, identityId);
        if (CollUtil.isEmpty(taskIds)) {
            return;
        }
        for (String taskId : taskIds) {
            // 查询任务阶段表
            this.selfProxy.dealTaskStudyItem(userPrimaryBoundOne, taskId, tenantId);
        }

    }


    /**
     * 任务技能学习
     *
     * @param message 培训信息
     */
    @Override
    public void dealTaskPracticeStudy(CultivateMqDTO message) {
        String userId = message.getUserId();
        String practiceId = message.getBusinessId();
        String tenantId = message.getTenantId();
        if (StringUtils.isEmpty(practiceId) || StringUtils.isEmpty(userId)) {
            log.error("dealPositionExamStudy参数不完整，practiceId={}, userId={}", practiceId, userId);
            return;
        }
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userPrimaryBoundOne == null) {
            log.error("用户查询未null，practiceId={}, userId={}", practiceId, userId);
            return;
        }
        List<V2MyCultivateLearnTaskListVo> taskListVoList = ftbCultivateLearnTaskService.queryMyNoCompleteTaskListForUserId(userId);
        if (CollUtil.isEmpty(taskListVoList)) {
            return;
        }
        List<String> taskIds = taskListVoList.stream().map(V2MyCultivateLearnTaskListVo::getTaskId).collect(Collectors.toList());
        //过滤有改考试的任务
        taskIds = ftbCultivateLearnTaskService.queryTaskHasPracticeId(taskIds, practiceId);
        if (CollUtil.isEmpty(taskIds)) {
            return;
        }
        for (String taskId : taskIds) {
            // 查询任务阶段表
            this.selfProxy.dealTaskStudyItem(userPrimaryBoundOne, taskId, tenantId);
        }

    }


    /**
     * 删除申请详情
     *
     * @param appId 鉴定id
     */
    private void deleteApplyDetails(String appId) {
        applyDetailsService.update(new LambdaUpdateWrapper<CultivateIdentifyApplyDetails>().set(CultivateIdentifyApplyDetails::getDeleteMark, 1).eq(CultivateIdentifyApplyDetails::getApplyId, appId).eq(CultivateIdentifyApplyDetails::getDeleteMark, 0));
    }

    /**
     * 触发考试
     *
     * @param userId   用户id
     * @param examId   考试id
     * @param source   来源
     * @param sourceId 来源id
     */
    public FtbCultivateExamUser triggerExam(String userId, String examId, Integer source, String sourceId, String tenantId) {
        log.error("triggerExam userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
        CultivateExam ftbCultivateExam = v2CultivateExamMapper.selectById(examId);
        if (ftbCultivateExam == null) {
            log.error("triggerExam 考试不存在在 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
            return null;
        }
        if (ftbCultivateExam.getEnabledMark().equals(0)) {
            log.error("triggerExam 考试已删除 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
            return null;
        }
        //异常正常触发 用户考试的时候提示
//        if (ftbCultivateExam.getNeedUpdate().equals(2)) {
//            log.error("triggerExam 考试已结束 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
//            return null;
//        }

        //查看是否有记录
        LambdaQueryWrapper<FtbCultivateExamUser> wrapper = new LambdaQueryWrapper<FtbCultivateExamUser>().eq(FtbCultivateExamUser::getUserId, userId).eq(FtbCultivateExamUser::getExamId, examId).eq(FtbCultivateExamUser::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode()).orderByDesc(FtbCultivateExamUser::getCreatorTime);
        List<FtbCultivateExamUser> examUserList = ftbCultivateExamUserMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(examUserList)) {
            log.error("triggerExam 考试已经完成或存在 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);

            return examUserList.get(0);
        }

//        LambdaQueryWrapper<FtbCultivateExamUser> wrapperNoComplete = new LambdaQueryWrapper<FtbCultivateExamUser>().eq(FtbCultivateExamUser::getUserId, userId).eq(FtbCultivateExamUser::getExamId, examId).in(FtbCultivateExamUser::getStatus, 0, 2).eq(FtbCultivateExamUser::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
//        List<FtbCultivateExamUser> examUserListComplete = ftbCultivateExamUserMapper.selectList(wrapperNoComplete);
//        if (CollUtil.isNotEmpty(examUserListComplete)) {
//            log.error("triggerExam 考试已经存在 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
//            return;
//        }


        List<CultivateExamDrawRule> ruleList = examDrawRuleService.list(new LambdaQueryWrapper<CultivateExamDrawRule>().eq(CultivateExamDrawRule::getExamId, ftbCultivateExam.getId()));


        //2、没有就写入一条记录
        FtbCultivateExamUser user = FtbCultivateExamUser.builder().examId(examId).examType(ftbCultivateExam.getExamType()).userId(userId).status(CourseEnums.ExamStatus.WAIT.getCode()).examSource(source).enabledMark(CourseEnums.EnabledMarkType.VALID.getCode()).batch(UUID.randomUUID().toString().replaceAll("-", "")).userExamCount(1).build();
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userPrimaryBoundOne != null && userPrimaryBoundOne.getOrganizeId() != null) {
            user.setUserOrgList(userPrimaryBoundOne.getOrganizeId());
        }
        if (CollUtil.isNotEmpty(ruleList)) {
            user.setPickQuestionRule(JSON.toJSONString(ruleList));
            int totalScore = 0;
            int questionNumber = 0;
            for (CultivateExamDrawRule cultivateExamDrawRule : ruleList) {
                totalScore += cultivateExamDrawRule.getScore() * cultivateExamDrawRule.getPickCount();
                questionNumber += cultivateExamDrawRule.getPickCount();
            }
            user.setTotalScore(totalScore);
            user.setQuestionNumber(questionNumber);
            user.setPassScore(QuestionAnalysisUtil.calPassScore(totalScore, ftbCultivateExam));
            user.setExcellentScore(QuestionAnalysisUtil.calExcellentScore(totalScore, ftbCultivateExam));
            user.setExamTime(ftbCultivateExam.getExamTime());
        }
        if (source.equals(2)) {
            user.setRelationPositionId(sourceId);
        } else if (source.equals(4)) {
            user.setRelationTaskId(sourceId);
        }
        ftbCultivateExamUserMapper.insert(user);
        log.error("triggerExam 生成考试记录 userId={},examId={},source={},sourceId={}", userId, examId, source, sourceId);
        return user;
    }

    /**
     * 触发鉴定
     *
     * @param userId     用户id
     * @param identifyId 鉴定id
     * @param source     鉴定来源(0手动发起，1课程学习鉴定，2岗位学习鉴定，3本人申请,4任务鉴定)
     * @param sourceId   鉴定来源id
     * @param phaseId    阶段
     */
    public CultivateIdentifyApply triggerIdentification(String userId, String identifyId, Integer source, String sourceId, String phaseId, String tenantId) {
        log.info("触发鉴定  userId={},  identifyId={},  source={},  sourceId ={}", userId, identifyId, source, sourceId);
        CultivateIdentifyTable table = identifyTableService.getById(identifyId);
        if (table == null) {
            log.error("鉴定表不存在  userId={},  identifyId={},  source={},  sourceId ={}", userId, identifyId, source, sourceId);
            return null;
        }

        List<CultivateIdentifyItems> identifyItemsList = this.identifyItemsService.lambdaQuery().eq(CultivateIdentifyItems::getTableId, table.getId()).eq(CultivateIdentifyItems::getDeleteMark, ConstantUtil.NUM_FALSE).list();
        if (CollUtil.isEmpty(identifyItemsList)) {
            log.error("鉴定表项不存在  userId={},  identifyId={},  source={},  sourceId ={}", userId, identifyId, source, sourceId);
        }
        UserBoundVO userBoundVO = userApiV2Util.getUserPrimaryBoundOne(userId, tenantId);
        if (userBoundVO == null) {
            return null;
        }
        LambdaQueryWrapper<CultivateIdentifyApply> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CultivateIdentifyApply::getSourceId, sourceId);
        wrapper.eq(CultivateIdentifyApply::getSource, source);
        wrapper.eq(CultivateIdentifyApply::getOriginalTableId, table.getId());
        wrapper.eq(CultivateIdentifyApply::getBeIdentifyUserId, userId);
        wrapper.eq(CultivateIdentifyApply::getPhaseId, phaseId);
        wrapper.eq(CultivateIdentifyApply::getDeleteMark, ConstantUtil.NUM_FALSE);
        wrapper.orderByDesc(CultivateIdentifyApply::getCreatorTime);
        List<CultivateIdentifyApply> oldApplyLists = identifyApplyService.list(wrapper);

        if (CollUtil.isNotEmpty(oldApplyLists)) {
            CultivateIdentifyApply oldApply = oldApplyLists.get(0);
            if (oldApply.getStatus().equals(1) || oldApply.getStatus().equals(0)) {
                return oldApply;
            }
            oldApply.setDeleteMark(1);
            deleteApplyDetails(oldApply.getId());
            identifyApplyService.updateById(oldApply);
        }
        CultivateIdentifyApply apply = new CultivateIdentifyApply();
        apply.setId(UUID.randomUUID().toString());
        apply.setIdentifyUserId("");
        apply.setIdentifyOrgList("");
        apply.setSourceId(sourceId);
        apply.setSource(source);
        apply.setTableId(table.getId());
        apply.setOriginalTableId(table.getId());
        apply.setName(table.getName());
        apply.setBeIdentifyUserId(userId);
        apply.setStatus(ApplyStatusEnum.DJD.getCode());
        apply.setAppraisalResults(ConstantUtil.NUM_FALSE);
        apply.setUseTime(0);
        apply.setIsVisible(0);
        apply.setPhaseId(phaseId);

        //设置被鉴定人信息
        apply.setIsChoose(ConstantUtil.NUM_FALSE);
        apply.setStudyFinishTime(new Date());
        apply.setIsReIdentify(ConstantUtil.NUM_FALSE);
        apply.setDeleteMark(0);
        // 岗位学习和课程实操鉴定，不进行直属主管判定，因为直属主管需要组织、岗位、职等进行确定

        //被鉴定人组织信息
        List<UserOrgInfoAll1Vo> beIdentifyUserInfoJsonList = CollUtil.newArrayList();
        UserOrgInfoAll1Vo all1Vo = new UserOrgInfoAll1Vo();
        all1Vo.setUserOrgCode(userBoundVO.getOrganizeEnCode());
        all1Vo.setUserOrgName(userBoundVO.getOrganizeName());
        all1Vo.setUserPostCode(userBoundVO.getPositionEnCode());
        all1Vo.setUserPostName(userBoundVO.getPositionName());
        all1Vo.setUserOfficialRankCode(userBoundVO.getGradeId());
        all1Vo.setUserOfficialRankName(userBoundVO.getGradeName());
        beIdentifyUserInfoJsonList.add(all1Vo);

        apply.setBeIdentifyOrgList(userBoundVO.getOrganizeId());
        apply.setBeOfficialRankInfoJson(JSON.toJSONString(beIdentifyUserInfoJsonList));

        //生成鉴定表、鉴定项备份数据
        CultivateIdentifyApplyTableBackups applyTableBackups = new CultivateIdentifyApplyTableBackups();
        BeanUtils.copyProperties(table, applyTableBackups);
        applyTableBackups.setId(RandomUtil.uuId());
        applyTableBackups.setTableId(table.getId());
        apply.setTableId(applyTableBackups.getId());

        List<CultivateIdentifyApplyDetailsBackups> applyDetailsBackupsList = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(identifyItemsList)) {
            applyDetailsBackupsList.addAll(identifyItemsList.stream().map(item -> {
                CultivateIdentifyApplyDetailsBackups applyDetailsBackups = new CultivateIdentifyApplyDetailsBackups();
                BeanUtils.copyProperties(item, applyDetailsBackups);
                applyDetailsBackups.setId(RandomUtil.uuId());
                applyDetailsBackups.setItemsId(item.getId());
                applyDetailsBackups.setTableId(applyTableBackups.getId());
                applyDetailsBackups.setDeleteMark(0);
                return applyDetailsBackups;
            }).collect(Collectors.toList()));
        }
        //生成鉴定项数据
        List<CultivateIdentifyApplyDetails> applyDetailsList = CollUtil.newArrayList();

        applyDetailsList.addAll(applyDetailsBackupsList.stream().map(item -> {
            CultivateIdentifyApplyDetails applyDetails = new CultivateIdentifyApplyDetails();
            applyDetails.setApplyId(apply.getId());
            applyDetails.setItemsId(item.getId());
            applyDetails.setDeleteMark(0);
            return applyDetails;
        }).collect(Collectors.toList()));
        //保存备份数据
        applyTableBackupsService.save(applyTableBackups);
        if (CollUtil.isNotEmpty(applyDetailsBackupsList)) {
            applyDetailsBackupsService.saveBatch(applyDetailsBackupsList);
        }

        if (CollUtil.isNotEmpty(applyDetailsList)) {
            this.applyDetailsService.saveBatch(applyDetailsList);
        }
        identifyApplyService.save(apply);
        return apply;
    }

    /**
     * 鉴定表项是否触发任务证书颁发
     *
     * @param userId        用户id
     * @param certificateId 证书id
     * @param taskId        任务id
     * @param phaseId       阶段id
     * @return true-已经触发过了  false-未触发
     */
    private Boolean checkIsTriggerTaskCertificate(String userId, String certificateId, String taskId, String phaseId) {
        //查询是否颁发
        LambdaQueryWrapper<FtbCultivateCertificateResult> certificateResultLambdaQueryWrapper = Wrappers.lambdaQuery();
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getUserId, userId);
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getCertificateId, certificateId);
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getTaskId, taskId);
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getPhaseId, phaseId);
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getType, 3);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        return ftbCultivateCertificateResultMapper.selectCount(certificateResultLambdaQueryWrapper) > 0;
    }

    /**
     * 记录触发的任务证书
     *
     * @param userId        用户id
     * @param certificateId 证书id
     * @param taskId        任务id
     * @param phaseId       阶段id
     */
    private void recordTriggerTaskCertificate(String userId, String certificateId, String taskId, String phaseId) {
        FtbCultivateCertificateResult cultivateCertificateResult = new FtbCultivateCertificateResult();
        cultivateCertificateResult.setUserId(userId);
        cultivateCertificateResult.setCertificateId(certificateId);
        cultivateCertificateResult.setTaskId(taskId);
        cultivateCertificateResult.setPhaseId(phaseId);
        cultivateCertificateResult.setType(3);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        ftbCultivateCertificateResultMapper.insert(cultivateCertificateResult);
    }

    /**
     * 触发证书
     *
     * @param userId        用户id
     * @param certificateId 证书id
     * @param tenantId      租户id
     */
    public void triggerCertificate(String userId, String certificateId, String tenantId) {
        v2CultivateCertificateService.triggerCertificate(userId, certificateId, tenantId);
    }


}