package jnpf.cultivate.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.UserInfo;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskAssignmentMapper;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceLearningMapper;
import jnpf.cultivate.service.*;
import jnpf.cultivate.v2.service.FtbCultivatePromotionSettingService;
import jnpf.cultivate.v2.service.FtbCultivatePromotionUserService;
import jnpf.model.cultivate.dto.learn.NeedAlertUserDto;
import jnpf.model.cultivate.dto.learn.NeedPerDayAlertDto;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnCategories;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTask;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskCourse;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionSetting;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionUser;
import jnpf.model.cultivate.resp.TaskRelationCertificateVo;
import jnpf.model.cultivate.resp.TaskRelationExamVo;
import jnpf.model.cultivate.resp.TaskRelationIdentificationVo;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskInfoCountListVO;
import jnpf.model.cultivate.vo.learn.FtbCultivateLearnTaskInfoListVO;
import jnpf.model.cultivate.vo.learn.FtbExportCultivateLearnTaskInfoCountListVO;
import jnpf.model.cultivate.vo.learn.FtbExportCultivateLearnTaskInfoListVO;
import jnpf.model.personnels.dto.roster.meta.FtbPersonnlesJobTenureDTO;
import jnpf.model.personnels.dto.roster.meta.FtbPersonnlesJoeInfo;
import jnpf.model.personnels.vo.roster.FtbPersonnlesJobTenureVO;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.FtbPersonneApi;
import jnpf.personnels.service.FtbPersonnelsMetaDataService;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Title: CultivateLearnUtils
 * @Author: xuguilin
 * @create: 2024/3/21 11:25
 */
@Component
@Slf4j
public class CultivateLearnUtils {

    @Autowired
    private FtbCultivateLearnCategoriesService cultivateLearnCategoriesService;


    @Autowired
    private FtbCultivateLearnTaskAssignmentService taskAssignmentService;

    @Autowired
    private FtbCultivateLearnTaskCourseService taskCourseService;

    /**
     * 考试用户服务
     */
    @Autowired
    private FtbCultivateExamUserService examUserService;


    @Autowired
    private FtbCultivateLearnTaskExamService taskExamService;

    @Autowired
    private FtbCultivateLearnTaskIdentificationService taskIdentificationService;

    @Autowired
    private FtbCultivateLearnTaskCertificateService taskCertificateService;

    @Autowired
    private FtbCultivateLearnTaskMapper ftbCultivateLearnTaskInfoMapper;

    @Autowired
    private FtbPersonnelsMetaDataService metaDataService;

    @Autowired
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    private CultivateLearnTaskIMUtils cultivateLearnTaskIMUtils;

    @Autowired
    private CultivateIdentifyApplyService cultivateIdentifyApplyService;

    @Autowired
    private FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbCultivatePromotionSettingService ftbCultivatePromotionSettingService;

    @Autowired
    private FtbCultivatePromotionUserService ftbCultivatePromotionUserService;

    @Autowired
    private FtbPersonneApi ftbPersonneApi;

    /**
     * 填充任务列表显示的统计数据
     *
     * @param list 任务列表
     */
    public void fillTaskInfoList(List<FtbCultivateLearnTaskInfoListVO> list) {
        if (CollUtil.isEmpty(list)) {
            return;
        }
        Set<String> cateIdsSet = new HashSet<>();//分类id集合
        Set<String> userIdsSet = new HashSet<>();//创建人id集合
        Set<String> taskIdsSet = new HashSet<>();//任务id集合
        //填充任务分类名称
        for (FtbCultivateLearnTaskInfoListVO vo : list) {
            cateIdsSet.add(vo.getTaskClass());
            userIdsSet.add(vo.getCreatorUserId());
            taskIdsSet.add(vo.getId());
        }

        Map<String, FtbCultivateLearnCategories> categoriesMap = cultivateLearnCategoriesService.queryCateByIds(new ArrayList<>(cateIdsSet));
        Map<String, UserEntity> userNameMap = userApiV2Util.getUserNameAndCopyForUserIds(new ArrayList<>(userIdsSet));

        Map<String, Integer> allTaskNumMap = taskAssignmentService.groupCountNum(new ArrayList<>(taskIdsSet), 0);//所有任务数量
        Map<String, Integer> completeTaskNumMap = taskAssignmentService.groupCountNum(new ArrayList<>(taskIdsSet), 1); //已完成任务数量
        Date now = new Date();
        for (FtbCultivateLearnTaskInfoListVO vo : list) {
            FtbCultivateLearnCategories cate = categoriesMap.get(vo.getTaskClass());
            if (cate != null) {
                vo.setTaskClassName(cate.getName());
            }
            UserEntity roster = userNameMap.get(vo.getCreatorUserId());
            if (roster != null) {
                vo.setCreatorUserName(roster.getRealName());
            }
            vo.setTotleNum(Objects.requireNonNullElse(allTaskNumMap.get(vo.getId()), 0));
            vo.setCompleteTotleNum(Objects.requireNonNullElse(completeTaskNumMap.get(vo.getId()), 0));
            //计算任务剩余天数 0,长期,1限时
            if (vo.getTaskType().equals(1)) {
                if (now.before(vo.getTimeLimitStartTime())) {  //未开始
                    Long diff = DateUtil.betweenDay(vo.getTimeLimitStartTime(), vo.getTimeLimitStartTime(), false);
                    vo.setSurplusDay(diff);
                } else if (now.before(vo.getTimeLimitEndTime())) { //进行中
                    Long diff = DateUtil.betweenDay(vo.getTimeLimitStartTime(), now, false);
                    vo.setSurplusDay(diff);
                } else { //结束
                    vo.setSurplusDay(0L);
                }
            }
        }

    }

    public static List<FtbExportCultivateLearnTaskInfoListVO> convertFtbExportCultivateLearnTaskInfoListVO(List<FtbCultivateLearnTaskInfoListVO> list) {
        List<FtbExportCultivateLearnTaskInfoListVO> retList = new ArrayList<>();
        if (CollUtil.isEmpty(list)) {
            return retList;
        }
        for (FtbCultivateLearnTaskInfoListVO vo : list) {
            FtbExportCultivateLearnTaskInfoListVO exportVo = new FtbExportCultivateLearnTaskInfoListVO();
            exportVo.setId(vo.getId());
            exportVo.setTaskName(vo.getTaskName());
            exportVo.setLearnTaskShowId(vo.getLearnTaskShowId());
            exportVo.setTaskClass(vo.getTaskClass());
            exportVo.setTaskClassName(vo.getTaskClassName());
            exportVo.setTotleNum(vo.getTotleNum());
            exportVo.setCompleteTotleNum(vo.getCompleteTotleNum());
            exportVo.setShowTaskNum(vo.getCompleteTotleNum() + "/" + vo.getTotleNum());
            exportVo.setStatus(vo.getStatus());
            exportVo.setStatusName(convertLearnStatusName(vo.getStatus()));
            exportVo.setSurplusDay(vo.getSurplusDay());
            if (vo.getSurplusDay() == null) {
                exportVo.setSurplusDayStr("-");
            } else {
                exportVo.setSurplusDayStr(String.valueOf(vo.getSurplusDay()));
            }
            exportVo.setTaskType(vo.getTaskType());
            exportVo.setTaskTypeName(convertLearnTypeName(vo.getTaskType()));
            exportVo.setTimeLimitStartTime(vo.getTimeLimitStartTime());
            exportVo.setTimeLimitEndTime(vo.getTimeLimitEndTime());
            if (vo.getTaskType().equals(1)) {
                String timeStr = DateUtil.format(vo.getTimeLimitStartTime(), "yyyy-MM-dd HH:mm:ss") + "-" + DateUtil.format(vo.getTimeLimitEndTime(), "yyyy-MM-dd HH:mm:ss");
                exportVo.setTaskstartEndDateStr(timeStr);
            } else {
                exportVo.setTaskstartEndDateStr("-");
            }
            exportVo.setCreatorUserName(vo.getCreatorUserName());
            exportVo.setCreatorTime(vo.getCreatorTime());
            exportVo.setCreatorTimeStr(DateUtil.format(vo.getCreatorTime(), "yyyy-MM-dd HH:mm:ss"));
            retList.add(exportVo);
        }
        return retList;
    }

    /**
     * 转换学习类型名称
     *
     * @param taskType 0长期,1限时
     * @return 学习类型名称
     */
    private static String convertLearnTypeName(Integer taskType) {
        if (taskType == null) {
            return "";
        }

        switch (taskType) {
            case 0:
                return "长期";
            case 1:
                return "限时";
            default:
                return "";
        }
    }

    /**
     * 转换学习状态名称
     *
     * @param status 学习状态 0未发布,1未开始,2进行中,3已完成,4终止
     * @return 对应的状态名称
     */
    private static String convertLearnStatusName(Integer status) {
        if (status == null) {
            return "";
        }

        switch (status) {
            case 0:
                return "未发布";
            case 1:
                return "未开始";
            case 2:
                return "进行中";
            case 3:
                return "已结束";
            case 4:
                return "终止";
            default:
                return "";
        }
    }


    /**
     * 获取登录用户所属租户code
     *
     * @return 登录用户所属租户code
     */
    public String getTenantId() {
        UserInfo userInfo = UserProvider.getUser();
        return userInfo.getTenantId();
    }

    /**
     * 填充任务统计列表相关数据
     *
     * @param list 任务统计列表
     */
    public void fillLearnCountList(List<FtbCultivateLearnTaskInfoCountListVO> list) {
        if (CollUtil.isEmpty(list)) {
            return;
        }
        Set<String> taskIdsSet = new HashSet<>();//任务id集合
        //填充任务分类名称
        for (FtbCultivateLearnTaskInfoCountListVO vo : list) {
            taskIdsSet.add(vo.getId());
        }
        Map<String, TaskRelationCertificateVo> certificateNameMap = queryCertificateName(new ArrayList<>(taskIdsSet));
        Map<String, TaskRelationIdentificationVo> allIdentificationNameMap = queryIdentificationName(new ArrayList<>(taskIdsSet));
        Map<String, TaskRelationExamVo> allExamNameMap = queryExamMap(new ArrayList<>(taskIdsSet));//查询任务id对应->考试信息
        Map<String, Integer> allExamUserNumMap = examUserService.groupAllCountNumV2(new ArrayList<>(taskIdsSet)); //所有的考试人数
        Map<String, Integer> allPassExamUserNumMap = examUserService.groupPassCountNumV2(new ArrayList<>(taskIdsSet)); //所有通过的考试人数
        Map<String, Integer> allCourseNumMap = taskCourseService.groupCountNum(new ArrayList<>(taskIdsSet)); //所有课程数量
        Map<String, Integer> allTaskNumMap = taskAssignmentService.groupCountNum(new ArrayList<>(taskIdsSet), 0);//所有任务数量
        Map<String, Integer> completeTaskNumMap = taskAssignmentService.groupCountNum(new ArrayList<>(taskIdsSet), 1); //已完成任务数量
        Map<String, List<FtbCultivateLearnTaskAssignment>> allGroupUserListMap = taskAssignmentService.groupListAssignment(new ArrayList<>(taskIdsSet));//查询每个任务的用户列表 taskID->userlist
        Map<String, List<FtbCultivateLearnTaskCourse>> allCourseListMap = taskCourseService.groupListTaskCourse(new ArrayList<>(taskIdsSet)); //所有课程列表 taskid->courselist
        Map<String, List<String>> completeLearnMap = queryCultivatePositionCourceLearning(allGroupUserListMap); //用户->已经完成的课程id列表
//        List<String> tableIds = getAllTableId(allIdentificationNameMap);
        Map<String, Integer> userAllIdentifyMap = cultivateIdentifyApplyService.groupIdentifyCountNum(new ArrayList<>(taskIdsSet), 0); //鉴定所有的人数
        Map<String, Integer> userPassIdentifyMap = cultivateIdentifyApplyService.groupIdentifyCountNum(new ArrayList<>(taskIdsSet), 1); //鉴定通过人数

        for (FtbCultivateLearnTaskInfoCountListVO vo : list) {

            //应完成人数 任务完成人数 任务完成率
            Integer allNum = allTaskNumMap.get(vo.getId());
            if (allNum != null) {
                vo.setTaskTotleNum(allNum);
            } else {
                vo.setTaskTotleNum(0);
            }
            Integer completeNum = completeTaskNumMap.get(vo.getId());
            if (completeNum != null) {
                vo.setTaskCompleteTotleNum(completeNum);
            } else {
                vo.setTaskCompleteTotleNum(0);
            }
            vo.setTaskCompleteLv(convertLv(vo.getTaskCompleteTotleNum(), vo.getTaskTotleNum()));
            //课程数量 完课率
            Integer courseNum = allCourseNumMap.get(vo.getId());
            vo.setCourseNum(courseNum);
            //完课率
            List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments = allGroupUserListMap.get(vo.getId());
            Integer completeCourse = calCompleteNum(allCourseListMap.get(vo.getId()), ftbCultivateLearnTaskAssignments, completeLearnMap);
            vo.setCompleteCourseLv(convertLv(completeCourse, vo.getTaskTotleNum()));

            //考试名称
            TaskRelationExamVo examVo = allExamNameMap.get(vo.getId());
            if (examVo != null) {
                vo.setExamName(examVo.getExamName());
                //参与考试人数 考试合格率
                Integer examNum = allExamUserNumMap.get(vo.getId());
                if (examNum != null) {
                    vo.setCompleteExamUserNum(examNum);
                } else {
                    vo.setCompleteExamUserNum(0);
                }
                vo.setExamPassLv(convertLv(allPassExamUserNumMap.get(vo.getId()), allNum));
            } else {
                vo.setExamName("-");
                vo.setExamPassLv("-");
            }
            //鉴定名称
            TaskRelationIdentificationVo identificationVo = allIdentificationNameMap.get(vo.getId());
            if (identificationVo != null) {
                vo.setIdentificationName(identificationVo.getIdentificationName());
                //鉴定人数 鉴定合格率
                Integer allIdentifyNum = userAllIdentifyMap.get(identificationVo.getTaskId());
                if (allIdentifyNum != null) {
                    vo.setCompleteIdentificationNum(allIdentifyNum);
                } else {
                    vo.setCompleteIdentificationNum(0);
                }

                vo.setIdentificationPassLv(convertLv(userPassIdentifyMap.get(identificationVo.getTaskId()), allNum));

            } else {
                vo.setIdentificationName("-");
                vo.setIdentificationPassLv("-");
            }
            //证书名称
            TaskRelationCertificateVo certificateVo = certificateNameMap.get(vo.getId());
            if (certificateVo != null) {
                vo.setCertificateName(certificateVo.getCertificateName());
                //已颁发证书
                vo.setSendCertificateNum(calCerTificateNum(ftbCultivateLearnTaskAssignments));

            } else {
                vo.setCertificateName("-");
            }

        }

    }

    /**
     * 统计所有的鉴定表id
     *
     * @param allIdentificationNameMap
     * @return
     */
    private List<String> getAllTableId(Map<String, TaskRelationIdentificationVo> allIdentificationNameMap) {
        List<String> ret = new ArrayList<>();
        if (CollUtil.isEmpty(allIdentificationNameMap)) {
            return ret;
        }
        //遍历 allIdentificationNameMap
        for (Map.Entry<String, TaskRelationIdentificationVo> entry : allIdentificationNameMap.entrySet()) {
            String key = entry.getKey();
            TaskRelationIdentificationVo value = entry.getValue();
            if (value != null) {
                ret.add(value.getTableId());
            }
        }
        return ret;

    }

    /**
     * 计算整数数量
     *
     * @param ftbCultivateLearnTaskAssignments 任务人员列表
     * @return 获取证书数量
     */
    private Integer calCerTificateNum(List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments) {
        Integer num = 0;
        if (CollUtil.isEmpty(ftbCultivateLearnTaskAssignments)) {
            return num;
        }
        for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : ftbCultivateLearnTaskAssignments) {
            if (ftbCultivateLearnTaskAssignment.getIssuedCertificate() > 0) {
                num += ftbCultivateLearnTaskAssignment.getIssuedCertificate();
            }
        }
        return num;
    }

    /**
     * 计算完成的课程数量
     *
     * @param courseList         课程列表
     * @param userAssignmentList 人员列表
     * @param completeLearnMap   已完成课程MAP
     * @return
     */
    private Integer calCompleteNum(List<FtbCultivateLearnTaskCourse> courseList, List<FtbCultivateLearnTaskAssignment> userAssignmentList, Map<String, List<String>> completeLearnMap) {
        if (CollUtil.isEmpty(courseList)) {
            return 0;
        }
        if (CollUtil.isEmpty(userAssignmentList)) {
            return 0;
        }
        if (CollUtil.isEmpty(completeLearnMap)) {
            return 0;
        }
        List<String> allCoueseList = courseList.stream().map(FtbCultivateLearnTaskCourse::getCourseId).collect(Collectors.toList());
        int completeNum = 0;
        for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : userAssignmentList) {
            List<String> completeCourseList = completeLearnMap.get(ftbCultivateLearnTaskAssignment.getUserId());
            if (CollUtil.isEmpty(completeCourseList)) {
                continue;
            }
            boolean isSubset = completeCourseList.containsAll(allCoueseList);
            if (isSubset) {
                completeNum++;
            }
        }
        return completeNum;
    }

    private Map<String, List<String>> queryCultivatePositionCourceLearning(Map<String, List<FtbCultivateLearnTaskAssignment>> allGroupUserListMap) {
        Map<String, List<String>> retMap = new HashMap<>();
        if (CollUtil.isEmpty(allGroupUserListMap)) {
            return retMap;
        }
        Set<String> userIdSet = new HashSet<>();
        for (Map.Entry<String, List<FtbCultivateLearnTaskAssignment>> entry : allGroupUserListMap.entrySet()) {
            String key = entry.getKey();
            List<FtbCultivateLearnTaskAssignment> assignments = entry.getValue();
            for (FtbCultivateLearnTaskAssignment assignment : assignments) {
                userIdSet.add(assignment.getUserId());
            }
        }
        if (CollUtil.isEmpty(userIdSet)) {
            return retMap;
        }
        List<FtbCultivatePositionCourceLearning> ftbCultivatePositionCourceLearnings = ftbCultivatePositionCourceLearningMapper.listCompleteCourseForUserIds(new ArrayList<>(userIdSet));
        if (CollUtil.isEmpty(ftbCultivatePositionCourceLearnings)) {
            return retMap;
        }

        for (FtbCultivatePositionCourceLearning entity : ftbCultivatePositionCourceLearnings) {
            List<String> courseIdList = retMap.get(entity.getUserId());
            if (courseIdList == null) {
                courseIdList = new ArrayList<>();
            }
            courseIdList.add(entity.getCourceId());
            retMap.put(entity.getUserId(), courseIdList);
        }
        return retMap;
    }

    /**
     * 任务统计导出转换函数
     *
     * @param list 任务统计列表
     * @return
     */
    public static List<FtbExportCultivateLearnTaskInfoCountListVO> convertFtbExportCultivateLearnTaskInfoCountListVO(List<FtbCultivateLearnTaskInfoCountListVO> list) {

        List<FtbExportCultivateLearnTaskInfoCountListVO> exportList = new ArrayList<>();
        if (CollUtil.isEmpty(list)) {
            return exportList;
        }
        exportList = BeanUtil.copyToList(list, FtbExportCultivateLearnTaskInfoCountListVO.class);
        for (FtbExportCultivateLearnTaskInfoCountListVO exportVo : exportList) {
            String showTaskstartEndDateStr = "";
            if (exportVo.getTaskType().equals(1)) {
                showTaskstartEndDateStr = DateUtil.format(exportVo.getTimeLimitStartTime(), "yyyy-MM-dd HH:mm:ss") + "-" + DateUtil.format(exportVo.getTimeLimitEndTime(), "yyyy-MM-dd HH:mm:ss");
                exportVo.setShowTaskstartEndDateStr(showTaskstartEndDateStr);
            } else {
                exportVo.setShowTaskstartEndDateStr("永久");
            }
            if (exportVo.getCompleteExamUserNum() != null) {
                exportVo.setCompleteExamUserNumStr(exportVo.getCompleteExamUserNum() + "");
            } else {
                exportVo.setCompleteExamUserNumStr("-");
            }
            if (exportVo.getCompleteIdentificationNum() != null) {
                exportVo.setCompleteIdentificationNumStr(exportVo.getCompleteIdentificationNum() + "");
            } else {
                exportVo.setCompleteIdentificationNumStr("-");
            }
            if (exportVo.getSendCertificateNum() != null) {
                exportVo.setSendCertificateNumStr(exportVo.getSendCertificateNum() + "");
            } else {
                exportVo.setSendCertificateNumStr("-");
            }

            exportVo.setTaskTypeName(convertLearnTypeName(exportVo.getTaskType()));
            exportVo.setStatusName(convertLearnStatusName(exportVo.getStatus()));
            exportVo.setCreatorTimeStr(DateUtil.format(exportVo.getCreatorTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return exportList;

    }

    /**
     * 批量查询证书名称
     *
     * @param taskIds 任务ID集合
     * @return
     */
    private Map<String, TaskRelationCertificateVo> queryCertificateName(ArrayList<String> taskIds) {
        Map<String, TaskRelationCertificateVo> retMap = new HashMap<>();
        if (CollUtil.isEmpty(taskIds)) {
            return retMap;
        }
        List<TaskRelationCertificateVo> list = taskCertificateService.queryCertificateName(taskIds);
        if (CollUtil.isEmpty(list)) {
            return retMap;
        }
        for (TaskRelationCertificateVo vo : list) {
            retMap.put(vo.getTaskId(), vo);
        }
        return retMap;
    }

    /**
     * 批量查询鉴定名称
     *
     * @param taskIds 任务ID集合
     * @return
     */
    private Map<String, TaskRelationIdentificationVo> queryIdentificationName(List<String> taskIds) {
        Map<String, TaskRelationIdentificationVo> retMap = new HashMap<>();
        if (CollUtil.isEmpty(taskIds)) {
            return retMap;
        }
        List<TaskRelationIdentificationVo> list = taskIdentificationService.queryIdentificationName(taskIds);
        if (CollUtil.isEmpty(list)) {
            return retMap;
        }
        for (TaskRelationIdentificationVo taskRelationIdentificationVo : list) {
            retMap.put(taskRelationIdentificationVo.getTaskId(), taskRelationIdentificationVo);
        }
        return retMap;
    }

    /**
     * 批量查询任务考试信息
     *
     * @param taskIds 任务ID集合
     * @return
     */
    private Map<String, TaskRelationExamVo> queryExamMap(List<String> taskIds) {
        Map<String, TaskRelationExamVo> retMap = new HashMap<>();
        if (CollUtil.isEmpty(taskIds)) {
            return retMap;
        }
        List<TaskRelationExamVo> list = taskExamService.queryExamBaseInfo(taskIds);
        if (CollUtil.isEmpty(list)) {
            return retMap;
        }
        for (TaskRelationExamVo taskRelationExamVo : list) {
            retMap.put(taskRelationExamVo.getTaskId(), taskRelationExamVo);
        }
        return retMap;
    }

    /**
     * 计算百分比
     *
     * @param a
     * @param b
     * @return
     */
    public static String convertLv(Integer a, Integer b) {
        if (a == null || a.equals(0)) {
            return "0%";
        }
        if (b.equals(0)) {
            return "0%";
        }
        int round = Math.round((a / (float) b) * 100);
        return round + "%";
    }

    public void organizeOrPositionChange(List<String> userIds, String tenantCode) {
        List<UserBoundVO> userLists = userApiV2Util.getUserPrimaryBoundBatchReturnList(userIds, tenantCode);
        if (CollUtil.isEmpty(userLists)) {
            return;
        }
        //司令龄
//        Map<String, Integer> companyAgeMap = metaDataService.queryCompanyAge(userLists.stream().map(UserBoundVO::getId).collect(Collectors.toList()));
//        //岗位龄
//        Map<String, Integer> postAgeMap = queryPostAge(userLists, tenantCode);
        //查询满足条件的任务
        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = new LambdaQueryWrapper<FtbCultivateLearnTask>()
                .eq(FtbCultivateLearnTask::getEnableMark, 0)
                .eq(FtbCultivateLearnTask::getAssignmentRule, 2)
                .notIn(FtbCultivateLearnTask::getStatus, 3, 4);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskInfoMapper.selectList(wrapper);
        if (CollUtil.isEmpty(taskList)) {
            return;
        }
        List<String> taskIds = taskList.stream()
                .map(FtbCultivateLearnTask::getId)
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWrapper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                .in(FtbCultivateLearnTaskAssignment::getTaskId, taskIds);
        List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWrapper);
        Map<String, List<FtbCultivateLearnTaskAssignment>> cultivateTaskMap = assignList.stream()
                .collect(Collectors.groupingBy(FtbCultivateLearnTaskAssignment::getTaskId));
        List<FtbCultivateLearnTaskAssignment> addAssignmentList = new ArrayList<>();
        for (FtbCultivateLearnTask task : taskList) {


            Set<String> existUserIds = new HashSet<>();
            List<FtbCultivateLearnTaskAssignment> taskMapOrDefault = cultivateTaskMap.getOrDefault(task.getId(), new ArrayList<>());
            if (CollUtil.isNotEmpty(taskMapOrDefault)) {
                for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : taskMapOrDefault) {
                    existUserIds.add(ftbCultivateLearnTaskAssignment.getUserId());
                }
            }
            for (UserBoundVO newUser : userLists) {
                if (!existUserIds.contains(newUser.getId())
                        && StringUtils.isNotEmpty(newUser.getOrganizeId())
                        && StringUtils.isNotEmpty(task.getAssociationIds())
                        && task.getAssociationIds().contains(newUser.getOrganizeId())
                ) {
                    FtbCultivateLearnTaskAssignment add = new FtbCultivateLearnTaskAssignment();
                    add.setTaskId(task.getId());
                    add.setUserId(newUser.getId());
                    add.setStudyStats(0);
                    add.setEnableMark(0);
                    addAssignmentList.add(add);
                }
            }
        }
        if (CollUtil.isNotEmpty(addAssignmentList)) {
            addUserToTaskReal(addAssignmentList);
        }
    }


    public void addNewPersonToTask(List<String> userIds, String tenantCode) {
        List<UserBoundVO> userLists = userApiV2Util.getUserPrimaryBoundBatchReturnList(userIds, tenantCode);
        if (CollUtil.isEmpty(userLists)) {
            return;
        }
        //司令龄
        Map<String, Integer> companyAgeMap = metaDataService.queryCompanyAge(userLists.stream().map(UserBoundVO::getId).collect(Collectors.toList()));
        //岗位龄
        Map<String, Integer> postAgeMap = queryPostAge(userLists, tenantCode);
        //查询满足条件的任务
        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = new LambdaQueryWrapper<FtbCultivateLearnTask>()
                .eq(FtbCultivateLearnTask::getEnableMark, 0)
                .eq(FtbCultivateLearnTask::getAssignmentRule, 4)
                .notIn(FtbCultivateLearnTask::getStatus, 3, 4);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskInfoMapper.selectList(wrapper);
        if (CollUtil.isEmpty(taskList)) {
            return;
        }
        List<FtbCultivateLearnTaskAssignment> addAssignmentList = new ArrayList<>();
        for (FtbCultivateLearnTask task : taskList) {

            List<String> realUserId = new ArrayList<>();
            Integer endEntryPeriod = task.getEndEntryPeriod();
            if (task.getCustomAssignType().equals(0)) {
                for (UserBoundVO userEntity : userLists) {
                    Integer age = companyAgeMap.get(userEntity.getId());
                    if (age == null) {
                        continue;
                    }
                    if (age <= endEntryPeriod) {
                        realUserId.add(userEntity.getId());
                    }

                }
            } else {
                for (UserBoundVO userEntity : userLists) {
                    if (StringUtils.isNotEmpty(userEntity.getPositionId())
                            && StringUtils.isNotEmpty(task.getCustomAssignPostIds())
                            && task.getCustomAssignPostIds().contains(userEntity.getPositionId())
                    ) {
                        Integer age = postAgeMap.get(userEntity.getId());
                        if (age == null) {
                            continue;
                        }
                        if (age >= endEntryPeriod) {
                            realUserId.add(userEntity.getId());
                        }
                    }
                }
            }
            if (CollUtil.isEmpty(realUserId)) {
                continue;
            }
            Set<String> existUserIds = new HashSet<>();
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWraper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                    .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                    .eq(FtbCultivateLearnTaskAssignment::getTaskId, task.getId());
            List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWraper);
            if (CollUtil.isNotEmpty(assignList)) {
                for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : assignList) {
                    existUserIds.add(ftbCultivateLearnTaskAssignment.getUserId());
                }
            }
            for (String userId : realUserId) {
                if (!existUserIds.contains(userId)) {
                    FtbCultivateLearnTaskAssignment add = new FtbCultivateLearnTaskAssignment();
                    add.setTaskId(task.getId());
                    add.setUserId(userId);
                    add.setStudyStats(0);
                    add.setEnableMark(0);
                    addAssignmentList.add(add);
                }
            }
        }
        if (CollUtil.isNotEmpty(addAssignmentList)) {
            addUserToTaskReal(addAssignmentList);
        }
    }


    private Map<String, Integer> queryPostAge(List<UserBoundVO> userBoundVOList, String tenantId) {
        // 转换为用户任职信息列表
        List<FtbPersonnlesJoeInfo> joeInfoList = userBoundVOList.stream()
                .map(user -> {
                    FtbPersonnlesJoeInfo info = new FtbPersonnlesJoeInfo();
                    info.setUserId(user.getId());
                    info.setPositionId(user.getPositionId());
                    return info;
                })
                .collect(Collectors.toList());

        // 查询岗龄信息
        FtbPersonnlesJobTenureDTO tenureDTO = new FtbPersonnlesJobTenureDTO();
        tenureDTO.setUserInfo(joeInfoList);
        tenureDTO.setTenantId(tenantId);

        List<FtbPersonnlesJobTenureVO> tenureList = ftbPersonneApi.queryPositionTenureAge(tenureDTO);
        if (CollUtil.isEmpty(tenureList)) {
            return new HashMap<>();
        }

        return tenureList.stream()
                .collect(Collectors.toMap(FtbPersonnlesJobTenureVO::getUserId, FtbPersonnlesJobTenureVO::getJobTenure));
    }


    /**
     * 真正添加人到任务列表
     *
     * @param addAssignmentList 新增任务
     */
    private void addUserToTaskReal(List<FtbCultivateLearnTaskAssignment> addAssignmentList) {
        for (FtbCultivateLearnTaskAssignment vo : addAssignmentList) {
            taskAssignmentService.save(vo);
        }
    }

    /**
     * 计算员工司龄（根据当前日期和入职日期）
     *
     * @param userLists 用户列表
     * @return 用户ID -> 司龄（天）的映射
     */
    private Map<String, Integer> runCompanyAge(List<UserBoundVO> userLists) {
        Map<String, Integer> companyAgeMap = new HashMap<>();
        if (CollUtil.isEmpty(userLists)) {
            return companyAgeMap;
        }

        Date currentDate = new Date();
        for (UserBoundVO user : userLists) {
            if (user.getEntryDate() == null) {
                continue;
            }
            long between = DateUtil.between(user.getEntryDate(), currentDate, DateUnit.DAY);
            companyAgeMap.put(user.getId(), (int) between);
        }

        return companyAgeMap;
    }

    /**
     * 每天定时任务检测用户是否加入任务中
     */
    @Transactional
    public void timingAddNewPersonToTask(String tenantId) {
        //查询满足条件的任务
        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = new LambdaQueryWrapper<FtbCultivateLearnTask>()
                .eq(FtbCultivateLearnTask::getEnableMark, 0)
                .eq(FtbCultivateLearnTask::getAssignmentRule, 4)
                .notIn(FtbCultivateLearnTask::getStatus, 3, 4);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskInfoMapper.selectList(wrapper);
        if (CollUtil.isEmpty(taskList)) {
            return;
        }
        List<UserBoundVO> userLists = userApiV2Util.getAllUserList(tenantId);
        if (CollUtil.isEmpty(userLists)) {
            return;
        }
        //查询司令
        Map<String, Integer> companyAgeMap = runCompanyAge(userLists);
        //查询岗领
        Map<String, Integer> postAgeMap = queryPostAge(userLists, tenantId);


        List<FtbCultivateLearnTaskAssignment> addAssignmentList = new ArrayList<>();
        for (FtbCultivateLearnTask task : taskList) {

            List<String> realUserId = new ArrayList<>();
            Integer endEntryPeriod = task.getEndEntryPeriod();
            if (task.getCustomAssignType().equals(0)) {
                for (UserBoundVO userEntity : userLists) {
                    Integer age = companyAgeMap.get(userEntity.getId());
                    if (age == null) {
                        continue;
                    }
                    if (age <= endEntryPeriod) {
                        realUserId.add(userEntity.getId());
                    }

                }
            } else {
                for (UserBoundVO userEntity : userLists) {
                    if (StringUtils.isNotEmpty(userEntity.getPositionId())
                            && StringUtils.isNotEmpty(task.getCustomAssignPostIds())
                            && task.getCustomAssignPostIds().contains(userEntity.getPositionId())
                    ) {
                        Integer age = postAgeMap.get(userEntity.getId());
                        if (age == null) {
                            continue;
                        }
                        if (age <= endEntryPeriod) {
                            realUserId.add(userEntity.getId());
                        }
                    }
                }
            }
            if (CollUtil.isEmpty(realUserId)) {
                continue;
            }
            Set<String> existUserIds = new HashSet<>();
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWraper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                    .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                    .eq(FtbCultivateLearnTaskAssignment::getTaskId, task.getId());
            List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWraper);
            if (CollUtil.isNotEmpty(assignList)) {
                for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : assignList) {
                    existUserIds.add(ftbCultivateLearnTaskAssignment.getUserId());
                }
            }
            for (String userId : realUserId) {
                if (!existUserIds.contains(userId)) {
                    FtbCultivateLearnTaskAssignment add = new FtbCultivateLearnTaskAssignment();
                    add.setTaskId(task.getId());
                    add.setUserId(userId);
                    add.setStudyStats(0);
                    add.setEnableMark(0);
                    addAssignmentList.add(add);
                }
            }
        }
        if (CollUtil.isNotEmpty(addAssignmentList)) {
            addUserToTaskReal(addAssignmentList);
        }
    }


    /**
     * 每天定时定点提醒
     *
     * @param tenantId
     */
    public void timingTaskLearningAlert(String tenantId) {
        List<NeedPerDayAlertDto> taskList = ftbCultivateLearnTaskInfoMapper.queryNeedPerDayAlert();
        if (CollUtil.isEmpty(taskList)) {
            return;
        }
        log.error("timingTaskLearningAlert={}", taskList);
        List<NeedAlertUserDto> alertUserList = new ArrayList<>();
        for (NeedPerDayAlertDto dto : taskList) {
            if (StringUtils.isEmpty(dto.getPerInterval())) {
                continue;
            }
            // 解析时间
            String[] split = dto.getPerInterval().split(":");
            int alertHour = Integer.parseInt(split[0]);
            LocalTime now = LocalTime.now();
            int currHour = now.getHour();
            if (currHour != alertHour) {
                continue;
            }
            //需要提醒 查询未完成的人员列表
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWraper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                    .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                    .in(FtbCultivateLearnTaskAssignment::getStudyStats, 0, 1)
                    .eq(FtbCultivateLearnTaskAssignment::getTaskId, dto.getTaskId());
            List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWraper);
            if (CollUtil.isNotEmpty(assignList)) {
                for (FtbCultivateLearnTaskAssignment assignment : assignList) {
                    NeedAlertUserDto userDto = new NeedAlertUserDto();
                    userDto.setTaskId(dto.getTaskId());
                    userDto.setTaskName(dto.getTaskName());
                    userDto.setUserId(assignment.getUserId());
                    alertUserList.add(userDto);
                }
            }
        }
        log.error("timingTaskLearningAlert user={}", alertUserList);
        if (CollUtil.isNotEmpty(alertUserList)) {
            cultivateLearnTaskIMUtils.sendMsg(alertUserList, tenantId);
        }

    }

    /**
     * 定时检查任务开始消息提醒
     *
     * @param taskList 任务id
     * @param tenantId 租户id
     */
    public void sendStartTaskLearningAlert(List<FtbCultivateLearnTask> taskList, String tenantId) {
        List<NeedAlertUserDto> alertUserList = new ArrayList<>();
        for (FtbCultivateLearnTask dto : taskList) {
            //需要提醒 查询未完成的人员列表
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWraper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                    .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                    .in(FtbCultivateLearnTaskAssignment::getStudyStats, 0, 1)
                    .eq(FtbCultivateLearnTaskAssignment::getTaskId, dto.getId());
            List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWraper);
            if (CollUtil.isNotEmpty(assignList)) {
                for (FtbCultivateLearnTaskAssignment assignment : assignList) {
                    NeedAlertUserDto userDto = new NeedAlertUserDto();
                    userDto.setTaskId(dto.getId());
                    userDto.setTaskName(dto.getTaskName());
                    userDto.setUserId(assignment.getUserId());
                    alertUserList.add(userDto);
                }
            }
        }
        log.error("timingTaskLearningAlert user={}", alertUserList);
        if (CollUtil.isNotEmpty(alertUserList)) {
            cultivateLearnTaskIMUtils.sendMsg(alertUserList, tenantId);
        }

    }


    /**
     * 修改用户的任务状态  长期任务
     *
     * @param tenantCode
     */
    public void updateLongTaskUserTaskStatus(String tenantCode) {
        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(FtbCultivateLearnTask::getId,
                        FtbCultivateLearnTask::getTimeLimitEndTime,
                        FtbCultivateLearnTask::getStudentTimeCompletion,
                        FtbCultivateLearnTask::getTimeCompletionUnit,
                        FtbCultivateLearnTask::getTimeCompletionDays
                ).eq(FtbCultivateLearnTask::getStatus, 3)
                .eq(FtbCultivateLearnTask::getTaskType, 1)
                .eq(FtbCultivateLearnTask::getEnableMark, 0);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskInfoMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(taskList)) {
            //转换成map
            Map<String, FtbCultivateLearnTask> taskMap = taskList.stream().collect(Collectors.toMap(FtbCultivateLearnTask::getId, Function.identity()));
            //获取任务ids集合
            List<String> taskIds = taskList.stream().map(FtbCultivateLearnTask::getId).collect(Collectors.toList());
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.in(FtbCultivateLearnTaskAssignment::getTaskId, taskIds);
            lambdaQuery.in(FtbCultivateLearnTaskAssignment::getStudyStats, 0, 1);
            lambdaQuery.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
            List<FtbCultivateLearnTaskAssignment> taskAssignments = ftbCultivateLearnTaskAssignmentMapper.selectList(lambdaQuery);
            if (CollUtil.isEmpty(taskAssignments)) return;

            List<FtbCultivateLearnTaskAssignment> needUpdate = new ArrayList<>();
            for (FtbCultivateLearnTaskAssignment taskAssignment : taskAssignments) {
                FtbCultivateLearnTask task = taskMap.get(taskAssignment.getTaskId());
                if (task == null) {
                    continue;
                }

                //学习中  限时完成   学员限时完成(0,限时,1不限时)
                if (taskAssignment.getStudyStats() == 1 || taskAssignment.getStudyStats() == 0) {
                    taskAssignment.setStudyStats(3);
                    needUpdate.add(taskAssignment);
                }
            }
            if (CollUtil.isNotEmpty(needUpdate)) {
                taskAssignmentService.updateBatchById(needUpdate, needUpdate.size());
            }
        }

    }

    /**
     * 添加地图人员
     *
     * @param userIds  用户id
     * @param tenantId 租户id
     */
    public void addPromotionUser(List<String> userIds, String tenantId) {
        List<UserBoundVO> userLists = userApiV2Util.getUserPrimaryBoundBatchReturnList(userIds, tenantId);
        if (CollUtil.isEmpty(userLists)) {
            return;
        }
        List<String> positionIds = new ArrayList<>();
        Map<String, List<UserBoundVO>> userMap = new HashMap<>();
        for (UserBoundVO user : userLists) {
            if (StringUtils.isEmpty(user.getPositionId())) {
                continue;
            }
            positionIds.add(user.getPositionId());
            List<UserBoundVO> userList = userMap.get(user.getPositionId());
            if (userList == null) {
                userList = new ArrayList<>();
            }
            userList.add(user);
            userMap.put(user.getPositionId(), userList);
        }

        if (CollUtil.isEmpty(positionIds)) {
            return;
        }
        LambdaQueryWrapper<FtbCultivatePromotionSetting> promotionSettingWrapper = Wrappers.lambdaQuery();
        promotionSettingWrapper.ne(FtbCultivatePromotionSetting::getScope, 3)
                .eq(FtbCultivatePromotionSetting::getEnabledMark, 0)
                .in(FtbCultivatePromotionSetting::getPostId, positionIds)
        ;
        List<FtbCultivatePromotionSetting> promotionSettingList = ftbCultivatePromotionSettingService.list(promotionSettingWrapper);
        if (CollUtil.isEmpty(promotionSettingList)) {
            return;
        }
        List<FtbCultivatePromotionUser> ftbCultivatePromotionUsers = new ArrayList<>();
        for (FtbCultivatePromotionSetting ftbCultivatePromotionSetting : promotionSettingList) {
            List<UserBoundVO> userBoundVOS = userMap.get(ftbCultivatePromotionSetting.getPostId());
            if (CollUtil.isEmpty(userBoundVOS)) {
                continue;
            }
            for (UserBoundVO userBoundVO : userBoundVOS) {
                if (ftbCultivatePromotionSetting.getScope().equals(2)
                        && ftbCultivatePromotionSetting.getPostId().equals(userBoundVO.getPositionId())
                        && ftbCultivatePromotionSetting.getScopeId().equals(userBoundVO.getGradeId())
                ) {
                    FtbCultivatePromotionUser ftbCultivatePromotionUser = new FtbCultivatePromotionUser();
                    ftbCultivatePromotionUser.setPromotionId(ftbCultivatePromotionSetting.getPromotionId());
                    ftbCultivatePromotionUser.setUserId(userBoundVO.getId());
                    ftbCultivatePromotionUser.setEnabledMark(0);
                    ftbCultivatePromotionUsers.add(ftbCultivatePromotionUser);
                } else if (ftbCultivatePromotionSetting.getScope().equals(1)
                        && ftbCultivatePromotionSetting.getPostId().equals(userBoundVO.getPositionId())
                ) {
                    FtbCultivatePromotionUser ftbCultivatePromotionUser = new FtbCultivatePromotionUser();
                    ftbCultivatePromotionUser.setPromotionId(ftbCultivatePromotionSetting.getPromotionId());
                    ftbCultivatePromotionUser.setUserId(userBoundVO.getId());
                    ftbCultivatePromotionUser.setEnabledMark(0);
                    ftbCultivatePromotionUsers.add(ftbCultivatePromotionUser);
                }
            }
        }
        if (CollUtil.isNotEmpty(ftbCultivatePromotionUsers)) {
            for (FtbCultivatePromotionUser user : ftbCultivatePromotionUsers) {
                long count = ftbCultivatePromotionUserService.count(
                        Wrappers.<FtbCultivatePromotionUser>lambdaQuery()
                                .eq(FtbCultivatePromotionUser::getUserId, user.getUserId())
                                .eq(FtbCultivatePromotionUser::getPromotionId, user.getPromotionId())
                                .eq(FtbCultivatePromotionUser::getEnabledMark, 0)
                );
                if (count > 0) {
                    continue;
                }
                ftbCultivatePromotionUserService.save(user);
            }
        }
    }

    public void dealPositionUpdateUser(List<String> userIds, String tenantCode) {
        List<UserBoundVO> userLists = userApiV2Util.getUserPrimaryBoundBatchReturnList(userIds, tenantCode);
        if (CollUtil.isEmpty(userLists)) {
            return;
        }

        LambdaQueryWrapper<FtbCultivateLearnTask> wrapper = new LambdaQueryWrapper<FtbCultivateLearnTask>()
                .eq(FtbCultivateLearnTask::getEnableMark, 0)
                .eq(FtbCultivateLearnTask::getAssignmentRule, 3)
                .notIn(FtbCultivateLearnTask::getStatus, 3, 4);
        List<FtbCultivateLearnTask> taskList = ftbCultivateLearnTaskInfoMapper.selectList(wrapper);
        if (CollUtil.isEmpty(taskList)) {
            return;
        }
        List<String> taskIds = taskList.stream()
                .map(FtbCultivateLearnTask::getId)
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());
        LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignWrapper = new LambdaQueryWrapper<FtbCultivateLearnTaskAssignment>()
                .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                .in(FtbCultivateLearnTaskAssignment::getTaskId, taskIds);
        List<FtbCultivateLearnTaskAssignment> assignList = taskAssignmentService.list(assignWrapper);
        Map<String, List<FtbCultivateLearnTaskAssignment>> cultivateTaskMap = assignList.stream()
                .collect(Collectors.groupingBy(FtbCultivateLearnTaskAssignment::getTaskId));
        List<FtbCultivateLearnTaskAssignment> addAssignmentList = new ArrayList<>();
        for (FtbCultivateLearnTask task : taskList) {


            Set<String> existUserIds = new HashSet<>();
            List<FtbCultivateLearnTaskAssignment> taskMapOrDefault = cultivateTaskMap.getOrDefault(task.getId(), new ArrayList<>());
            if (CollUtil.isNotEmpty(taskMapOrDefault)) {
                for (FtbCultivateLearnTaskAssignment ftbCultivateLearnTaskAssignment : taskMapOrDefault) {
                    existUserIds.add(ftbCultivateLearnTaskAssignment.getUserId());
                }
            }
            for (UserBoundVO newUser : userLists) {
                if (!existUserIds.contains(newUser.getId())
                        && StringUtils.isNotEmpty(newUser.getPositionId())
                        && StringUtils.isNotEmpty(task.getAssociationIds())
                        && task.getAssociationIds().contains(newUser.getPositionId())
                ) {
                    FtbCultivateLearnTaskAssignment add = new FtbCultivateLearnTaskAssignment();
                    add.setTaskId(task.getId());
                    add.setUserId(newUser.getId());
                    add.setStudyStats(0);
                    add.setEnableMark(0);
                    addAssignmentList.add(add);
                }
            }
        }
        if (CollUtil.isNotEmpty(addAssignmentList)) {
            addUserToTaskReal(addAssignmentList);
        }
    }
}
