package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.FtbCultivateLearnCategoriesService;
import jnpf.cultivate.service.FtbCultivateLearnTaskAssignmentService;
import jnpf.cultivate.service.FtbCultivateLearnTaskInfoService;
import jnpf.cultivate.service.FtbCultivateLearnTaskListService;
import jnpf.cultivate.utils.CultivateDateTimeUtils;
import jnpf.cultivate.utils.CultivateLearnUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.entity.cultivate.CultivateIdentifyTable;
import jnpf.enums.cultivate.v2.LearnTaskStatusEnum;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.learn.FtbCultivateLearnTaskListDto;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.course.FtbCultivateCourseType;
import jnpf.model.cultivate.po.exam.FtbCultivateExam;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.*;
import jnpf.model.cultivate.vo.learn.*;
import jnpf.model.cultivate.vo.learn.info.*;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Author: peng.hao
 * @create: 2024/9/9:14:50
 */
@Slf4j
@Service
public class FtbCultivateLearnTaskInfoServiceImpl implements FtbCultivateLearnTaskInfoService {

    @Resource
    private FtbCultivateLearnTaskMapper ftbCultivateLearnTaskMapper;

    @Resource
    private FtbCultivateLearnTaskInfoMapper ftbCultivateLearnTaskInfoMapper;

    @Resource
    private FtbCultivateLearnTaskCourseMapper cultivateLearnTaskCourseMapper;

    @Resource
    private FtbCultivateLearnTaskExamMapper cultivateLearnTaskExamMapper;

    @Resource
    private FtbCultivateExamMapper ftbCultivateExamMapper;

    @Resource
    private FtbCultivateLearnTaskIdentificationMapper cultivateLearnTaskIdentificationMapper;

    @Resource
    private CultivateIdentifyTableMapper cultivateIdentifyTableMapper;

    @Resource
    private FtbCultivateLearnTaskCertificateMapper cultivateLearnTaskCertificateMapper;

    @Resource
    private FtbCultivateCertificateMapper certificateMapper;

    @Resource
    private FtbCultivateCourseTypeMapper cultivateCourseTypeMapper;

    @Resource
    private FtbCultivateCourseMapper cultivateCourseMapper;

    @Resource
    private FtbCultivateLearnTaskAssignmentMapper assignmentMapper;

    //    @Autowired
//    private V2UserApi userApi;
    @Autowired
    private UserApiV2Util userApiV2Util;


    @Resource
    private FtbPersonnelsStaffRosterService staffRosterService;

    @Resource
    private FtbCultivatePositionStatisticesMapper ftbCultivatePositionStatisticesMapper;

    @Autowired
    private FtbCultivateLearnCategoriesService cultivateLearnCategoriesService;

    @Autowired
    CultivateLearnUtils cultivateLearnUtils;

    @Autowired
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    @Autowired
    private FtbCultivateLearnTaskAssignmentService taskAssignmentService;

    @Autowired
    private FtbCultivateLearnTaskListService learnTaskListService;

    @Override
    public FtbCultivateLearnTaskInfoVO getLearnTaskInfo(String taskId) {
        FtbCultivateLearnTask learnTask = ftbCultivateLearnTaskMapper.selectById(taskId);
        if (learnTask == null) throw new RuntimeException("任务不存在!");
        FtbCultivateLearnTaskInfoVO convert = FtbCultivateLearnTaskInfoVO.convert(learnTask);
        //  添加分类名称
        FtbCultivateLearnCategories categories = cultivateLearnCategoriesService.getById(convert.getTaskClass());
        convert.setTaskClassName(categories.getName());
        //补充当前分类和父接分类
        convert.setAllCategoryList(cultivateLearnCategoriesService.queryCategoryAndParentCategory(convert.getTaskClass()));
        // 任务内容
        // 课程
        LambdaQueryWrapper<FtbCultivateLearnTaskCourse> learnTaskCourseLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskCourseLambdaQueryWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, taskId);
        List<FtbCultivateLearnTaskCourse> learnTaskCourses = cultivateLearnTaskCourseMapper.selectList(learnTaskCourseLambdaQueryWrapper);
        if (CollUtil.isEmpty(learnTaskCourses)) {
            throw new RuntimeException("该任务没有课程!");
        }
        List<String> courseIds = learnTaskCourses.stream().map(FtbCultivateLearnTaskCourse::getCourseId).collect(Collectors.toList());
        LambdaQueryWrapper<FtbCultivateCourse> courseLambdaQueryWrapper = Wrappers.lambdaQuery();
        courseLambdaQueryWrapper.in(SuperBaseEntity.SuperIBaseEntity::getId, courseIds);
        List<FtbCultivateCourse> ftbCultivateCourses = cultivateCourseMapper.selectList(courseLambdaQueryWrapper);
        // 获取课程信息
        Map<String, FtbCultivateCourse> courseNameMaps = ftbCultivateCourses.stream().collect(Collectors.toMap(SuperBaseEntity.SuperIBaseEntity::getId, vo -> vo));
        List<FtbCultivateCourseType> ftbCultivateCourseTypes = cultivateCourseTypeMapper.selectList(null);
        // 获取课程类型
        Map<String, String> courseTypeMaps = ftbCultivateCourseTypes.stream().collect(Collectors.toMap(SuperBaseEntity.SuperIBaseEntity::getId, FtbCultivateCourseType::getName));

        List<FtbCultivateLearnTaskCourseInfoVO> covertCourses = learnTaskCourses.stream().map(item -> {
            FtbCultivateLearnTaskCourseInfoVO convertInfo = FtbCultivateLearnTaskCourseInfoVO.convert(item);
            if (courseNameMaps.containsKey(convertInfo.getCourseId())) {
                FtbCultivateCourse ftbCultivateCourse = courseNameMaps.get(convertInfo.getCourseId());
                convertInfo.setCourseName(ftbCultivateCourse.getName());
                convertInfo.setCourseType(courseTypeMaps.get(ftbCultivateCourse.getTypeId()));
                Integer format = ftbCultivateCourse.getFormat();
                convertInfo.setFormat(format);
                convertInfo.setIsGroundIng(ftbCultivateCourse.getIsGroundIng());
            }
            return convertInfo;
        }).collect(Collectors.toList());
        // 添加课程内容
        convert.setCourseList(covertCourses);
        // 添加考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> examLambdaQueryWrapper = Wrappers.lambdaQuery();
        examLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getEnableMark, 0);
        examLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, taskId);

        FtbCultivateLearnTaskExam taskExam = cultivateLearnTaskExamMapper.selectOne(examLambdaQueryWrapper);
        if (taskExam != null) {
            FtbCultivateLearnTaskExamInfoVO examList = FtbCultivateLearnTaskExamInfoVO.convertExam(taskExam);
            FtbCultivateExam ftbCultivateExam = ftbCultivateExamMapper.selectById(examList.getExamId());
            examList.setExamName(ftbCultivateExam.getExamName());
            convert.setExamList(examList);
        }
        // 添加鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> identificationLambdaQueryWrapper = Wrappers.lambdaQuery();
        identificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, taskId);
        identificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getEnableMark, 0);
        FtbCultivateLearnTaskIdentification learnTaskIdentification = cultivateLearnTaskIdentificationMapper.selectOne(identificationLambdaQueryWrapper);
        if (learnTaskIdentification != null) {
            FtbCultivateLearnTaskIdentificationInfoVO identificationInfoVO = FtbCultivateLearnTaskIdentificationInfoVO.convert(learnTaskIdentification);
            CultivateIdentifyTable cultivateIdentifyTable = cultivateIdentifyTableMapper.selectById(identificationInfoVO.getIdentificationId());
            identificationInfoVO.setIdentificationName(cultivateIdentifyTable.getName());
            convert.setIdentificationList(identificationInfoVO);
        }
        // 添加证书
        LambdaQueryWrapper<FtbCultivateLearnTaskCertificate> learnTaskCertificateLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskCertificateLambdaQueryWrapper.eq(FtbCultivateLearnTaskCertificate::getTaskId, taskId);
        learnTaskCertificateLambdaQueryWrapper.eq(FtbCultivateLearnTaskCertificate::getEnableMark, 0);
        FtbCultivateLearnTaskCertificate learnTaskCertificate = cultivateLearnTaskCertificateMapper.selectOne(learnTaskCertificateLambdaQueryWrapper);
        if (learnTaskCertificate != null) {
            FtbCultivateLearnTaskCertificateInfoVO certificateList = FtbCultivateLearnTaskCertificateInfoVO.convert(learnTaskCertificate);
            certificateList.setCertificateName(certificateMapper.selectById(certificateList.getCertificateId()).getName());
            convert.setCertificateList(certificateList);
        }
        return convert;
    }

    @Override
    public PageListVO<FtbCultivateLearnTaskFinishInfoVO> getListOfCompletions(String taskId, CultivatePage oldPage, List<String> ids) {
        Page<FtbCultivateLearnTaskFinishInfoVO> page = oldPage.coverCultivatePage();
        List<FtbCultivateLearnTaskFinishInfoVO> records = ftbCultivateLearnTaskInfoMapper.getListOfCompletions(taskId, ids);
        List<String> userIds = records.stream().map(FtbCultivateLearnTaskFinishInfoVO::getUserId).collect(Collectors.toList());
        Map<String, UserBoundVO> finalInfosByUserIdMap = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        List<FtbCultivateLearnTaskFinishInfoVO> taskFinishInfoVOS = records.stream().filter(v -> finalInfosByUserIdMap.containsKey(v.getUserId())).map(item -> {
            if (finalInfosByUserIdMap.containsKey(item.getUserId())) {
                // 获取默认组织
                UserBoundVO userBoundMoreInfoVO = finalInfosByUserIdMap.get(item.getUserId());
                if (userBoundMoreInfoVO != null) {
                    item.setUserName(userBoundMoreInfoVO.getUserName());
                    item.setOrgName(userBoundMoreInfoVO.getOrganizeName());
                    String positionName = userBoundMoreInfoVO.getPositionName();
                    if (userBoundMoreInfoVO.getGradeName() != null) {
                        positionName = positionName + "/" + userBoundMoreInfoVO.getGradeName();
                    }
                    item.setPositionAndGradesName(positionName);
                    item.setEmployeeID(userBoundMoreInfoVO.getSystemWorkerId());
                }
            }
            if (item.getTaskStartTime() != null && item.getTaskEndTime() != null) {
                // 计算任务时长
                TimeDifference timeDifference = CultivateDateTimeUtils.calculateDifference(item.getTaskStartTime(), item.getTaskEndTime());
                item.setTaskDuration(timeDifference.toString());
            }
            return item;
        }).collect(Collectors.toList());
        return CultivatePage.paginate(taskFinishInfoVOS, page);
    }

    @Override
    public FtbCultivateLearnTaskFinishStatisticsVO getCompletionStatistics(String taskId) {
        // 根据任务统计该任务下人员完成情况
        FtbCultivateLearnTaskFinishStatisticsVO statisticsVO = new FtbCultivateLearnTaskFinishStatisticsVO();
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskAssignmentLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        List<FtbCultivateLearnTaskAssignment> taskAssignmentList = assignmentMapper.selectList(taskAssignmentLambdaQueryWrapper);
        Map<Integer, List<FtbCultivateLearnTaskAssignment>> listMap = taskAssignmentList.stream().collect(Collectors.groupingBy(FtbCultivateLearnTaskAssignment::getStudyStats, Collectors.toList()));
        // 应完成人数
        // 0未开始，1进行中，2已完成，3已逾期
        statisticsVO.setBeCompleted(taskAssignmentList.size());
        // 0未开始
        if (listMap.containsKey(0)) statisticsVO.setDidnTStart(listMap.get(0).size());
        // 1进行中
        if (listMap.containsKey(1)) statisticsVO.setOngoing(listMap.get(1).size());
        // 2已完成
        if (listMap.containsKey(2)) statisticsVO.setDone(listMap.get(2).size());
        // 3已逾期
        if (listMap.containsKey(3)) statisticsVO.setOverdue(listMap.get(3).size());
        return statisticsVO;
    }

    @Override
    public FtbCultivateLearnTaskUserFinishInfoVO viewTaskCompletion(String taskId, String userId) {
        // 构建返回对象
        FtbCultivateLearnTaskUserFinishInfoVO infoVO = new FtbCultivateLearnTaskUserFinishInfoVO();
        // 查询当前人任务完成情况
        List<FtbCultivateLearnTaskCourseUserInfoVO> learnings = ftbCultivateLearnTaskInfoMapper.queryCourseUserInfo(taskId, userId);
        learnings.forEach(item -> {
            // 课程学习进度（%）
            Integer a = ftbCultivatePositionStatisticesMapper.courseLearningProgress(item.getCourseId(), userId, null);
            Integer b = ftbCultivatePositionStatisticesMapper.courseLearningProgress(item.getCourseId(), userId, 1);
            item.setLearningProgress(FtbCultivatePositionStatisticesServiceImpl.computeDivision(b, a));
        });
        infoVO.setCourseInfoVOS(learnings);
        // 添加考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> examLambdaQueryWrapper = Wrappers.lambdaQuery();
        examLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, taskId);
        FtbCultivateLearnTaskExam taskExam = cultivateLearnTaskExamMapper.selectOne(examLambdaQueryWrapper);
        if (taskExam != null) {
            FtbCultivateLearnTaskExamUserInfoVO examUserInfoVO = new FtbCultivateLearnTaskExamUserInfoVO();
            FtbCultivateExam ftbCultivateExam = ftbCultivateExamMapper.selectById(taskExam.getExamId());
            examUserInfoVO.setExamName(ftbCultivateExam.getExamName());
            // 考试信息
//            FtbCultivateLearnTaskExamUserInfoVO examUserInfoVO1 = ftbCultivateLearnTaskInfoMapper.queryExamInfo(taskId, userId);
            LambdaQueryWrapper<FtbCultivateExamUser> userExamWraper = Wrappers.lambdaQuery();
            userExamWraper.eq(FtbCultivateExamUser::getExamSource, 4);
            userExamWraper.eq(FtbCultivateExamUser::getRelationTaskId, taskId);
            userExamWraper.eq(FtbCultivateExamUser::getUserId, userId);
            userExamWraper.eq(FtbCultivateExamUser::getEnabledMark, 1);
            userExamWraper.orderByDesc(FtbCultivateExamUser::getCreatorTime);
            List<FtbCultivateExamUser> examUserList = ftbCultivateExamUserMapper.selectList(userExamWraper);

            /** 考试状态 是否完成 (0否 1 是)*/
            Integer isFinish = 0;
            /** 用时 (单位秒)*/
            Long unavailable = 0L;
            if (CollUtil.isNotEmpty(examUserList)) {
                FtbCultivateExamUser examUser = examUserList.get(0);
                if (examUser.getStatus() == 0 || examUser.getStatus() == 2) {
                    isFinish = 0;
                } else {
                    isFinish = 1;
                    unavailable = examUser.getDuration();
                }
                examUserInfoVO.setUserExamId(examUser.getId());
                examUserInfoVO.setExamStatus(examUser.getStatus());
            }
            examUserInfoVO.setIsFinish(isFinish);
            examUserInfoVO.setUnavailable(unavailable);
            examUserInfoVO.setExamId(taskExam.getExamId());
            infoVO.setExamInfoVOS(examUserInfoVO);
        }
        // 添加鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> identificationLambdaQueryWrapper = Wrappers.lambdaQuery();
        identificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, taskId);
        FtbCultivateLearnTaskIdentification learnTaskIdentification = cultivateLearnTaskIdentificationMapper.selectOne(identificationLambdaQueryWrapper);
        if (learnTaskIdentification != null) {
            FtbCultivateLearnTaskIdentificationUserInfoVO identificationUserInfoVO = new FtbCultivateLearnTaskIdentificationUserInfoVO();
            CultivateIdentifyTable cultivateIdentifyTable = cultivateIdentifyTableMapper.selectById(learnTaskIdentification.getIdentificationId());
            identificationUserInfoVO.setIdentificationName(cultivateIdentifyTable.getName());
            // 鉴定
            FtbCultivateLearnTaskIdentificationUserInfoVO identificationInfoVOS = ftbCultivateLearnTaskInfoMapper.queryIdentificationInfo(taskId, userId);
            identificationUserInfoVO.setIsFinish(identificationInfoVOS == null ? 0 : identificationInfoVOS.getIsFinish());
            if (identificationInfoVOS != null) {
                identificationUserInfoVO.setIdentifyResult(identificationInfoVOS.getIdentifyResult());
                identificationUserInfoVO.setIdentifyStatus(identificationInfoVOS.getIdentifyStatus());
            }
            infoVO.setIdentificationInfoVOS(identificationUserInfoVO);
        }
        // 添加证书
        LambdaQueryWrapper<FtbCultivateLearnTaskCertificate> learnTaskCertificateLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskCertificateLambdaQueryWrapper.eq(FtbCultivateLearnTaskCertificate::getTaskId, taskId);
        FtbCultivateLearnTaskCertificate learnTaskCertificate = cultivateLearnTaskCertificateMapper.selectOne(learnTaskCertificateLambdaQueryWrapper);
        if (learnTaskCertificate != null) {
            FtbCultivateLearnTaskCertificateUserInfoVO ftbCultivateLearnTaskCertificateUserInfoVO = new FtbCultivateLearnTaskCertificateUserInfoVO();
            ftbCultivateLearnTaskCertificateUserInfoVO.setCertificateName(certificateMapper.selectById(learnTaskCertificate.getCertificateId()).getName());
            // 证书
            FtbCultivateLearnTaskCertificateUserInfoVO certificateInfoVOS = ftbCultivateLearnTaskInfoMapper.queryCertificateInfo(taskId, userId);
            ftbCultivateLearnTaskCertificateUserInfoVO.setIsFinish(certificateInfoVOS == null ? 0 : certificateInfoVOS.getIsFinish());
            infoVO.setCertificateInfoVOS(ftbCultivateLearnTaskCertificateUserInfoVO);
        }
        return infoVO;
    }

    @Override
    @Transactional
    public PageListVO<FtbCultivateLearnTaskListVO> getTaskList(FtbCultivateLearnTaskListDto taskListDto) {
        Page<FtbCultivateLearnTaskListVO> page = taskListDto.coverCultivatePage();
//        updateUserFinishTime(null);//
//        cultivateLearnUtils.updateUserTaskStatus(UserProvider.getUser().getTenantId());
//        learnTaskListService.preUpdateTaskStatus(cultivateLearnUtils.getTenantId());
        page = ftbCultivateLearnTaskInfoMapper.getTaskList(page, taskListDto);
        return CultivatePage.coverPageList(page);
    }

    /**
     * 培训任务列表列表小气泡计数
     *
     * @param keyWords 任务名称
     * @return
     */
    @Override
    public Map<String, Integer> getTaskCount(String keyWords) {
        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = Wrappers.lambdaQuery();
        wrapper.ne(FtbCultivateLearnTask::getStatus, LearnTaskStatusEnum.UNPUBLISHED.getCode());
        wrapper.like(StringUtils.isNotEmpty(keyWords), FtbCultivateLearnTask::getTaskName, keyWords);
        List<FtbCultivateLearnTask> learnTasks = ftbCultivateLearnTaskMapper.selectList(wrapper);
        if (learnTasks == null) return null;
        Map<String, Integer> hashMap = new HashMap<>();
        // 1 未开始 ,2 进行中，3 已结束
        hashMap.put("total", learnTasks.size());
        hashMap.put("didnTStart", countStatus(learnTasks, LearnTaskStatusEnum.NOT_STARTED.getCode()));
        hashMap.put("ongoing", countStatus(learnTasks, LearnTaskStatusEnum.IN_PROGRESS.getCode()));
        hashMap.put("ended", countStatus(learnTasks, LearnTaskStatusEnum.FINISHED.getCode()));

        return hashMap;
    }

    private Integer countStatus(List<FtbCultivateLearnTask> learnTasks, Integer status) {
        Predicate<FtbCultivateLearnTask> predicate = item -> Objects.equals(item.getStatus(), status);
        return Math.toIntExact(learnTasks.stream().filter(predicate).count());
    }

    @Override
    @Transactional
    public void updateUserFinishTime(String userId) {
        /**
         * 获取学习任务详情进行实时更新
         */
        List<String> taskIds = new ArrayList<>();

        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        lambdaQuery.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        lambdaQuery.notIn(FtbCultivateLearnTaskAssignment::getStudyStats, 2, 3);
        List<FtbCultivateLearnTaskAssignment> taskAssignments = assignmentMapper.selectList(lambdaQuery);
        if (CollUtil.isEmpty(taskAssignments)) return;
        taskIds = taskAssignments.stream()
                .map(FtbCultivateLearnTaskAssignment::getTaskId)
                .collect(Collectors.toList());

        // 进入状态更新
        // 1.更新任务状态
        LambdaQueryWrapper<FtbCultivateLearnTask> taskLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskLambdaQueryWrapper.in(FtbCultivateLearnTask::getStatus,
                LearnTaskStatusEnum.NOT_STARTED.getCode(),
                LearnTaskStatusEnum.IN_PROGRESS.getCode(),
                LearnTaskStatusEnum.FINISHED.getCode());
        taskLambdaQueryWrapper.eq(FtbCultivateLearnTask::getTaskType, 1);
        if (CollUtil.isNotEmpty(taskIds)) taskLambdaQueryWrapper.in(SuperBaseEntity.SuperIBaseEntity::getId, taskIds);
        List<FtbCultivateLearnTask> learnTasks = ftbCultivateLearnTaskMapper.selectList(taskLambdaQueryWrapper);
        if (CollUtil.isEmpty(learnTasks)) return;

        //转换成map
        Map<String, FtbCultivateLearnTask> taskMap = learnTasks.stream().collect(Collectors.toMap(SuperBaseEntity.SuperIBaseEntity::getId, Function.identity()));
        Date nowDate = new Date();
        List<FtbCultivateLearnTaskAssignment> needUpdate = new ArrayList<>();
        for (FtbCultivateLearnTaskAssignment taskAssignment : taskAssignments) {
            FtbCultivateLearnTask task = taskMap.get(taskAssignment.getTaskId());
            if (task == null) {
                continue;
            }
            // 任务结束时间
            Date timeLimitEndTime = task.getTimeLimitEndTime();
            /** 学习状态 0未开始，1进行中，2已完成，3已逾期*/
            if (nowDate.after(timeLimitEndTime)) {
                taskAssignment.setStudyStats(3);
                needUpdate.add(taskAssignment);
            }
            if (taskAssignment.getStudyStats() == 1 && task.getStudentTimeCompletion() == 0) {
                //进行中判断是否限时
                Date endCompleteTime = taskAssignment.getLearningStartTime();
                //学员限时完成单位(0,天,1,小时)
                if (task.getTimeCompletionUnit() == 0) {
                    endCompleteTime = DateUtil.offsetDay(endCompleteTime, task.getTimeCompletionDays());
                } else {
                    endCompleteTime = DateUtil.offsetHour(endCompleteTime, task.getTimeCompletionDays());
                }
                if (nowDate.after(endCompleteTime)) {
                    taskAssignment.setStudyStats(3);
                }
                needUpdate.add(taskAssignment);
            }
        }
        if (CollUtil.isNotEmpty(needUpdate)) {
            taskAssignmentService.updateBatchById(needUpdate, needUpdate.size());
        }
    }
}
