package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.CultivateDateTimeUtils;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.CultivateIdentifyTable;
import jnpf.exception.HandleException;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.bo.TriggerEventBO;
import jnpf.model.cultivate.dto.learn.FtbCultivateLearnTaskListDto;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.examidentify.ExamIdentifyTriggerEventDTO;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.exam.FtbCultivateExam;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.*;
import jnpf.model.cultivate.po.paper.FtbCultivateTestPaper;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.vo.course.app.FtbAppTaskCountVO;
import jnpf.model.cultivate.vo.course.app.FtbGlobalCurriculumAppVO;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskExamInfoVO;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskIdentificationInfoVO;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskInfoForAppVO;
import jnpf.model.cultivate.vo.learn.FtbCultivateMyLearnTaskListVO;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.context.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author: peng.hao
 * @create: 2024/9/11:14:51
 */
@Slf4j
@Service
public class FtbCultivateMyLearnTaskInfoServiceImpl implements FtbCultivateMyLearnTaskInfoService {

    @Resource
    private FtbCultivateLearnTaskMapper ftbCultivateLearnTaskMapper;

    @Resource
    private FtbCultivateLearnTaskInfoMapper ftbCultivateLearnTaskInfoMapper;

    @Resource
    private FtbCultivateLearnTaskInfoService ftbCultivateLearnTaskInfoService;

    @Resource
    private FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;

    @Resource
    private FtbCultivateLearnTaskCourseMapper ftbCultivateLearnTaskCourseMapper;

    @Resource
    private FtbCultivateLearnTaskExamMapper learnTaskExamMapper;

    @Resource
    private FtbCultivateLearnTaskIdentificationMapper learnTaskIdentificationMapper;

    @Resource
    private FtbCultivateExamUserService ftbCultivateExamUserService;

    @Resource
    private CultivateIdentifyApplyMapper cultivateIdentifyApplyMapper;

    @Resource
    private FtbCultivateExamService ftbCultivateExamService;

    @Resource
    private FtbCultivateMyLearnTaskInfoMapper ftbCultivateMyLearnTaskInfoMapper;

    @Resource
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    private FtbCultivateLearnCategoriesService cultivateLearnCategoriesService;

    @Resource
    private FtbCultivateExamMapper ftbCultivateExamMapper;

    @Resource
    private FtbCultivateTestPaperMapper ftbCultivateTestPaperMapper;

    @Resource
    private CultivateIdentifyTableMapper cultivateIdentifyTableMapper;

    @Resource
    private CultivateIdentifyApplyDetailsMapper cultivateIdentifyApplyDetailsMapper;

    @Resource
    private FtbCultivateCourseMapper ftbCultivateCourseMapper;

    @Override
    @Transactional
    public PageListVO<FtbCultivateMyLearnTaskListVO> taskList(FtbCultivateLearnTaskListDto taskListDto) {
        String userId = UserProvider.getUser().getUserId();
        // 更新任务状态
        ftbCultivateLearnTaskInfoService.updateUserFinishTime(userId);
        taskListDto.setUserId(userId);
        Page<FtbCultivateMyLearnTaskListVO> tPage = taskListDto.coverCultivatePage();
        Page<FtbCultivateMyLearnTaskListVO> taskPage = ftbCultivateLearnTaskInfoMapper.queryTaskList(tPage, taskListDto);
        taskPage.getRecords().forEach(item -> {
            if (item.getTaskType() == 1) {
                // 获取任务状态
                Date learningEndTime = item.getTimeLimitEndTime();
                String remainingValue = CultivateDateTimeUtils.calculateRemainingValue(new Date(), learningEndTime, 0);
                item.setDaysRemaining(remainingValue);
            }
        });
        return CultivatePage.coverPageList(taskPage);
    }

    /**
     * 查询任务课程列表
     *
     * @param taskId     任务主键ID(必传)
     * @param userId
     * @param compulsory
     * @return
     * @throws HandleException
     */
    @Override
    public List<FtbGlobalCurriculumAppVO> taskCourseList(String taskId, String userId, Integer compulsory) throws HandleException {

        List<FtbGlobalCurriculumAppVO> curriculumAppVOS = ftbCultivateMyLearnTaskInfoMapper.queryCourseList(taskId, userId, compulsory);
        curriculumAppVOS.forEach(item -> {
            // 学习总人数
            LambdaQueryWrapper<FtbCultivatePositionCourceLearning> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(FtbCultivatePositionCourceLearning::getState, List.of(1, 2));
            queryWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, item.getCourseId());
            queryWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            item.setLearnTotalNumber(ftbCultivatePositionCourceLearningMapper.selectCount(queryWrapper));
        });
        // 查询当前任务是否开始
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        wrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        wrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        FtbCultivateLearnTaskAssignment taskAssignment = ftbCultivateLearnTaskAssignmentMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(taskAssignment)) {
            throw new HandleException("已变更，无法继续完成");
        }
        // 0是必修 && 学习状态为开始
        if (compulsory == 0 && taskAssignment.getStudyStats() == 1) {
            // 任务必修课程
            LambdaQueryWrapper<FtbCultivateLearnTaskCourse> taskCourseQueryWrapper = Wrappers.lambdaQuery();
            taskCourseQueryWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, taskId);
            taskCourseQueryWrapper.eq(FtbCultivateLearnTaskCourse::getEnableMark, 0);
            taskCourseQueryWrapper.eq(FtbCultivateLearnTaskCourse::getIsRequired, 0);
            List<FtbCultivateLearnTaskCourse> ftbCultivateLearnTaskCourses = ftbCultivateLearnTaskCourseMapper.selectList(taskCourseQueryWrapper);
            List<String> courseIds = ftbCultivateLearnTaskCourses.stream()
                    .map(FtbCultivateLearnTaskCourse::getCourseId)
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(courseIds)) {
                boolean isStartStudyCourse = checkCourseStudyStatus(userId, courseIds);
                if (isStartStudyCourse == true) {
                    int needStudyNum = 0;
                    LambdaQueryWrapper<FtbCultivateCourse> courseWraper = Wrappers.lambdaQuery();
                    courseWraper.in(FtbCultivateCourse::getId, courseIds);
                    courseWraper.eq(FtbCultivateCourse::getEnableMark, 0);
                    courseWraper.eq(FtbCultivateCourse::getIsGroundIng, 1);//上下架（0下架，1上架）
                    List<FtbCultivateCourse> ftbCultivateCourses = ftbCultivateCourseMapper.selectList(courseWraper);
                    if (CollUtil.isEmpty(ftbCultivateCourses)) {
                        needStudyNum = 0;
                    } else {
                        needStudyNum = ftbCultivateCourses.size();
                        courseIds = ftbCultivateCourses.stream()
                                .map(FtbCultivateCourse::getId)
                                .collect(Collectors.toList());
                    }

                    if (needStudyNum == 0 || hasTheCourseBeenCompleted(userId, courseIds)) {
                        SpringContext.getApplicationContext()
                                .publishEvent(new JnpfApplicationEvent<>(
                                        ExamIdentifyTriggerEventDTO.builder()
                                                .taskId(taskId)
                                                .userId(userId)
                                                .triggerEventType(TriggerEventBO.TriggerEventType.TASK)
                                                .build()));
                    }
                }
            }
        }
        return curriculumAppVOS;
    }

    /**
     * 查询课程是否开始学习了
     *
     * @param userId    用户ID
     * @param courseIds 课程id
     * @return true -开始学习  false-未开始学习
     */
    private boolean checkCourseStudyStatus(String userId, List<String> courseIds) {
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> query = Wrappers.lambdaQuery();
        query.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        query.in(FtbCultivatePositionCourceLearning::getCourceId, courseIds);
        query.in(FtbCultivatePositionCourceLearning::getState, List.of("1"));//学习状态 1已学习，0未学习,2学习中
        query.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        return ftbCultivatePositionCourceLearningMapper.selectCount(query) > 0;
    }

    /**
     * 查询是否完成了课程学习
     *
     * @param userId    用户id
     * @param courseIds 课程id
     * @return
     */
    private boolean hasTheCourseBeenCompleted(String userId, List<String> courseIds) {
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> query = Wrappers.lambdaQuery();
        query.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        query.in(FtbCultivatePositionCourceLearning::getCourceId, courseIds);
        query.in(FtbCultivatePositionCourceLearning::getState, List.of("0", "2"));
        query.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        return ftbCultivatePositionCourceLearningMapper.selectCount(query) == 0;
    }

    @Override
    public FtbCultivateLearnTaskInfoForAppVO getLearnTaskInfoForApp(String taskId) {
        // 任务已变更，无法继续完成；
        LambdaQueryWrapper<FtbCultivateLearnTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateLearnTask::getId, taskId);
        FtbCultivateLearnTask ftbCultivateLearnTask = ftbCultivateLearnTaskMapper.selectOne(queryWrapper);
        if (ftbCultivateLearnTask == null) throw new RuntimeException("任务已变更，无法继续完成!");
        // if (ftbCultivateLearnTask.getStatus() == 3) throw new RuntimeException("任务已结束，无法继续完成!");
        // 查询当前人的任务状态
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskAssignmentLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, UserProvider.getUser().getUserId());
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        FtbCultivateLearnTaskAssignment taskAssignment = ftbCultivateLearnTaskAssignmentMapper.selectOne(taskAssignmentLambdaQueryWrapper);
        FtbCultivateLearnTaskInfoForAppVO convert = FtbCultivateLearnTaskInfoForAppVO.convert(ftbCultivateLearnTask);
        convert.setStudyStats(taskAssignment.getStudyStats());
        //  添加分类名称
        FtbCultivateLearnCategories categories = cultivateLearnCategoriesService.getById(convert.getTaskClass());
        convert.setTaskClassName(categories.getName());
        return convert;
    }

    @Override
    public void completeTask(String taskId) {
        String userId = UserProvider.getUser().getUserId();
        // 更新学习开始时间
        LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId)
                .eq(FtbCultivateLearnTaskAssignment::getUserId, userId)
                .eq(FtbCultivateLearnTaskAssignment::getEnableMark,0)
                .set(FtbCultivateLearnTaskAssignment::getLearningStartTime, new Date())
                .set(FtbCultivateLearnTaskAssignment::getStudyStats, 1);
        ftbCultivateLearnTaskAssignmentMapper.update(null, updateWrapper);
    }

    @Override
    public List<FtbCultivateLearnTaskExamInfoVO> taskExamList(String taskId, String userId) {
        List<FtbCultivateLearnTaskExamInfoVO> reult = new ArrayList<>();
        // 添加考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> examLambdaQueryWrapper = Wrappers.lambdaQuery();
        examLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, taskId);
        FtbCultivateLearnTaskExam taskExam = learnTaskExamMapper.selectOne(examLambdaQueryWrapper);
        if (taskExam == null) return reult;

        // 根据任务ID和用户ID查询考试结果
        List<FtbCultivateExamUser> cultivateExamUser = ftbCultivateExamUserService.queryExamResultForTaskInfo(taskId, userId);
        // 只返回考试
        if (CollUtil.isEmpty(cultivateExamUser)) {
            FtbCultivateExam ftbCultivateExam = ftbCultivateExamMapper.selectById(taskExam.getExamId());
            FtbCultivateLearnTaskExamInfoVO learnTaskExamInfoVO = FtbCultivateLearnTaskExamInfoVO.convertExam(taskExam);
            learnTaskExamInfoVO.setExamName(ftbCultivateExam.getExamName());
            learnTaskExamInfoVO.setExamStatus(0);
            learnTaskExamInfoVO.setExamType(ftbCultivateExam.getExamType());
            learnTaskExamInfoVO.setExamTime(ftbCultivateExam.getExamTime());
            learnTaskExamInfoVO.setExamId(ftbCultivateExam.getId());
            //由于任务只关联一个考试  查询考试关联的试卷信息
            if (null != ftbCultivateExam && StringUtils.isNotEmpty(ftbCultivateExam.getPaperId())) {
                FtbCultivateTestPaper paper = ftbCultivateTestPaperMapper.selectById(ftbCultivateExam.getPaperId());
                if (null != paper) {
                    learnTaskExamInfoVO.setPaperName(paper.getName());
                }
            }
            reult.add(learnTaskExamInfoVO);
            return reult;
        }
        // 使用Lambda表达式创建查询包装器
        LambdaQueryWrapper<FtbCultivateExam> queryWrapper = Wrappers.lambdaQuery();
        // 根据考试ID列表查询考试详情
        queryWrapper.in(SuperBaseEntity.SuperIBaseEntity::getId, cultivateExamUser.stream().map(FtbCultivateExamUser::getExamId).collect(Collectors.toList()));
        List<FtbCultivateExam> list = ftbCultivateExamService.list(queryWrapper);
        // 初始化一个映射考试ID到考试详情的Map
        Map<String, FtbCultivateExam> collect = new HashMap<>();
        if (CollUtil.isNotEmpty(list)) {
            // 将查询到的考试详情列表转换为Map，以考试ID为键
            collect = list.stream().collect(Collectors.toMap(SuperBaseEntity.SuperIBaseEntity::getId, Function.identity()));
        }
        Map<String, FtbCultivateExam> finalCollect = collect;
        // 将考试结果和考试详情合并
        return cultivateExamUser.stream().map(vo -> {
            // 根据考试ID获取考试详情
            FtbCultivateExam ftbCultivateExam = finalCollect.get(vo.getExamId());
            // 将考试结果转换为VO
            FtbCultivateLearnTaskExamInfoVO learnTaskExamInfoVO = FtbCultivateLearnTaskExamInfoVO.convert(vo);
            // 如果考试详情存在，则设置考试分数和名称
            if (ftbCultivateExam != null) {
                learnTaskExamInfoVO.setExamScore(ftbCultivateExam.getCurrTotalScore());
                learnTaskExamInfoVO.setExamName(ftbCultivateExam.getExamName());
                learnTaskExamInfoVO.setExamTime(ftbCultivateExam.getExamTime());
            }
            if ( StringUtils.isNotEmpty(vo.getPaperId())) {
                FtbCultivateTestPaper paper = ftbCultivateTestPaperMapper.selectById(vo.getPaperId());
                if (null != paper) {
                    learnTaskExamInfoVO.setPaperName(paper.getName());
                }
            }
            return learnTaskExamInfoVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<FtbCultivateLearnTaskIdentificationInfoVO> taskIdentificationList(String taskId, String userId) {
        List<FtbCultivateLearnTaskIdentificationInfoVO> reult = new ArrayList<>();
        // 添加鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> identificationLambdaQueryWrapper = Wrappers.lambdaQuery();
        identificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, taskId);
        FtbCultivateLearnTaskIdentification learnTaskIdentification = learnTaskIdentificationMapper.selectOne(identificationLambdaQueryWrapper);
        if (learnTaskIdentification == null) return reult;
        FtbCultivateLearnTaskIdentificationInfoVO identificationUserInfoVO = new FtbCultivateLearnTaskIdentificationInfoVO();
        CultivateIdentifyTable cultivateIdentifyTable = cultivateIdentifyTableMapper.selectById(learnTaskIdentification.getIdentificationId());
        if (cultivateIdentifyTable != null) {
            identificationUserInfoVO.setIdentificationName(cultivateIdentifyTable.getName());
            identificationUserInfoVO.setIdentificationId(cultivateIdentifyTable.getId());
            identificationUserInfoVO.setIdentificationName(cultivateIdentifyTable.getName());
            identificationUserInfoVO.setIdentificationType(4);
        }
        List<FtbCultivateLearnTaskIdentificationInfoVO> ftbCultivateLearnTaskIdentificationInfoVOS = cultivateIdentifyApplyMapper.queryIdentifyApplyInfo(taskId, userId);
        // 鉴定
        if (CollUtil.isEmpty(ftbCultivateLearnTaskIdentificationInfoVOS)) {
            reult.add(identificationUserInfoVO);
            return reult;
        }
        for (FtbCultivateLearnTaskIdentificationInfoVO ftbCultivateLearnTaskIdentificationInfoVO : ftbCultivateLearnTaskIdentificationInfoVOS) {
            BigDecimal identificationScore = cultivateIdentifyApplyDetailsMapper.countSumScore(ftbCultivateLearnTaskIdentificationInfoVO.getIdentificationId());
            ftbCultivateLearnTaskIdentificationInfoVO.setIdentificationScore(identificationScore);
        }
        return ftbCultivateLearnTaskIdentificationInfoVOS;
    }

    @Override
    public void updateUserFinishTime(String taskId, String userId, Integer source) {
        log.error("updateUserFinishTime: taskId:{}, userId:{} , source:{}", taskId, userId, source);
        // 查询是否有
        //  0:课程 1：考试 2：鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskCourse> courseLambdaQueryWrapper = Wrappers.lambdaQuery();
        courseLambdaQueryWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, taskId);
        courseLambdaQueryWrapper.eq(FtbCultivateLearnTaskCourse::getEnableMark, 0);
        List<FtbCultivateLearnTaskCourse> cultivateLearnTaskCourse = ftbCultivateLearnTaskCourseMapper.selectList(courseLambdaQueryWrapper);
        // 查询任务绑定考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> learnTaskExamLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskExamLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, taskId);
        learnTaskExamLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getEnableMark, 0);
        FtbCultivateLearnTaskExam ftbCultivateLearnTaskExam = learnTaskExamMapper.selectOne(learnTaskExamLambdaQueryWrapper);
        // 查询任务绑定实操鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> learnTaskIdentificationLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskIdentificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, taskId);
        learnTaskIdentificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getEnableMark, 0);
        FtbCultivateLearnTaskIdentification learnTaskIdentification = learnTaskIdentificationMapper.selectOne(learnTaskIdentificationLambdaQueryWrapper);
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId)
                .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                .eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        FtbCultivateLearnTaskAssignment taskAssignment = ftbCultivateLearnTaskAssignmentMapper.selectOne(queryWrapper);


        if (taskAssignment != null && 2 == taskAssignment.getStudyStats()) return;
        if (source == 0 && CollUtil.isNotEmpty(cultivateLearnTaskCourse)
                && (ftbCultivateLearnTaskExam == null && learnTaskIdentification == null)) {
            // 更新学习开始时间
            LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId)
                    .eq(FtbCultivateLearnTaskAssignment::getUserId, userId)
                    .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                    .set(FtbCultivateLearnTaskAssignment::getStudyStats, 2)
                    .set(FtbCultivateLearnTaskAssignment::getLearningEndTime, new Date());
            ftbCultivateLearnTaskAssignmentMapper.update(null, updateWrapper);
        } else {
            boolean examFlag = false, identificationFlag = false;
            if (ftbCultivateLearnTaskExam == null) {
                examFlag = true;
            } else {
                Integer isPassComplete = ftbCultivateLearnTaskExam.getIsPassComplete();
                // 考试情况
                // 考试id
                // 根据任务id加考试id+用户id查询当前人的考试情况
                String examId = ftbCultivateLearnTaskExam.getExamId();
                //-1 没有考试记录 0:未完成考试 3合格 5优秀

                Integer forTask = ftbCultivateExamUserService.queryExamResultForTask(taskId, userId);
//                if (forTask != -1) examFlag = true;
                if (forTask == 3 || forTask == 5) {
                    examFlag = true;
                }
                if (isPassComplete == 0 && forTask > 0 && forTask != 1) {
                    //不需要考试合格才算完成
                    examFlag = true;
                }

            }
            // 不存在鉴定
            if (learnTaskIdentification == null) {
                identificationFlag = true;
            } else {
                Integer isPassComplete = learnTaskIdentification.getIsPassComplete();
                // 根据任务id加鉴定id+用户id查询当前人的鉴定情况
                LambdaQueryWrapper<CultivateIdentifyApply> identifyApplyLambdaQueryWrapper = Wrappers.lambdaQuery();
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getSourceId, taskId);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getBeIdentifyUserId, userId);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getDeleteMark, 0);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getSource, 4);
                CultivateIdentifyApply identifyApply = cultivateIdentifyApplyMapper.selectOne(identifyApplyLambdaQueryWrapper);
                if (identifyApply == null) return;
                //鉴定结果(0-合格，1-优秀，2-不合格)
                Integer result = identifyApply.getResult();
                // 颁发规则鉴定(0 合格, 1 优秀)
                if (result != null && result != 2) identificationFlag = true;

                if (isPassComplete == 0) {
                    identificationFlag = true;
                }
            }
            if (examFlag && identificationFlag) {
                LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId)
                        .eq(FtbCultivateLearnTaskAssignment::getUserId, userId)
                        .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                        .set(FtbCultivateLearnTaskAssignment::getStudyStats, 2)
                        .set(FtbCultivateLearnTaskAssignment::getLearningEndTime, new Date());
                ftbCultivateLearnTaskAssignmentMapper.update(null, updateWrapper);
            }
        }
    }
    /**
     * 获取任务列表总数
     * @param keyWords 任务名称
     * @return
     */
    @Override
    public Map<String, Integer> taskListCount( String keyWords) {
        String userId = UserProvider.getUser().getUserId();
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        queryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        List<FtbCultivateLearnTaskAssignment> taskAssignments = ftbCultivateLearnTaskAssignmentMapper.selectList(queryWrapper);
        Map<String, Integer> maps = new HashMap<>();
        if (CollUtil.isEmpty(taskAssignments)) {
            return maps;
        }

        //查询已发布任务信息
        List<String> taskIds = taskAssignments.stream().map(FtbCultivateLearnTaskAssignment::getTaskId).collect(Collectors.toList());
        QueryWrapper<FtbCultivateLearnTask> taskQuery = new QueryWrapper<>();
        taskQuery.lambda()
                .ne(FtbCultivateLearnTask::getStatus, 0)
                .like(StringUtil.isNotEmpty(keyWords), FtbCultivateLearnTask::getTaskName, keyWords)
                .in(FtbCultivateLearnTask::getId, taskIds);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskMapper.selectList(taskQuery);

        if (taskAssignments != null) {
            maps.put("toBeCompleted", getTaskStatus(taskAssignments, 1, taskList));
            maps.put("done", getTaskStatus(taskAssignments, 0, taskList));
        }
        return maps;
    }

    /**
     * 查询任务数量
     * @param taskId 任务id
     * @param userId 用户ID
     * @return
     */
    @Override
    public FtbAppTaskCountVO taskCourseNum(String taskId, String userId) {
        List<FtbGlobalCurriculumAppVO> vo = ftbCultivateMyLearnTaskInfoMapper.queryCourseList(taskId, userId, null);
        int totalCount = CollUtil.isEmpty(vo) ? 0 : vo.size();
        FtbAppTaskCountVO ftbAppTaskCountVO =new FtbAppTaskCountVO();
        ftbAppTaskCountVO.setAllCourseNum(totalCount);
        return ftbAppTaskCountVO;
    }

    /**
     * 获取任务状态
     */
    private Integer getTaskStatus(List<FtbCultivateLearnTaskAssignment> taskAssignments, Integer flag, List<FtbCultivateLearnTask> publishTaskList) {
        Predicate<FtbCultivateLearnTaskAssignment> predicate;
        if (flag == 0) {
            predicate = item -> item.getStudyStats() == 2;
        } else {
            predicate = item -> item.getStudyStats() != 2;
        }
        long count = taskAssignments.stream().filter(predicate)
                .filter(f -> {
                    //未发布不计入统计
                    return publishTaskList.stream().map(FtbCultivateLearnTask::getId).collect(Collectors.toList()).contains(f.getTaskId());
                })
                .count();
        return Math.toIntExact(count);
    }

}
