package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.CultivateImUtil;
import jnpf.cultivate.utils.CultivateLearnTaskIMUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.dto.learn.*;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.course.PositionCourseEventDTO;
import jnpf.model.cultivate.po.learn.*;
import jnpf.model.cultivate.vo.learn.FtbLearnQueryTaskDetailsEditingVO;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.personnels.service.FtbPersonnelsMetaDataService;
import jnpf.util.SelfGrowthUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.context.SpringContext;
import jnpf.util.context.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class FtbCultivateLearnTaskInfoContentServiceImpl implements FtbCultivateLearnTaskInfoContentService {


    @Autowired
    private UserApiV2Util userApiV2Util;

    @Resource
    private CultivateImUtil cultivateImUtil;

    @Resource
    private CultivateLearnTaskIMUtils captchaImUtil;

    @Resource
    private FtbCultivateExamUserService ftbCultivateExamUserService;

    @Resource
    private FtbCultivateLearnTaskMapper ftbCultivateLearnTaskMapper;

    @Resource
    private FtbCultivateLearnTaskAssignmentService ftbCultivateLearnTaskAssignmentService;

    @Resource
    private FtbCultivateLearnTaskCertificateMapper ftbCultivateLearnTaskCertificateMapper;

    @Resource
    private FtbCultivateLearnTaskCourseService ftbCultivateLearnTaskCourseService;

    @Resource
    private FtbCultivateLearnTaskExamMapper ftbCultivateLearnTaskExamMapper;

    @Resource
    private FtbCultivateLearnTaskIdentificationMapper ftbCultivateLearnTaskIdentificationMapper;

    @Resource
    private FtbPersonnelsMetaDataService ftbPersonnelsMetaDataService;

    @Resource
    private FtbCultivateLearnTaskReminderRuleMapper ftbCultivateLearnTaskReminderRuleMapper;

    @Resource
    private CultivateIdentifyApplyService cultivateIdentifyApplyService;

    @Resource
    private FtbCultivateLearnTaskInfoContentMapper ftbCultivateLearnTaskInfoContentMapper;

    @Resource
    private ThreadPoolExecutor cultivateThreadPool;

    @Override
    @Transactional
    public void saveLearnTaskList(FtbCultivateLearnTaskInfoDto taskInfoDto) {
        taskInfoDto.beforeCheck();
        // 任务名称不能重复
        LambdaQueryWrapper<FtbCultivateLearnTask> taskQueryWrapper = Wrappers.lambdaQuery();
        taskQueryWrapper.eq(FtbCultivateLearnTask::getTaskName, taskInfoDto.getTaskName());
        taskQueryWrapper.eq(FtbCultivateLearnTask::getEnableMark, 0);
        if (ftbCultivateLearnTaskMapper.selectCount(taskQueryWrapper) > 0) {
            throw new RuntimeException("任务名称不能重复");
        }
        initLearnTaskData(taskInfoDto, null, null);
    }

    @Override
    @Transactional
    public void updateLearnTaskList(FtbCultivateLearnTaskInfoDto taskInfoDto) {

        taskInfoDto.beforeCheck();
        LambdaQueryWrapper<FtbCultivateLearnTask> taskNameQueryWrapper = Wrappers.lambdaQuery();
        taskNameQueryWrapper.eq(FtbCultivateLearnTask::getTaskName, taskInfoDto.getTaskName());
        taskNameQueryWrapper.eq(FtbCultivateLearnTask::getEnableMark, 0);
        FtbCultivateLearnTask findByName = ftbCultivateLearnTaskMapper.selectOne(taskNameQueryWrapper);
        if (findByName != null && !findByName.getId().equals(taskInfoDto.getId())) {
            throw new RuntimeException("任务名称不能重复");
        }

        // 上次任务展示ID
        LambdaQueryWrapper<FtbCultivateLearnTask> taskQueryWrapper = Wrappers.lambdaQuery();
        taskQueryWrapper.eq(FtbCultivateLearnTask::getId, taskInfoDto.getId());
        FtbCultivateLearnTask ftbCultivateLearnTask = ftbCultivateLearnTaskMapper.selectOne(taskQueryWrapper);
        // 任务进行中时，编辑任务后将重置任务，已完成的部分清空。已有统计数据一并清除
        deleteTask(taskInfoDto.getId());
        initLearnTaskData(taskInfoDto, ftbCultivateLearnTask.getLearnTaskShowId(), ftbCultivateLearnTask);
    }
    /**
     * 获取学习任务分配列表
     *
     * @param taskId 任务ID，用于标识特定的学习任务
     * @return 返回一个字符串列表，包含任务的分配详情
     */
    @Override
    public List<String> getLearnTaskAllocationList(String taskId) {
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignmentQueryWrapper = Wrappers.lambdaQuery();
        assignmentQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        assignmentQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        return ftbCultivateLearnTaskAssignmentService.list(assignmentQueryWrapper)
                .stream()
                .map(FtbCultivateLearnTaskAssignment::getUserId)
                .collect(Collectors.toList());
    }

    /**
     * 查询未完成的学院
     * @param taskId 任务id
     * @return
     */
    @Override
    public List<String> queryUserListForTaskNoComplete(String taskId) {
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignmentQueryWrapper = Wrappers.lambdaQuery();
        assignmentQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        assignmentQueryWrapper.ne(FtbCultivateLearnTaskAssignment::getStudyStats, 2);
        assignmentQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        return ftbCultivateLearnTaskAssignmentService.list(assignmentQueryWrapper)
                .stream()
                .map(FtbCultivateLearnTaskAssignment::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void allocation(FtbCultivateLearnAllocationDTO allocationDTO) {
        // 人员清洗，补充分配（回显张三，并添加李四、王五）覆盖分配（回显张三，移除张三；再添加李四、王五）
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskAssignmentLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskAssignmentLambdaQueryWrapper.select(FtbCultivateLearnTaskAssignment::getUserId);
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, allocationDTO.getTaskId());
        taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
        List<FtbCultivateLearnTaskAssignment> oldLearnTaskAssignments = ftbCultivateLearnTaskAssignmentService.list(taskAssignmentLambdaQueryWrapper);
        List<String> oldUserIds = oldLearnTaskAssignments.stream()
                .map(FtbCultivateLearnTaskAssignment::getUserId)
                .collect(Collectors.toList());
        // 覆盖分配
        List<String> overwritePersonnelIds = oldUserIds.stream()
                .filter(a -> !allocationDTO.getUserIds().contains(a))
                .collect(Collectors.toList());
        if (!overwritePersonnelIds.isEmpty()) {
            // 移除覆盖分配人员
            taskAssignmentLambdaQueryWrapper.clear();
            taskAssignmentLambdaQueryWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, allocationDTO.getTaskId());
            taskAssignmentLambdaQueryWrapper.in(FtbCultivateLearnTaskAssignment::getUserId, overwritePersonnelIds);
            ftbCultivateLearnTaskAssignmentService.remove(taskAssignmentLambdaQueryWrapper);
        }
        List<String> processingUserIds = allocationDTO.getUserIds()
                .stream()
                .filter(a -> !oldUserIds.contains(a))
                .collect(Collectors.toList());
        // 任务课程
        LambdaQueryWrapper<FtbCultivateLearnTaskCourse> courseQueryWrapper = Wrappers.lambdaQuery();
        courseQueryWrapper.select(FtbCultivateLearnTaskCourse::getCourseId);
        courseQueryWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, allocationDTO.getTaskId());
        courseQueryWrapper.eq(FtbCultivateLearnTaskCourse::getEnableMark, 0);
        List<FtbCultivateLearnTaskCourse> courseList = ftbCultivateLearnTaskCourseService.list(courseQueryWrapper);
        // 新人员绑定
        List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments = processingUserIds.stream().map(a -> {
            FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment = new FtbCultivateLearnTaskAssignment();
            ftbCultivateLearnTaskAssignment.setTaskId(allocationDTO.getTaskId());
            ftbCultivateLearnTaskAssignment.setUserId(a);
            ftbCultivateLearnTaskAssignment.setStudyStats(0);
            return ftbCultivateLearnTaskAssignment;
        }).collect(Collectors.toList());
        ftbCultivateLearnTaskAssignmentService.saveBatch(ftbCultivateLearnTaskAssignments);
        // 人员课程绑定
        List<String> courseIds = courseList.stream()
                .map(FtbCultivateLearnTaskCourse::getCourseId)
                .collect(Collectors.toList());
        SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(
                PositionCourseEventDTO.builder()
                        .courseIds(courseIds)
                        .userIds(processingUserIds)
                        .eventType(PositionCourseEventDTO.EventType.USER)
                        .whetherToChange(false)
                        .build()));
    }

    @Override
    @Transactional
    public void deleteTask(String id) {
        // 任务删除
        LambdaQueryWrapper<FtbCultivateLearnTask> deleteLearnTaskWrapper = Wrappers.lambdaQuery();
        deleteLearnTaskWrapper.eq(SuperBaseEntity.SuperIBaseEntity::getId, id);
        ftbCultivateLearnTaskMapper.delete(deleteLearnTaskWrapper);
        // 任务人员
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> deleteLearnTaskAssignmentWrapper = Wrappers.lambdaQuery();
        deleteLearnTaskAssignmentWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, id);
        ftbCultivateLearnTaskAssignmentService.remove(deleteLearnTaskAssignmentWrapper);
        // 任务课程
        LambdaQueryWrapper<FtbCultivateLearnTaskCourse> deleteCourseWrapper = Wrappers.lambdaQuery();
        deleteCourseWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, id);
        ftbCultivateLearnTaskCourseService.remove(deleteCourseWrapper);
        // 任务证书
        LambdaQueryWrapper<FtbCultivateLearnTaskCertificate> deleteCertificateWrapper = Wrappers.lambdaQuery();
        deleteCertificateWrapper.eq(FtbCultivateLearnTaskCertificate::getTaskId, id);
        ftbCultivateLearnTaskCertificateMapper.delete(deleteCertificateWrapper);
        // 任务考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> deleteExamWrapper = Wrappers.lambdaQuery();
        deleteExamWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, id);
        ftbCultivateLearnTaskExamMapper.delete(deleteExamWrapper);
        // 任务鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> deleteIdentificationWrapper = Wrappers.lambdaQuery();
        deleteIdentificationWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, id);
        ftbCultivateLearnTaskIdentificationMapper.delete(deleteIdentificationWrapper);
        // 任务提醒鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskReminderRule> deleteReminderWrapper = Wrappers.lambdaQuery();
        deleteReminderWrapper.eq(FtbCultivateLearnTaskReminderRule::getTaskId, id);
        ftbCultivateLearnTaskReminderRuleMapper.delete(deleteReminderWrapper);
        // 删除任务关联考试
        ftbCultivateExamUserService.deleteTaskExamUserRecord(id);
        // 删除任务鉴定
        cultivateIdentifyApplyService.deleteLearnTaskApplyIdentified(id);
    }

    @Override
    public FtbLearnQueryTaskDetailsEditingVO queryTaskDetailsWhileEditing(String id) {
        FtbCultivateLearnTask ftbCultivateLearnTask = ftbCultivateLearnTaskMapper.selectById(id);
        FtbLearnQueryTaskDetailsEditingVO ftbLearnQueryTaskDetailsEditingVO = FtbLearnQueryTaskDetailsEditingVO.convert(ftbCultivateLearnTask);
        if (null == ftbLearnQueryTaskDetailsEditingVO) {
            return ftbLearnQueryTaskDetailsEditingVO;
        }
        if (ftbCultivateLearnTask != null && ftbCultivateLearnTask.getAssignmentRule() == 1) {
            List<String> userIds = new ArrayList<>();
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskAssignmentWraper = Wrappers.lambdaQuery();
            taskAssignmentWraper.eq(FtbCultivateLearnTaskAssignment::getTaskId, id);
            taskAssignmentWraper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
            List<FtbCultivateLearnTaskAssignment> taskAssignmentList = ftbCultivateLearnTaskAssignmentService.list(taskAssignmentWraper);
            if (CollUtil.isNotEmpty(taskAssignmentList)) {
                //获取用户id列表
                for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : taskAssignmentList) {
                    userIds.add(ftbCultivateLearnTaskAssignment.getUserId());
                }
            }
            ftbLearnQueryTaskDetailsEditingVO.setUserIds(userIds);
        }
        // 任务提醒规则
        LambdaQueryWrapper<FtbCultivateLearnTaskReminderRule> reminderRuleLambdaQueryWrapper = Wrappers.lambdaQuery();
        reminderRuleLambdaQueryWrapper.eq(FtbCultivateLearnTaskReminderRule::getTaskId, id);
        FtbCultivateLearnTaskReminderRule ftbCultivateLearnTaskReminderRule = ftbCultivateLearnTaskReminderRuleMapper.selectOne(reminderRuleLambdaQueryWrapper);
        ftbLearnQueryTaskDetailsEditingVO.setTaskStartReminder(ftbCultivateLearnTaskReminderRule.getTaskStartReminder());
        ftbLearnQueryTaskDetailsEditingVO.setTaskEndReminder(ftbCultivateLearnTaskReminderRule.getTaskEndReminder());
        ftbLearnQueryTaskDetailsEditingVO.setPerInterval(ftbCultivateLearnTaskReminderRule.getPerInterval());
        // 任务课程
        List<FtbCultivateLearnTaskCourseInfoDto> learnTaskCourseList = ftbCultivateLearnTaskReminderRuleMapper.getLearnTaskCourseList(id);

        ftbLearnQueryTaskDetailsEditingVO.setCourseList(learnTaskCourseList);
        // 任务考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> examQueryWrapper = Wrappers.lambdaQuery();
        examQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, id);
        FtbCultivateLearnTaskExam ftbCultivateLearnTaskExam = ftbCultivateLearnTaskExamMapper.selectOne(examQueryWrapper);
        ftbLearnQueryTaskDetailsEditingVO.setExamList(FtbCultivateLearnTaskExamInfoDto.convert(ftbCultivateLearnTaskExam));
        // 任务鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> identificationQueryWrapper = Wrappers.lambdaQuery();
        identificationQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, id);
        FtbCultivateLearnTaskIdentification ftbCultivateLearnTaskIdentification = ftbCultivateLearnTaskIdentificationMapper.selectOne(identificationQueryWrapper);
        ftbLearnQueryTaskDetailsEditingVO.setIdentificationList(FtbCultivateLearnTaskIdentificationInfoDto.convert(ftbCultivateLearnTaskIdentification));
        // 任务证书
        LambdaQueryWrapper<FtbCultivateLearnTaskCertificate> certificateQueryWrapper = Wrappers.lambdaQuery();
        certificateQueryWrapper.eq(FtbCultivateLearnTaskCertificate::getTaskId, id);
        FtbCultivateLearnTaskCertificate ftbCultivateLearnTaskCertificate = ftbCultivateLearnTaskCertificateMapper.selectOne(certificateQueryWrapper);
        ftbLearnQueryTaskDetailsEditingVO.setCertificateList(FtbCultivateLearnTaskCertificateInfoDto.convert(ftbCultivateLearnTaskCertificate));
        // 考试名称
        if (Objects.nonNull(ftbCultivateLearnTaskExam)) {
            String examName = ftbCultivateLearnTaskInfoContentMapper.queryNameBasedOnExamId(ftbCultivateLearnTaskExam.getExamId());
            ftbLearnQueryTaskDetailsEditingVO.getExamList().setExamName(examName);
        }
        // 鉴定名称
        if (Objects.nonNull(ftbCultivateLearnTaskIdentification)) {
            String identificationName = ftbCultivateLearnTaskInfoContentMapper.queryNameBasedOnIdentificaId(ftbCultivateLearnTaskIdentification.getIdentificationId());
            ftbLearnQueryTaskDetailsEditingVO.getIdentificationList().setIdentificationName(identificationName);
        }
        // 证书名称
        if (Objects.nonNull(ftbCultivateLearnTaskCertificate)) {
            String certificateName = ftbCultivateLearnTaskInfoContentMapper.queryNameBasedOnCertificateId(ftbCultivateLearnTaskCertificate.getCertificateId());
            ftbLearnQueryTaskDetailsEditingVO.getCertificateList().setCertificateName(certificateName);
        }
        return ftbLearnQueryTaskDetailsEditingVO;
    }

    @Override
    @Transactional
    public void abort(String taskId) {
        // 任务中止
        LambdaUpdateWrapper<FtbCultivateLearnTask> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SuperBaseEntity.SuperIBaseEntity::getId, taskId);
        updateWrapper.set(FtbCultivateLearnTask::getStatus, 3);
        ftbCultivateLearnTaskMapper.update(new FtbCultivateLearnTask(), updateWrapper);
        String tenantId = UserProvider.getUser().getTenantId();
        // im消息通知
        LambdaQueryWrapper<FtbCultivateLearnTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(FtbCultivateLearnTask::getTaskName);
        queryWrapper.eq(FtbCultivateLearnTask::getId, taskId);
        FtbCultivateLearnTask ftbCultivateLearnTask = ftbCultivateLearnTaskMapper.selectOne(queryWrapper);
        String pushMessageContent = "您的任务【" + ftbCultivateLearnTask.getTaskName() + "】已终止，无法继续进行任务！";
        cultivateImUtil.sendTaskAbortMessage(queryUserListForTaskNoComplete(taskId), tenantId, pushMessageContent);
    }


    /**
     * 学习任务数据
     *
     * @param taskInfoDto     任务信息
     * @param learnTaskShowId 学习任务展示id
     */
    private void initLearnTaskData(FtbCultivateLearnTaskInfoDto taskInfoDto, String learnTaskShowId, FtbCultivateLearnTask oldTaskInfo) {
        // 任务分配规则(1,指定成员,2指定组织,3指定岗位,4自定义)
        List<String> userIds = new ArrayList<>();
        if (taskInfoDto.getAssignmentRule() == 1) {
            userIds = taskInfoDto.getUserIds();
        } else if (taskInfoDto.getAssignmentRule() == 2) {
            // 指定组织下所有用户
            if(StringUtil.isNotEmpty(taskInfoDto.getAssociationIds())) {
                List<String> split = List.of(taskInfoDto.getAssociationIds().split(StringPool.COMMA));
                List<UserPageListVO> userBaseInfoByOrganizes = userApiV2Util.getUserListForOrgIds(split,null);
                if(CollUtil.isNotEmpty(userBaseInfoByOrganizes)){
                    userIds = userBaseInfoByOrganizes.stream().map(UserPageListVO::getId).distinct().collect(Collectors.toList());
                }
            }
        } else if (taskInfoDto.getAssignmentRule() == 3) {
            // 指定岗位下所有用户
            List<UserBoundVO> userBaseInfoByPositions = userApiV2Util.getUserListForPositions(List.of(taskInfoDto.getAssociationIds().split(StringPool.COMMA)),null);
            if(CollUtil.isNotEmpty(userBaseInfoByPositions)){
                userIds = userBaseInfoByPositions.stream().map(UserBoundVO::getId).distinct().collect(Collectors.toList());
            }

        } else if (taskInfoDto.getAssignmentRule() == 4) {
            // 自定义
            userIds = ftbPersonnelsMetaDataService.queryUserIdsForCompanyAge(taskInfoDto.getStartEntryPeriod(), taskInfoDto.getEndEntryPeriod());
        }
        // 任务主表
        FtbCultivateLearnTask ftbCultivateLearnTask = taskInfoDto.convertFtbCultivateLearnTask(taskInfoDto);
        // 任务展示Id，更新是之前的，新增则为新的
        ftbCultivateLearnTask.setLearnTaskShowId(learnTaskShowId);
        if (learnTaskShowId == null) {
            ftbCultivateLearnTask.setLearnTaskShowId(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.LEARN_TASK));
        }
        if (oldTaskInfo != null) {
            ftbCultivateLearnTask.setCreatorTime(oldTaskInfo.getCreatorTime());
            ftbCultivateLearnTask.setCreatorUserId(oldTaskInfo.getCreatorUserId());
        }
        ftbCultivateLearnTaskMapper.insert(ftbCultivateLearnTask);
        // 学习任务关联人
        List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments = userIds.stream().map(a -> {
            FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment = new FtbCultivateLearnTaskAssignment();
            ftbCultivateLearnTaskAssignment.setTaskId(ftbCultivateLearnTask.getId());
            ftbCultivateLearnTaskAssignment.setStudyStats(0);
            ftbCultivateLearnTaskAssignment.setUserId(a);
            return ftbCultivateLearnTaskAssignment;
        }).collect(Collectors.toList());
        // 任务课程
        List<FtbCultivateLearnTaskCourse> ftbCultivateLearnTaskCourses = taskInfoDto.getCourseList().stream().map(a -> {
            FtbCultivateLearnTaskCourse ftbCultivateLearnTaskCourse = new FtbCultivateLearnTaskCourse();
            ftbCultivateLearnTaskCourse.setTaskId(ftbCultivateLearnTask.getId());
            ftbCultivateLearnTaskCourse.setCourseId(a.getCourseId());
            ftbCultivateLearnTaskCourse.setIsRequired(a.getIsRequired());
            return ftbCultivateLearnTaskCourse;
        }).collect(Collectors.toList());
        // 任务学习关联规则提醒
        FtbCultivateLearnTaskReminderRule ftbCultivateLearnTaskReminderRule = taskInfoDto.convertTaskReminderRule(taskInfoDto);
        ftbCultivateLearnTaskReminderRule.setTaskId(ftbCultivateLearnTask.getId());
        ftbCultivateLearnTaskReminderRuleMapper.insert(ftbCultivateLearnTaskReminderRule);
        // 任务考试
        if (Objects.nonNull(taskInfoDto.getExamList())) {
            FtbCultivateLearnTaskExam ftbCultivateLearnTaskExam = taskInfoDto.convertFtbCultivateLearnTaskExam(taskInfoDto);
            ftbCultivateLearnTaskExam.setTaskId(ftbCultivateLearnTask.getId());
            ftbCultivateLearnTaskExamMapper.insert(ftbCultivateLearnTaskExam);
        }
        // 任务鉴定
        if (Objects.nonNull(taskInfoDto.getIdentificationList())) {
            FtbCultivateLearnTaskIdentification ftbCultivateLearnTaskIdentification = taskInfoDto.convertFtbCultivateLearnTaskIdentification(taskInfoDto);
            ftbCultivateLearnTaskIdentification.setTaskId(ftbCultivateLearnTask.getId());
            ftbCultivateLearnTaskIdentificationMapper.insert(ftbCultivateLearnTaskIdentification);
        }
        // 任务证书
        if (Objects.nonNull(taskInfoDto.getCertificateList())) {
            FtbCultivateLearnTaskCertificate ftbCultivateLearnTaskCertificate = taskInfoDto.convertFtbCultivateLearnTaskCertificate(taskInfoDto);
            ftbCultivateLearnTaskCertificate.setTaskId(ftbCultivateLearnTask.getId());
            ftbCultivateLearnTaskCertificateMapper.insert(ftbCultivateLearnTaskCertificate);
        }
        ftbCultivateLearnTaskAssignmentService.saveBatch(ftbCultivateLearnTaskAssignments);
        ftbCultivateLearnTaskCourseService.saveBatch(ftbCultivateLearnTaskCourses);
        // 任务课程事件
        List<String> courseIds = taskInfoDto.getCourseList().stream()
                .map(FtbCultivateLearnTaskCourseInfoDto::getCourseId)
                .collect(Collectors.toList());
        SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(
                PositionCourseEventDTO.builder()
                        .courseIds(courseIds)
                        .userIds(userIds)
                        .eventType(PositionCourseEventDTO.EventType.USER)
                        .whetherToChange(false)
                        .build()));
        // 任务进行中，启用提醒后，任务开始时将提醒员工
        if (ftbCultivateLearnTask.getStatus() == 2
                && ftbCultivateLearnTaskReminderRule.getTaskStartReminder() == 1
                && CollUtil.isNotEmpty(userIds)) {
            List<NeedAlertUserDto> alertUserList = userIds.stream().map(a -> {
                NeedAlertUserDto needAlertUserDto = new NeedAlertUserDto();
                needAlertUserDto.setUserId(a);
                needAlertUserDto.setTaskId(ftbCultivateLearnTask.getId());
                needAlertUserDto.setTaskName(ftbCultivateLearnTask.getTaskName());
                return needAlertUserDto;
            }).collect(Collectors.toList());
            String tenantId = UserProvider.getUser().getTenantId();

            CompletableFuture.runAsync(ThreadContext.wrap(() -> {
                captchaImUtil.sendMsg(alertUserList, tenantId);
            }), cultivateThreadPool);
        }
    }


}
