package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.FtbCultivateCourseService;
import jnpf.cultivate.service.FtbCultivateExamUserService;
import jnpf.cultivate.service.FtbCultivatePositionStatisticesService;
import jnpf.cultivate.service.FtbCultivatePromotionNewService;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.bo.TriggerEventBO;
import jnpf.model.cultivate.dto.learn.BatchCommonCountDto;
import jnpf.model.cultivate.dto.promotion.FtbCultivateCreatMeMapInfoDTO;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionCreatNewDto;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionDto;
import jnpf.model.cultivate.entiy.BaseEntity;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.examidentify.ExamIdentifyTriggerEventDTO;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionMemberNew;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionNew;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionNewMessage;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionPostNew;
import jnpf.model.cultivate.v2.position.vo.CultivateUserPositionVo;
import jnpf.model.cultivate.v2.promotion.req.FtbCultivatePromotionReq;
import jnpf.model.cultivate.v2.promotion.req.V2PromotionOrgStatisticReq;
import jnpf.model.cultivate.v2.promotion.req.V2PromotionPersonStatisticReq;
import jnpf.model.cultivate.v2.promotion.vo.V2CultivatePromotionOrgStatisticVo;
import jnpf.model.cultivate.v2.promotion.vo.V2CultivatePromotionPersonStatisticVo;
import jnpf.model.cultivate.v2.promotion.vo.WebCultivatePromotionListVo;
import jnpf.model.cultivate.vo.course.app.FtbGlobalCurriculumAppVO;
import jnpf.model.cultivate.vo.promotion.*;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.ListIdDTO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.util.SelfGrowthUtil;
import jnpf.util.UserProvider;
import jnpf.util.context.SpringContext;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * @Title: FtbCultivatePromotionNewServiceImpl
 * @Author: peng.hao
 * @create: 2024/3/27 11:38
 */
@Service
public class FtbCultivatePromotionNewServiceImpl extends ServiceImpl<FtbCultivatePromotionNewMapper, FtbCultivatePromotionNew> implements FtbCultivatePromotionNewService {

    @Resource
    FtbCultivatePromotionPostNewMapper ftbCultivatePromotionPostNewMapper;

    @Resource
    FtbCultivatePromotionMemberNewMapper promotionMemberNewMapper;

    @Resource
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    UserApi userApi;

    @Resource
    FtbCultivatePositionStatisticesService statisticesService;

    @Resource
    FtbCultivatePromotionNewMessageMapper messageMapper;

    @Autowired
    CultivatePerUtils cultivatePerUtils;

    @Autowired
    FtbCultivateCourseService cultivateCourseService;

    @Resource
    FtbCultivateExamUserService cultivateExamUserService;

    /**
     * 取出线程池
     */
    @Autowired
    private Executor threadPoolExecutor;
    @Autowired
    private UserApiV2Util userApiV2Util;

    @Override
    public PageListVO<FtbCultivatePromotionNewVO> getList(CultivatePage oldPage, FtbCultivatePromotionDto dto) {
        // 通过旧的分页对象获取培养推广的新分页对象
        Page<FtbCultivatePromotionNewVO> page = oldPage.coverCultivatePage();
        // 调用baseMapper的getList方法更新page对象，传入分页信息和DTO
        page = baseMapper.getList(page, dto);

        // 遍历page对象中的记录，为每个记录添加额外的处理逻辑
        page.getRecords().forEach(vo -> {
            // 创建Lambda查询包装器，用于后续的数据库查询
            LambdaQueryWrapper<FtbCultivatePromotionPostNew> queryWrapper = Wrappers.lambdaQuery();
            // 设置查询条件，查找与当前vo对象的ID匹配的推广帖子
            queryWrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, vo.getId());

            // 执行查询，获取与当前vo对象关联的所有推广帖子
            List<FtbCultivatePromotionPostNew> ftbCultivatePromotionPostNews = ftbCultivatePromotionPostNewMapper.selectList(queryWrapper);
            // 将查询结果按照帖子的级别进行分组
            Map<Integer, List<FtbCultivatePromotionPostNew>> collect = ftbCultivatePromotionPostNews.stream()
                    .collect(Collectors.groupingBy(FtbCultivatePromotionPostNew::getLevel));

            // 查询当前vo对象的学习范围
            Integer learningScope = baseMapper.queryStudyScope(vo.getId());
            // 获取分组后的所有级别
            Set<Integer> integers = collect.keySet();

            // 创建一个用于存储学习地图级别的VO对象
            FtbCultivatePromotionLevelMapVO learnMapLevelsVO = new FtbCultivatePromotionLevelMapVO();
            // 设置学习地图级别的基本信息
            learnMapLevelsVO.setPromotionId(vo.getId());
            learnMapLevelsVO.setPromotion(vo.getPromotion());
            learnMapLevelsVO.setChannelIniName(vo.getChannelIniName());
            learnMapLevelsVO.setPromotionBusinessId(vo.getPromotionBusinessId());
            learnMapLevelsVO.setLearningScope(learningScope);

            // 创建一个列表，用于存储每个级别的选课信息
            List<FtbCultivatePromotionPostSelectCourseInfo> arrayList = new ArrayList<>();
            // 遍历每个级别，获取相应的选课信息并添加到列表中
            for (Integer integer : integers) {
                FtbCultivatePromotionPostSelectCourseInfo selectCourseInfo = getCourseInfo(integer, collect, vo.getId());
                arrayList.add(selectCourseInfo);
            }
            // 将选课信息列表设置到学习地图级别的VO对象中
            learnMapLevelsVO.setPostChannelLevel(arrayList);
            // 将学习地图级别的VO对象设置到vo对象中
            vo.setPostChannelLevel(learnMapLevelsVO);
        });

        // 对page对象进行最终的处理并返回
        return CultivatePage.coverPageList(page);
    }

    @Override
    @Transactional
    public void add(FtbCultivatePromotionCreatNewDto creatDto) {
        FtbCultivatePromotionNew promotionNew = FtbCultivatePromotionCreatNewDto.coverFtbCultivatePromotionCreatDto(creatDto);
        // 新增岗位通道
        String promotionBusinessId = SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.PROMOTION);
        //设置对应的key
        promotionNew.setPromotionBusinessId(promotionBusinessId);
        String promotion = promotionNew.getPromotion();
        if (StringUtils.isNotBlank(promotion)) {
            LambdaQueryWrapper<FtbCultivatePromotionNew> lambdaQuery = Wrappers.lambdaQuery();
            lambdaQuery.eq(FtbCultivatePromotionNew::getPromotion, promotion);
            lambdaQuery.eq(FtbCultivatePromotionNew::getEnableMark, 0);
            Long aLong = baseMapper.selectCount(lambdaQuery);
            if (aLong > 0) {
                throw new RuntimeException("该地图名称已存在！");
            }
        }
        baseMapper.insert(promotionNew);
        //晋升通道id
        String promotionId = promotionNew.getId();
        List<FtbCultivatePromotionPostNewVO> postChannelLevel = creatDto.getPostChannelLevel();
        String postId = postChannelLevel.stream().filter(item -> 1 == item.getChannelLevel()).findFirst().orElse(null).getPostId();
        verifyThatTheInitialPositionIsDuplicated(postId);
        // 添加岗位
        extractedAddNewJobInformation(postChannelLevel, postId, promotionId);
    }

    /**
     * 提取
     *
     * @param postChannelLevel
     * @param postId
     * @param promotionId
     */
    private void extractedAddNewJobInformation(List<FtbCultivatePromotionPostNewVO> postChannelLevel, String postId, String promotionId) {
        Map<Integer, List<FtbCultivatePromotionPostNewVO>> listMap = postChannelLevel.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostNewVO::getChannelLevel));
        Set<Integer> integers = listMap.keySet();
        List<FtbCultivatePromotionPostNew> list = new ArrayList<>();
        for (Integer integer : integers) {
            List<FtbCultivatePromotionPostNewVO> vos = listMap.get(integer);
            if (integer != 1) {
                List<String[]> collect = vos.stream().map(item -> item.getPostId().split(",")).collect(Collectors.toList());
                List<String> stringList = collect.stream().flatMap(Arrays::stream).collect(Collectors.toList());
                if (stringList.contains(postId)) {
                    throw new RuntimeException("初始岗位不可以存在于其他阶段,请移除后重新添加学习地图!");
                }
            }
            if (integer == 1) {
                FtbCultivatePromotionPostNewVO postNewVO = vos.stream().findFirst().orElse(null);
                FtbCultivatePromotionPostNew postNew = FtbCultivatePromotionPostNewVO.coverFtbCultivatePromotionPostVO(postNewVO);
                postNew.setPromotionId(promotionId);
                postNew.setPostId(postNewVO.getPostId());
                postNew.setPostName(postNewVO.getPostName());
                postNew.setSelectCourseNumber(1);
                list.add(postNew);
            } else {
                FtbCultivatePromotionPostNewVO postNewVO = vos.stream().findFirst().orElse(null);
                String itemPostId = postNewVO.getPostId();
                String postName = postNewVO.getPostName();
                String[] split = itemPostId.split(",");
                String[] postNameS = postName.split(",");
//                List<PositionEntity> positionName = positionApi.getPositionName(List.of(split));
                List<PositionVO> positionName = userApiV2Util.listPositionDetailInfoByIds(List.of(split), null);
                if (CollUtil.isEmpty(positionName)) {
                    throw new RuntimeException("对应岗位未匹配对应的数据！");
                }
                Map<String, String> positionMap = positionName.stream().collect(Collectors.toMap(PositionVO::getId, PositionVO::getFullName));
                if (split.length != postNameS.length) {
                    throw new RuntimeException("岗位名称与岗位id数量不匹配,请重新添加!");
                }
                for (int i = 0; i < split.length; i++) {
                    FtbCultivatePromotionPostNew postNew = FtbCultivatePromotionPostNewVO.coverFtbCultivatePromotionPostVO(postNewVO);
                    postNew.setPromotionId(promotionId);
                    String rePostId = split[i];
                    //   String postName1 = postNameS[i];
                    String postName1 = positionMap.get(rePostId);
                    postNew.setPostId(rePostId);
                    postNew.setPostName(postName1);
                    list.add(postNew);
                }
            }
        }
        String tenantId = UserProvider.getUser().getTenantId();
        list.forEach(postNew -> {
            ftbCultivatePromotionPostNewMapper.insert(postNew);
            if (postNew.getLevel() == 1) {
                // 学习地图岗位id
                String postNewId = postNew.getId();
                List<UserBoundVO> partUserInfoVos = userApiV2Util.getUserListForPositions(List.of(postNew.getPostId()), null);
                if (CollUtil.isNotEmpty(partUserInfoVos)) {
                    Map<String, String> stringMap = partUserInfoVos.stream().collect(Collectors.toMap(UserBoundVO::getId, UserBoundVO::getName));
                    ListIdDTO listIdDTO = new ListIdDTO();
                    Set<String> keySet = stringMap.keySet();
                    listIdDTO.setIds(new ArrayList<>(keySet));
//                    List<PositionGradesInfoBoundVO> positionGradesInfoBoundVOS = positionApi.postOrgPositionInfoList(listIdDTO);
                    List<UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatchReturnList(listIdDTO.getIds(), tenantId);
                    // 过滤数据初始岗位相同数据进行新增
                    List<UserBoundVO> infoBoundVOS = userPrimaryBoundBatch.stream().filter(vo -> vo.getPositionId().equals(postNew.getPostId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(infoBoundVOS)) {
                        threadPoolExecutor.execute(() -> {
                            //切换成租户库
                            try {
                                TenantDataSourceUtil.switchTenant(tenantId);
                            } catch (LoginException e) {
                                throw new RuntimeException("切换租户失败");
                            }
                            for (UserBoundVO partUserInfoVo : infoBoundVOS) {
                                FtbCultivateCreatMeMapInfoDTO meMapInfoDTO = FtbCultivateCreatMeMapInfoDTO.covertMe(partUserInfoVo);
                                meMapInfoDTO.setLevel(postNew.getLevel());
                                meMapInfoDTO.setUserName(stringMap.get(meMapInfoDTO.getUserId()));
                                meMapInfoDTO.setPromotionId(postNew.getPromotionId());
                                meMapInfoDTO.setStudyMapJobId(Arrays.asList(postNewId));
                                correspondingPersonnelSelectPositions(meMapInfoDTO);
                            }
                        });
                    }
                }
            }
        });
    }

    @Override
    @Transactional
    public void updatePromotion(FtbCultivatePromotionCreatNewDto creatDto) {
        FtbCultivatePromotionNew promotionNew = FtbCultivatePromotionCreatNewDto.
                coverFtbCultivatePromotionCreatDto(creatDto);
        // 修改后重新学习需要清除之前的对应学习地图创建的用户学习记录
        //       List<FtbCultivatePromotionMeberPostInfo>  postInfoList = baseMapper.getThePositionThisPersonHasChosen(promotionNew.getId());
//        Map<String, List<FtbCultivatePromotionMeberPostInfo>> userPostMap = postInfoList.stream().collect(Collectors.groupingBy(FtbCultivatePromotionMeberPostInfo::getUserId));
        //       Set<String> userSet = userPostMap.keySet();
//        for (String userId : userSet){
//            List<FtbCultivatePromotionMeberPostInfo> postInfos = userPostMap.get(userId);
//            postInfos.forEach(item->{
//                // 清除学习记录
//                cultivateCourseService.learnMapRelearn(userId,item.getPostId());
//            });
//        }
        // 删除岗位信息重新构建
        LambdaUpdateWrapper<FtbCultivatePromotionPostNew> update = Wrappers.lambdaUpdate();
        String id = promotionNew.getId();
        update.eq(FtbCultivatePromotionPostNew::getPromotionId, id);
        ftbCultivatePromotionPostNewMapper.delete(update);
        baseMapper.updateById(promotionNew);
        // 移除晋升通道岗位信息
        LambdaUpdateWrapper<FtbCultivatePromotionPostNew> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, id);
        ftbCultivatePromotionPostNewMapper.delete(wrapper);
        // 移除关联数据 地图成员管理关联数据
        LambdaQueryWrapper<FtbCultivatePromotionMemberNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionMemberNew::getPromotionId, id);
        List<FtbCultivatePromotionMemberNew> memberNews = promotionMemberNewMapper.selectList(lambdaQuery);
        // 新增通知表 成员重新选择
        List<FtbCultivatePromotionNewMessage> collect = memberNews.stream().map(item -> {
            FtbCultivatePromotionNewMessage message = new FtbCultivatePromotionNewMessage();
            message.setPromotionId(id);
            message.setUserId(item.getUserId());
            return message;
        }).collect(Collectors.toList());
        collect.forEach(item -> messageMapper.insert(item));
        LambdaUpdateWrapper<FtbCultivatePromotionMemberNew> memberLambdaUpdateWrapper = Wrappers.lambdaUpdate();
        memberLambdaUpdateWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, id);
        promotionMemberNewMapper.delete(memberLambdaUpdateWrapper);
        String postId = creatDto.getPostChannelLevel().stream().filter(item -> 1 == item.getChannelLevel()).findFirst().orElse(null).getPostId();
        extractedAddNewJobInformation(creatDto.getPostChannelLevel(), postId, id);
    }

    /**
     * 校验初始岗位是否重复添加
     *
     * @param postId
     */
    private void verifyThatTheInitialPositionIsDuplicated(String postId) {
        List<FtbCultivatePromotionPostNew> postNews = getFtbCultivatePromotionPostNews(postId);
        if (CollUtil.isNotEmpty(postNews)) {
            throw new RuntimeException("初始岗位不可添加重复学习地图,请添加其他岗位学习地图!");
        }
    }

    private List<FtbCultivatePromotionPostNew> getFtbCultivatePromotionPostNews(String postId) {
        // 校验初始岗位是否已经添加了学习地图
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPostId, postId);
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getLevel, "1");
        return ftbCultivatePromotionPostNewMapper.selectList(lambdaQuery);
    }


    @Override
    @Transactional
    public String deleteById(String id, boolean flag) {
        // 判断结果1：是-二次确认提示：请谨慎删除，
        // 该通道的初始岗位在岗位学习进行了学习配置，
        // 删除该通道会导致APP端应用了该通道的用户重新选择晋升通道，目前共有X位用户应用了该通道。
        // 确定删除后在APP端将触发重新选择晋升通道
        if (!flag) { //一次删除
            FtbCultivatePromotionStudyDeleteInfo theCurrentMapBindingMembers = getTheCurrentMapBindingMembers(id);
            // 查询是否存在关联数据
            if (CollUtil.isNotEmpty(theCurrentMapBindingMembers.getDeleteInfoVOS())) {
                return "1";
            }
        }
        return deleteByPromotionId(id);
    }

    /**
     * 删除晋升通道
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public String deleteByPromotionId(String id) {
        LambdaUpdateWrapper<FtbCultivatePromotionNew> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(FtbCultivatePromotionNew::getEnableMark, "1");
        updateWrapper.eq(BaseEntity::getId, id);
        // 判断结果2：否-二次确认提示：您确认要删除该通道吗？点击确认后删除
        // 软删除
        baseMapper.update(new FtbCultivatePromotionNew(), updateWrapper);
        LambdaUpdateWrapper<FtbCultivatePromotionPostNew> wrapper = Wrappers.lambdaUpdate();
        // 移除晋升通道岗位信息
        wrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, id);
        ftbCultivatePromotionPostNewMapper.delete(wrapper);
        // 移除关联数据 地图成员管理关联数据
        LambdaUpdateWrapper<FtbCultivatePromotionMemberNew> memberLambdaUpdateWrapper = Wrappers.lambdaUpdate();
        memberLambdaUpdateWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, id);
        promotionMemberNewMapper.delete(memberLambdaUpdateWrapper);
        return null;
    }

    @Override
    public Page<WebCultivatePromotionListVo> webList(Page<WebCultivatePromotionListVo> page, FtbCultivatePromotionReq dto) {
        return baseMapper.webList(page, dto);
    }

    @Override
    public List<BatchCommonCountDto> queryMaxLevel(List<String> promotionIds) {
        List<BatchCommonCountDto> countDtoList = baseMapper.queryMaxLevel(promotionIds);
        if (CollUtil.isEmpty(countDtoList)) {
            return new ArrayList<>();
        }
        return countDtoList;
    }

    @Override
    public Page<V2CultivatePromotionPersonStatisticVo> personStatisticsV2(V2PromotionPersonStatisticReq req, List<String> userIds, Page<V2CultivatePromotionPersonStatisticVo> page) {
        return baseMapper.personStatisticsV2(req, userIds, page);
    }

    @Override
    public List<CultivateUserPositionVo> queryPromotionPosition(List<String> userIds) {
        return baseMapper.queryPromotionPosition(userIds);
    }

    @Override
    public Page<V2CultivatePromotionOrgStatisticVo> mapStatisticPageV2(Page<V2CultivatePromotionOrgStatisticVo> page, V2PromotionOrgStatisticReq req, List<String> userIds) {
        return  baseMapper.mapStatisticPageV2(page, req, userIds);
    }

    @Override
    public List<BatchCommonCountDto> userCountForPromotion(List<String> userIds) {
        List<BatchCommonCountDto> countDtoList = baseMapper.userCountForPromotion(userIds);
        if (CollUtil.isEmpty(countDtoList)) {
            return new ArrayList<>();
        }
        return countDtoList;
    }

    @Override
    public List<BatchCommonCountDto> queryPositionNumForMap(List<String> promotionIds) {
        List<BatchCommonCountDto> countDtoList = baseMapper.queryPositionNumForMap(promotionIds);
        if (CollUtil.isEmpty(countDtoList)) {
            return new ArrayList<>();
        }
        return countDtoList;
    }

    @Override
    public FtbCultivatePromotionStudyDeleteInfo getTheCurrentMapBindingMembers(String id) {
        Map<String, String> map = baseMapper.queryInitializationPositions(id);
        String channelId = map.get("channelId");
        FtbCultivatePromotionStudyDeleteInfo deleteInfo = new FtbCultivatePromotionStudyDeleteInfo();
        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(id);
        deleteInfo.setPromotion(promotionNew.getPromotion());
        deleteInfo.setPromotionBusinessId(promotionNew.getPromotionBusinessId());
        Integer learningScope = baseMapper.queryStudyScope(id);
        deleteInfo.setNumberOfStudyPositions(learningScope);
        List<FtbCultivatePromotionMemberNew> memberNews = baseMapper.queryTheUserSLearnedPositionInformation(id, channelId);
        // 获取用户选择岗位集合
        List<FtbCultivatePromotionDeleteInfoVO> vos = new ArrayList<>();
        for (FtbCultivatePromotionMemberNew me : memberNews) {
            FtbCultivatePromotionDeleteInfoVO deleteInfoVO = new FtbCultivatePromotionDeleteInfoVO();
            String userId = me.getUserId();
            deleteInfoVO.setUserId(userId);
            deleteInfoVO.setUserName(me.getUserName());
            deleteInfoVO.setPostInfo(me.getPostInfo());
            //  查询用户已学习岗位信息
            List<Integer> list = new ArrayList<>();
            list.add(1);
            list.add(2);
            String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId, list);
            if (StringUtils.isNotEmpty(hasStudyPostIds)) {
                List<String> hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
                List<String> postIds = baseMapper.queryChosePostId(userId, id);
                List<String> excludeUnselectedList = hasStudyPostIdsList.stream().filter(postIds::contains).collect(Collectors.toList());
                List<PositionVO> positionNameList = userApiV2Util.listPositionDetailInfoByIds(excludeUnselectedList, null);
                if (CollUtil.isNotEmpty(positionNameList)) {
                    List<String> stringListNames = positionNameList.stream().map(PositionVO::getFullName).collect(Collectors.toList());
                    deleteInfoVO.setStudyPostNames(stringListNames);
                }
            }
            // 将对应的数据添加到列表
            vos.add(deleteInfoVO);
        }
        deleteInfo.setDeleteInfoVOS(vos);
        return deleteInfo;
    }

    @Override
    public FtbCultivateStudyMemberInfo getPromotionById(String id, CultivatePage oldPage) {
        Page<FtbCultivateMemberInfo> page = oldPage.coverCultivatePage();
        FtbCultivateStudyMemberInfo memberInfo = new FtbCultivateStudyMemberInfo();
        // 学习范围
        Integer learningScope = baseMapper.queryStudyScope(id);
        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(id);
        memberInfo.setPromotion(promotionNew.getPromotion());
        memberInfo.setPromotionBusinessId(promotionNew.getPromotionBusinessId());
        // 初始岗位名称
        Map<String, String> map = baseMapper.queryInitializationPositions(id);
        memberInfo.setChannelIniName(map.get("channelIniName"));
        memberInfo.setChannelIniId(map.get("channelId"));
        memberInfo.setLearningScope(learningScope);
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> postQueryWrapper = Wrappers.lambdaQuery();
        postQueryWrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, id);
        List<FtbCultivatePromotionPostNew> ftbCultivatePromotionPostNews = ftbCultivatePromotionPostNewMapper.selectList(postQueryWrapper);
        Map<Integer, List<FtbCultivatePromotionPostNew>> collect = ftbCultivatePromotionPostNews.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostNew::getLevel));
        Set<Integer> integers = collect.keySet();
        memberInfo.setLearningPhase(integers.size());
        // 根据学习地图id查询所有开启的用户的人员
//        LambdaQueryWrapper<FtbCultivatePromotionMemberNew> lambdaQuery = Wrappers.lambdaQuery();
//        lambdaQuery.eq(FtbCultivatePromotionMemberNew::getPromotionId,id);
//        List<FtbCultivatePromotionMemberNew> memberNews = promotionMemberNewMapper.selectList(lambdaQuery);
        List<Integer> learStutaList = new ArrayList<>();
        learStutaList.add(1);
        learStutaList.add(2);
        //  查询用户已学习岗位信息
        List<FtbCultivatePromotionMemberNew> memberNews = baseMapper.queryTheUserSLearnedPositionInformation(id, memberInfo.getChannelIniId());
        List<String> stringList = memberNews.stream().map(item -> item.getUserId() + "_" + item.getCurrentLearningStage()).distinct().collect(Collectors.toList());
        Map<String, List<FtbCultivatePromotionMemberNew>> userPosition = memberNews.stream().collect(Collectors.groupingBy(FtbCultivatePromotionMemberNew::getUserId, Collectors.toList()));
//        Map<String, String> userPosition = memberNews.stream()
//                .collect(Collectors.toMap(FtbCultivatePromotionMemberNew::getUserId, FtbCultivatePromotionMemberNew::getOrganizationInformation,(a,b)->a));
        List<FtbCultivateMemberInfo> list = new ArrayList<>();
        // 封装数据集
        List<String> userIds = memberNews.stream().map(FtbCultivatePromotionMemberNew::getUserId).collect(Collectors.toList());
        Map<String, String> userNameMap = new HashMap<>();
        Map<String, String> userIdSysMap = new HashMap<>();
        Map<String, UserBoundVO> userPrimaryBoundBatch = new HashMap<>();
        if (CollUtil.isNotEmpty(userIds)) {
            userNameMap = cultivatePerUtils.queryRosterNameBasedOnUserId(userIds);
            userIdSysMap = cultivatePerUtils.coverPersonalIds(userIds);
            userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        }
        for (String userInfo : stringList) {
            FtbCultivateMemberInfo ftbCultivateMemberInfo = new FtbCultivateMemberInfo();
            String[] split = userInfo.split("_");
            // 用户信息
            String userId = split[0];
            UserBoundVO userBoundVO = userPrimaryBoundBatch.get(userId);
            if (userBoundVO!=null) {
                ftbCultivateMemberInfo.setUserName(userBoundVO.getUserName());
                String orgStr = userBoundVO.getOrganizeName();
                if(StringUtils.isNotEmpty(userBoundVO.getPositionName())){
                    orgStr = orgStr+"_"+userBoundVO.getPositionName();
                }
                if(StringUtils.isNotEmpty(userBoundVO.getGradeName())){
                    orgStr = orgStr+"_"+userBoundVO.getGradeName();
                }
                ftbCultivateMemberInfo.setOrganizationInformation(orgStr);
            }

            ftbCultivateMemberInfo.setUserId(userId);
            // 当前学习阶段
            String currentLearningStage = split[1];
            // 查询对应地图选择的人员 对应的选择阶段选择
            ftbCultivateMemberInfo.setCurrentLearningStage(currentLearningStage);
            if (!"1".equals(currentLearningStage)) {
                List<String> postIdsChose = baseMapper.queryUserChosesPosts(userId, Integer.valueOf(currentLearningStage), id);
                ftbCultivateMemberInfo.setSelectedStudyPosition(postIdsChose);
            }
            //  查询用户已学习岗位信息
            List<Integer> relist = new ArrayList<>();
            relist.add(1);
            relist.add(2);
            String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId, relist);
            if (StringUtils.isNotEmpty(hasStudyPostIds)) {
                List<String> hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
                List<String> postIds = baseMapper.queryChosePostId(userId, id);
                List<String> excludeUnselectedList = hasStudyPostIdsList.stream().filter(postIds::contains).collect(Collectors.toList());
//                List<PositionEntity> positionNameList = positionApi.getPositionName(excludeUnselectedList);
                List<PositionVO> positionNameList = userApiV2Util.listPositionDetailInfoByIds(excludeUnselectedList, null);
                if (CollUtil.isNotEmpty(positionNameList)) {
                    List<String> stringListNames = positionNameList.stream().map(PositionVO::getFullName).collect(Collectors.toList());
                    ftbCultivateMemberInfo.setPositionLearned(stringListNames);
                }
            }
            if(CollUtil.isEmpty(ftbCultivateMemberInfo.getPositionLearned()) && userBoundVO!=null && "1".equals(currentLearningStage)){
                ftbCultivateMemberInfo.setPositionLearned(List.of(userBoundVO.getPositionName()));
            }
            if (userIdSysMap.containsKey(userId)) {
                ftbCultivateMemberInfo.setUserId(userIdSysMap.get(userId));
            }
            list.add(ftbCultivateMemberInfo);
        }
        PageListVO<FtbCultivateMemberInfo> paginate = CultivatePage.paginate(list, page);
        memberInfo.setMemberList(paginate);
        return memberInfo;
    }

    @Override
    public Integer queryTheCurrentUserLearningMapLevel(String userId, String postId) {
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            return 0;
        }
        Integer mapLevel = promotionMemberNewMapper.queryTheCurrentUserLearningMapLevel(userId, postId, promotionId);
        if (ObjectUtil.isEmpty(mapLevel)) {
            return 1;
        }
        String studying = checkStudying(mapLevel, userId, postId);
        if (StringUtils.isEmpty(studying)) {
            // 学习地图共有多少个阶段
            Integer learningScope = baseMapper.queryHowManyStages(promotionId);
            return checkAndIncrement(mapLevel, learningScope);
        }
        return mapLevel;
    }

    /**
     * 判断当前数字加1是否是最后一个等级，如果不是返回加1后的数，如果是返回最后等级的数。
     *
     * @param currentGrade 当前的数字
     * @return 如果加1不是最后一个等级，返回加1后的数；否则返回最后一个等级的数
     */
    private int checkAndIncrement(int currentGrade, int MAX_GRADE) {
        int incrementedGrade = currentGrade + 1;

        if (incrementedGrade <= MAX_GRADE) {
            return incrementedGrade;
        } else {
            return MAX_GRADE;
        }
    }

    @Override
    public FtbCultivatePromotionLevelMapVO getLearnMapLevels(String channelIniPoId) {
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivatePromotionPostNew::getPostId, channelIniPoId);
        queryWrapper.eq(FtbCultivatePromotionPostNew::getLevel, "1");
        FtbCultivatePromotionPostNew vo = ftbCultivatePromotionPostNewMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(vo)) {
            return null;
        }
        LambdaQueryWrapper<FtbCultivatePromotionNew> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BaseEntity::getId, vo.getPromotionId());
        wrapper.eq(FtbCultivatePromotionNew::getEnableMark, 0);
        FtbCultivatePromotionNew promotionNew = baseMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(promotionNew)) {
            return null;
        }
        // 学习地图id
        String promotionId = vo.getPromotionId();
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> postQueryWrapper = Wrappers.lambdaQuery();
        postQueryWrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, promotionId);
        List<FtbCultivatePromotionPostNew> ftbCultivatePromotionPostNews = ftbCultivatePromotionPostNewMapper.selectList(postQueryWrapper);
        Map<Integer, List<FtbCultivatePromotionPostNew>> collect = ftbCultivatePromotionPostNews.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostNew::getLevel));
        // 学习范围
        Integer learningScope = baseMapper.queryStudyScope(vo.getPromotionId());
        Map<String, String> str = baseMapper.queryInitializationPositions(promotionId);
        String channelIniName = "";
        if (ObjectUtils.isNotEmpty(str)) {
            channelIniName = str.get("channelIniName");
        }
        Set<Integer> integers = collect.keySet();

        FtbCultivatePromotionLevelMapVO learnMapLevelsVO = new FtbCultivatePromotionLevelMapVO();
        learnMapLevelsVO.setPromotionId(promotionId);
        learnMapLevelsVO.setPromotion(promotionNew.getPromotion());
        learnMapLevelsVO.setChannelIniName(channelIniName);
        learnMapLevelsVO.setPromotionBusinessId(promotionNew.getPromotionBusinessId());
        learnMapLevelsVO.setLearningScope(learningScope);
        List<FtbCultivatePromotionPostSelectCourseInfo> arrayList = new ArrayList<>();
        for (Integer integer : integers) {
            FtbCultivatePromotionPostSelectCourseInfo selectCourseInfo = getCourseInfo(integer, collect, promotionId);
            arrayList.add(selectCourseInfo);
        }
        learnMapLevelsVO.setChannelLevel(integers.size());
        learnMapLevelsVO.setPostChannelLevel(arrayList);
        return learnMapLevelsVO;
    }


    @Override
    public FtbCultivatePromotionLevelMapVO getLearnMapLevelsWithMapId(String promotionId) {
        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(promotionId);
        // 学习地图id
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> postQueryWrapper = Wrappers.lambdaQuery();
        postQueryWrapper.eq(FtbCultivatePromotionPostNew::getPromotionId, promotionId);
        List<FtbCultivatePromotionPostNew> ftbCultivatePromotionPostNews = ftbCultivatePromotionPostNewMapper.selectList(postQueryWrapper);
        Map<Integer, List<FtbCultivatePromotionPostNew>> collect = ftbCultivatePromotionPostNews.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostNew::getLevel));
        // 学习范围
        Integer learningScope = baseMapper.queryStudyScope(promotionId);
        Map<String, String> str = baseMapper.queryInitializationPositions(promotionId);
        Set<Integer> integers = collect.keySet();

        FtbCultivatePromotionLevelMapVO learnMapLevelsVO = new FtbCultivatePromotionLevelMapVO();
        learnMapLevelsVO.setPromotionId(promotionId);
        learnMapLevelsVO.setPromotion(promotionNew.getPromotion());
        learnMapLevelsVO.setChannelIniName(str.get("channelIniName"));
        learnMapLevelsVO.setPromotionBusinessId(promotionNew.getPromotionBusinessId());
        learnMapLevelsVO.setLearningScope(learningScope);
        List<FtbCultivatePromotionPostSelectCourseInfo> arrayList = new ArrayList<>();
        for (Integer integer : integers) {
            FtbCultivatePromotionPostSelectCourseInfo selectCourseInfo = getCourseInfo(integer, collect, promotionId);
            arrayList.add(selectCourseInfo);
        }
        learnMapLevelsVO.setChannelLevel(integers.size());
        learnMapLevelsVO.setPostChannelLevel(arrayList);
        return learnMapLevelsVO;
    }

    @Override
    public List<FtbCultivateLearnMapInfoVO> viewLearningMapBasedOnPosition(String userId, String postId, Integer level) {
        // 查询用户已经选择的对应阶段学习地图
        return baseMapper.viewLearningMapBasedOnPosition(userId, postId, level);
    }

    @Override
    public FtbCultivateStudyMemberVO getDetails(String id) {
        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(id);
        FtbCultivateStudyMemberVO memberVO = FtbCultivateStudyMemberVO.coverFtbCultivateStudyMemberVO(promotionNew);
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPromotionId, id);
        List<FtbCultivatePromotionPostNew> postNews = ftbCultivatePromotionPostNewMapper.selectList(lambdaQuery);
        List<FtbCultivatePromotionPostNewVO> newVOList = new ArrayList<>();
        Map<Integer, List<FtbCultivatePromotionPostNew>> collect = postNews.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostNew::getLevel));
        Set<Integer> integers = collect.keySet();
        for (Integer integer : integers) {
            List<FtbCultivatePromotionPostNew> postNews1 = collect.get(integer);
            FtbCultivatePromotionPostNew postNew;
            if (integer == 1) {
                postNew = postNews1.stream().findFirst().orElse(null);
            } else {
                String postId = postNews1.stream().map(FtbCultivatePromotionPostNew::getPostId).collect(Collectors.joining(","));
                String postName = postNews1.stream().map(FtbCultivatePromotionPostNew::getPostName).collect(Collectors.joining(","));
                postNew = postNews1.stream().findFirst().orElse(null);
                assert postNew != null;
                postNew.setPostId(postId);
                postNew.setPostName(postName);
            }
            FtbCultivatePromotionPostNewVO covert = FtbCultivatePromotionPostNew.covert(postNew);
            newVOList.add(covert);
        }
        memberVO.setPostChannelLevel(newVOList);
        return memberVO;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void correspondingPersonnelSelectPositions(FtbCultivateCreatMeMapInfoDTO creatMeMapInfoDTO) {
        List<String> studyMapJobId = creatMeMapInfoDTO.getStudyMapJobId();
        //  二次选择 根据选择岗位加 选学数量确定学习进度
        //  查询用户已学习岗位信息
        Integer currentLearningStage = 0;
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(creatMeMapInfoDTO.getUserId(),
                Collections.singletonList(1), null);
        List<String> hasStudyPostIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
        }
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.in(BaseEntity::getId, studyMapJobId);
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPromotionId, creatMeMapInfoDTO.getPromotionId());
        List<FtbCultivatePromotionPostNew> postNews = ftbCultivatePromotionPostNewMapper.selectList(lambdaQuery);
        List<String> stringList = postNews.stream().map(FtbCultivatePromotionPostNew::getPostId).collect(Collectors.toList());
        int selectCourseNumber = creatMeMapInfoDTO.getStudyMapJobId().size();
        // 查询当前人已学习岗位信息
        List<String> studyPostIds = hasStudyPostIdsList.stream().filter(stringList::contains).distinct().collect(Collectors.toList());
        if (studyPostIds.size() >= selectCourseNumber) {
            currentLearningStage = creatMeMapInfoDTO.getLevel();
            // 已经到下一阶段了
        } else if (creatMeMapInfoDTO.getLevel() > currentLearningStage) {
            currentLearningStage = creatMeMapInfoDTO.getLevel();
        }
        for (String item : studyMapJobId) {
            FtbCultivatePromotionMemberNew promotionMemberNew = FtbCultivateCreatMeMapInfoDTO.covert(creatMeMapInfoDTO);
            promotionMemberNew.setPromotionPostId(item);
            promotionMemberNew.setCurrentLearningStage(currentLearningStage);
            promotionMemberNewMapper.insert(promotionMemberNew);
            // 本岗不需要同步状态
            if (currentLearningStage != 1) {
                LambdaUpdateWrapper<FtbCultivatePromotionMemberNew> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionMemberNew.getPromotionId());
                updateWrapper.eq(FtbCultivatePromotionMemberNew::getUserId, promotionMemberNew.getUserId());
                updateWrapper.set(FtbCultivatePromotionMemberNew::getCurrentLearningStage, currentLearningStage);
                promotionMemberNewMapper.update(null, updateWrapper);
            }
        }
        // 课程数据初始化
        stringList.forEach(str -> cultivateCourseService.learnMapRelearn(creatMeMapInfoDTO.getUserId(), str));
    }

    @Override
    public FtbCultivateUnderMemberInfo queryTheLearningStageOfSubordinates(String userId, String postId) {
        FtbCultivateUnderMemberInfo memberInfo = new FtbCultivateUnderMemberInfo();
        // 根据岗位id查询学习地图主键
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            throw new RuntimeException("该岗位没有学习地图!");
        }
        UserEntity userEntity = userApi.getInfoById(userId);
        memberInfo.setUserId(userEntity.getId());
        memberInfo.setUserName(userEntity.getRealName());
        if (ObjectUtils.isEmpty(promotionId)) {
            BigDecimal bigDecimal = statisticesService.jobLearningProgress(postId, userId);
            memberInfo.setCurrentLearningStage(1);
            memberInfo.setLearningProgress(bigDecimal);
            memberInfo.setLearningScope(0);
            //  查询用户已学习岗位信息
            List<Integer> relist = new ArrayList<>();
            relist.add(1);
            relist.add(2);
            String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId, relist);
            List<String> hasStudyPostIdsList = new ArrayList<>();
            if (StringUtils.isNotEmpty(hasStudyPostIds)) {
                hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
//                List<PositionEntity> positionName = positionApi.getPositionName(hasStudyPostIdsList);
                List<PositionVO> positionName = userApiV2Util.listPositionDetailInfoByIds(hasStudyPostIdsList, null);
                memberInfo.setSelectedStudyPositionIds(hasStudyPostIds);
                memberInfo.setSelectedStudyPosition(positionName.stream().map(PositionVO::getFullName).collect(Collectors.toList()));
            }
            return memberInfo;
        }
        // 学习地图共有多少个阶段
        Integer learningScope = baseMapper.queryHowManyStages(promotionId);
        memberInfo.setLearningScope(learningScope);
        // 当前学习阶段
        LambdaQueryWrapper<FtbCultivatePromotionMemberNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionId);
        lambdaQuery.eq(FtbCultivatePromotionMemberNew::getUserId, userId);
        lambdaQuery.eq(FtbCultivatePromotionMemberNew::getDeleteMark, 0);
        lambdaQuery.orderByDesc(FtbCultivatePromotionMemberNew::getCurrentLearningStage);
        lambdaQuery.last("limit 1");
        FtbCultivatePromotionMemberNew memberNew = promotionMemberNewMapper.selectOne(lambdaQuery);
        //  查询用户已学习岗位信息
        List<Integer> relist = new ArrayList<>();
        relist.add(1);
        relist.add(2);
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId, relist);
        List<String> hasStudyPostIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
        }
        if (ObjectUtils.isEmpty(memberNew)) {
            BigDecimal bigDecimal = statisticesService.jobLearningProgress(postId, userId);
            memberInfo.setCurrentLearningStage(1);
            BigDecimal learningProgress = bigDecimal.multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            memberInfo.setLearningProgress(learningProgress);
            if (CollUtil.isNotEmpty(hasStudyPostIdsList)) {
//                List<PositionEntity> positionName = positionApi.getPositionName(hasStudyPostIdsList);
                List<PositionVO> positionName = userApiV2Util.listPositionDetailInfoByIds(hasStudyPostIdsList, null);
                memberInfo.setSelectedStudyPosition(positionName.stream().map(PositionVO::getFullName).collect(Collectors.toList()));
                memberInfo.setSelectedStudyPositionIds(hasStudyPostIds);
            }
            return memberInfo;
        }
        Integer currentLearningStage = memberNew.getCurrentLearningStage();
        memberInfo.setCurrentLearningStage(currentLearningStage);
        // 已选学岗位
        List<String> postIds = baseMapper.queryChosePostId(userId, promotionId);
        if (CollUtil.isNotEmpty(hasStudyPostIdsList)) {
            List<String> excludeUnselectedList = hasStudyPostIdsList.stream().filter(postIds::contains).collect(Collectors.toList());
//            List<PositionEntity> positionNameList = positionApi.getPositionName(excludeUnselectedList);
            List<PositionVO> positionNameList = userApiV2Util.listPositionDetailInfoByIds(excludeUnselectedList, null);
            if (CollUtil.isNotEmpty(positionNameList)) {
                List<String> stringListNames = positionNameList.stream().map(PositionVO::getFullName).collect(Collectors.toList());
                memberInfo.setSelectedStudyPosition(stringListNames);
                memberInfo.setSelectedStudyPositionIds(excludeUnselectedList.stream().collect(Collectors.joining(",")));
            }
        }
        // 学习进度
        List<BigDecimal> list = new ArrayList<>();
        for (String str : postIds) {
            BigDecimal bigDecimal = statisticesService.jobLearningProgress(str, userId);
            list.add(bigDecimal);
        }
        BigDecimal reduce = list.stream().reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if (reduce.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal divide = reduce.divide(new BigDecimal(postIds.size()), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal learningProgress = divide.multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            memberInfo.setLearningProgress(learningProgress);
        } else {
            memberInfo.setLearningProgress(BigDecimal.ZERO);
        }
        return memberInfo;
    }

    @Override
    @Transactional
    public FtbCultivateNextCourseVO selectPositionsCorrespondingToTheStages(String userId, String postId, Integer level, Integer compulsory) {
        FtbCultivateNextCourseVO ftbCultivateNextCourseVO = new FtbCultivateNextCourseVO();
        // 根据岗位id查询学习地图主键
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            throw new RuntimeException("该岗位没有学习地图!");
        }
        List<Map<String, Object>> maps = baseMapper.queryUserChosesPostsWitId(userId, level, promotionId);
        ftbCultivateNextCourseVO.setMaps(maps);
        List<String> postIds = maps.stream().map(a -> a.get("postId").toString()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(postIds)) {
            // 课程内容
            List<FtbGlobalCurriculumAppVO> fullCurriculumAppList = new ArrayList<>();
            long resultAlreadyLearnCourseNum = 0L;
            for (String traversePostId : postIds) {
                List<FtbGlobalCurriculumAppVO> tempFullCurriculumAppList = baseMapper.onTheJobLearningCourseNew(userId, List.of(traversePostId), compulsory);
                tempFullCurriculumAppList.forEach(item -> {
                    // 学习总人数
                    LambdaQueryWrapper<FtbCultivatePositionCourceLearning> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.in(FtbCultivatePositionCourceLearning::getState, List.of(1, 2));
                    queryWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, item.getCourseId());
                    queryWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
                    item.setLearnTotalNumber(ftbCultivatePositionCourceLearningMapper.selectCount(queryWrapper));
                });
                // 修复如果岗位学习中存在1，2, 3 课程时，如果1，2 课程已学习完，然后把3课程下架或者删除，无法触发考试与鉴定
                // 下层做业务幂等性，会存在重复调用的情况
                long alreadyLearnCourseNum = tempFullCurriculumAppList.stream()
                        .filter(b -> b.getLearnState() == 1).count();
                resultAlreadyLearnCourseNum = resultAlreadyLearnCourseNum + alreadyLearnCourseNum;
                if (alreadyLearnCourseNum == tempFullCurriculumAppList.size() && !tempFullCurriculumAppList.isEmpty()) {
                    SpringContext.getApplicationContext()
                            .publishEvent(new JnpfApplicationEvent<>(
                                    ExamIdentifyTriggerEventDTO.builder()
                                            .postId(traversePostId)
                                            .userId(userId)
                                            .triggerEventType(TriggerEventBO.TriggerEventType.POST)
                                            .build()));
                }
                fullCurriculumAppList.addAll(tempFullCurriculumAppList);
            }
            ftbCultivateNextCourseVO.setFullCurriculumAppList(fullCurriculumAppList);
            // 已学课程数
            ftbCultivateNextCourseVO.setAlreadyLearnCourseNum(resultAlreadyLearnCourseNum);
            // 已选择学习岗位的总课程数
            ftbCultivateNextCourseVO.setTotalCourseNum(fullCurriculumAppList.size());
        }
        return ftbCultivateNextCourseVO;
    }

    @Override
    public void changeTheCurrentPersonSLearningStage(String userId, String postId) {
        // 当前选择岗位 初始化岗位地图()
        // 学习地图id
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        // 初始岗位无学习地图
        if (StringUtils.isEmpty(promotionId)) {
            return;
        }
        // 根据学习地图查询学习层级
        FtbCultivateStudyMemberVO details = getDetails(promotionId);
        //  查询用户已学习岗位信息
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId,
                Collections.singletonList(1), null);
        List<String> hasStudyPostIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
        }
        // 学习层级
        List<FtbCultivatePromotionPostNewVO> postChannelLevel = details.getPostChannelLevel();
        List<Integer> objects = new LinkedList<>();
        for (FtbCultivatePromotionPostNewVO postChannelLevelVO : postChannelLevel) {
            // 获取等级
            Integer channelLevel = postChannelLevelVO.getChannelLevel();
            // 获取选学数量
            Integer selectCourseNumber = postChannelLevelVO.getSelectCourseNumber();
            // 按阶段筛选用户选择岗位进行学习阶段变更
            List<Map<String, Object>> postsWitId = baseMapper.queryUserChosesPostsWitId(userId, channelLevel, promotionId);
            // 当前用户没有选择地图
            if (CollUtil.isEmpty(postsWitId)) {
                continue;
            }
            // 选择的岗位id
            List<String> stringList = postsWitId.stream().map(map -> String.valueOf(map.get("postId"))).collect(Collectors.toList());
            // 查询当前人已学习岗位信息
            List<String> studyPostIds = hasStudyPostIdsList.stream().filter(stringList::contains).distinct().collect(Collectors.toList());
            if (studyPostIds.size() >= selectCourseNumber) {
                objects.add(channelLevel);
            }
        }
        // 更改当前人的学习阶段
        if (CollUtil.isNotEmpty(objects)) {
            // 当前学习阶段
            Integer integer = objects.get(objects.size() - 1);
            LambdaUpdateWrapper<FtbCultivatePromotionMemberNew> lambdaUpdate = Wrappers.lambdaUpdate();
            lambdaUpdate.set(FtbCultivatePromotionMemberNew::getCurrentLearningStage, integer);
            lambdaUpdate.eq(FtbCultivatePromotionMemberNew::getUserId, userId);
            lambdaUpdate.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionId);
            promotionMemberNewMapper.update(null, lambdaUpdate);
        }
    }

    @Override
    public String checkStudying(Integer level, String userId, String postId) {

        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            throw new RuntimeException("该岗位没有学习地图!");
        }
        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(promotionId);
        //   查询用户已学习岗位信息
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId,
                Collections.singletonList(1), null);
        List<String> hasStudyPostIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
        }
        if (StringUtils.isNotEmpty(promotionId)) {
            // 查询用户学习阶段
            LambdaQueryWrapper<FtbCultivatePromotionMemberNew> memberNewLambdaQueryWrapper = Wrappers.lambdaQuery();
            memberNewLambdaQueryWrapper.last("limit 1");
            memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionId);
            memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getUserId, userId);
            memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getDeleteMark, 0);
            FtbCultivatePromotionMemberNew memberNew = promotionMemberNewMapper.selectOne(memberNewLambdaQueryWrapper);
            // 有通道但是没有选择
            if (ObjectUtil.isNotEmpty(memberNew)) {
                // 当前学习阶段
                Integer currentLearningStage = memberNew.getCurrentLearningStage();
                // 如果当前阶段已经学习过了 则不需要重复学习
                if (currentLearningStage > level) {
                    return null;
                }
            }
        }
        // 本岗校验本岗是否学习完成且参加了 考试和鉴定
        Integer learningMapSetting = promotionNew.getLearningMapSetting();
        if (level == 1) {
            // 查询当前岗位是否存在学习课程
            Integer numberOfCourses = baseMapper.checkIfThePositionHasCourses(postId);
            if (numberOfCourses == 0) {
                throw new RuntimeException("当前阶段未绑定学习！无法进行下阶段学习");
            }
            if (!hasStudyPostIdsList.contains(postId)) {
                return "1";
            }
            // 查询本岗岗位学习是否有考试
            List<String> strings = baseMapper.checkIfThereAreExamsForThisPositionWithNew(postId, userId);
            int exmCount = 0;
            if (CollUtil.isNotEmpty(strings)) exmCount = strings.size();
            //  [1:已经完成考试或者合格   2:未完成考试, 3:考试未合格]
            Integer i = cultivateExamUserService.queryExamIsCompleteForUserIdAndPostion(userId, postId,
                    learningMapSetting);
            if (exmCount > 0 && 2 == i) {
                return "2";
            } else if (exmCount > 0 && 3 == i) {
                return "4";
            }
            // 或者实操鉴定
            // List<String> isAPracticalAppraisalIds = baseMapper.checkWhetherThereIsAPracticalAppraisal(postId);
            // 查询当前人实操鉴定是否是二次触发,如果二次触发就不需要校验
            List<String> applyIds = baseMapper.checkWhetherThereIsAPracticalAppraisalWithNew(postId, userId);
            Integer count = 0;
            if (!applyIds.isEmpty())
                count = baseMapper.queryTheNumberOfPracticalAppraisalStudies(List.of(postId), userId, applyIds, learningMapSetting);
            if (!applyIds.isEmpty() && learningMapSetting == 0 && count == 0) {
                return "3";
            } else if (!applyIds.isEmpty() && learningMapSetting == 1 && count == 0) {
                return "5";
            }
            return null;
        }
        List<Map<String, Object>> postsWitId = baseMapper.queryUserChosesPostsWitId(userId, level, promotionId);
        // 选择的岗位id
        List<String> stringList = postsWitId.stream().map(map -> String.valueOf(map.get("postId"))).collect(Collectors.toList());
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPromotionId, promotionId);
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getLevel, level);
        lambdaQuery.last("limit 1");
        FtbCultivatePromotionPostNew postNew = ftbCultivatePromotionPostNewMapper.selectOne(lambdaQuery);
        // 选学数量(根据选学数量控制学习数量)
        Integer selectCourseNumber = postNew.getSelectCourseNumber();
        // 查询当前人已学习岗位信息
        List<String> studyPostIds = hasStudyPostIdsList.stream().filter(stringList::contains).distinct().collect(Collectors.toList());
        // 空为已完成, 1 当前阶段未学习完成, 2岗位学习考试未完成, 3岗位学习实操鉴定未完成
        // 标记选学数量没有完成
        if (studyPostIds.size() < selectCourseNumber) {
            return "1";
        }
        List<String> exmList = new ArrayList<>();
        List<String> idemList = new ArrayList<>();
        int appCount = 0;
        List<String> strings = new ArrayList<>();
        for (String str : studyPostIds) {
            List<String> strings1 = baseMapper.checkIfThereAreExamsForThisPositionWithNew(str, userId);
            if (CollUtil.isNotEmpty(strings1)) exmList.addAll(strings1);
            List<String> isAPracticalAppraisal = baseMapper.checkWhetherThereIsAPracticalAppraisalWithNew(str, userId);
            if (!isAPracticalAppraisal.isEmpty()) {
                appCount += isAPracticalAppraisal.size();
                idemList.add(str);
                strings.addAll(isAPracticalAppraisal);
            }
        }
        //  考试判断
        List<Integer> collect = exmList.stream().map(str ->
                cultivateExamUserService.queryExamIsCompleteForUserIdAndPostionWithNew(str, learningMapSetting)
        ).collect(Collectors.toList());
        //  [1:已经完成考试或者合格   2:未完成考试, 3:考试未合格]
        if (!exmList.isEmpty() && collect.contains(2)) {
            return "2";
        } else if (!exmList.isEmpty() && collect.contains(3)) {
            return "4";
        }
        // 实操鉴定判断
        Integer count = 0;
        if (CollUtil.isNotEmpty(strings))
            count = baseMapper.queryTheNumberOfPracticalAppraisalStudies(idemList, userId, strings, learningMapSetting);
        if (appCount > count && learningMapSetting == 0) {
            return "3";
        } else if (appCount > count && learningMapSetting == 1) {
            return "5";
        }
        return null;
    }

    /**
     * 内部检查学习状态
     * @param level 学习等级
     * @param userId 用户ID
     * @param postId 岗位ID
     * @param promotionId 地图id
     * @return 状态
     */
    @Override
    public String innerCheckStudying(Integer level, String userId, String postId,String promotionId) {

        FtbCultivatePromotionNew promotionNew = baseMapper.selectById(promotionId);
        //   查询用户已学习岗位信息
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId,
                Collections.singletonList(1), null);
        List<String> hasStudyPostIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
        }

        // 查询用户学习阶段
        LambdaQueryWrapper<FtbCultivatePromotionMemberNew> memberNewLambdaQueryWrapper = Wrappers.lambdaQuery();
        memberNewLambdaQueryWrapper.last("limit 1");
        memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getPromotionId, promotionId);
        memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getUserId, userId);
        memberNewLambdaQueryWrapper.eq(FtbCultivatePromotionMemberNew::getDeleteMark, 0);
        FtbCultivatePromotionMemberNew memberNew = promotionMemberNewMapper.selectOne(memberNewLambdaQueryWrapper);
        // 有通道但是没有选择
        if (ObjectUtil.isNotEmpty(memberNew)) {
            // 当前学习阶段
            Integer currentLearningStage = memberNew.getCurrentLearningStage();
            // 如果当前阶段已经学习过了 则不需要重复学习
            if (currentLearningStage > level) {
                return null;
            }
        }

        // 本岗校验本岗是否学习完成且参加了 考试和鉴定
        Integer learningMapSetting = promotionNew.getLearningMapSetting();
        if (level == 1) {
            // 查询当前岗位是否存在学习课程
            Integer numberOfCourses = baseMapper.checkIfThePositionHasCourses(postId);
            if (numberOfCourses == 0) {
                throw new RuntimeException("当前阶段未绑定学习！无法进行下阶段学习");
            }
            if (!hasStudyPostIdsList.contains(postId)) {
                return "1";
            }
            // 查询本岗岗位学习是否有考试
            List<String> strings = baseMapper.checkIfThereAreExamsForThisPositionWithNew(postId, userId);
            int exmCount = 0;
            if (CollUtil.isNotEmpty(strings)) exmCount = strings.size();
            //  [1:已经完成考试或者合格   2:未完成考试, 3:考试未合格]
            Integer i = cultivateExamUserService.queryExamIsCompleteForUserIdAndPostion(userId, postId,
                    learningMapSetting);
            if (exmCount > 0 && 2 == i) {
                return "2";
            } else if (exmCount > 0 && 3 == i) {
                return "4";
            }
            // 或者实操鉴定
            // List<String> isAPracticalAppraisalIds = baseMapper.checkWhetherThereIsAPracticalAppraisal(postId);
            // 查询当前人实操鉴定是否是二次触发,如果二次触发就不需要校验
            List<String> applyIds = baseMapper.checkWhetherThereIsAPracticalAppraisalWithNew(postId, userId);
            Integer count = 0;
            if (!applyIds.isEmpty())
                count = baseMapper.queryTheNumberOfPracticalAppraisalStudies(List.of(postId), userId, applyIds, learningMapSetting);
            if (!applyIds.isEmpty() && learningMapSetting == 0 && count == 0) {
                return "3";
            } else if (!applyIds.isEmpty() && learningMapSetting == 1 && count == 0) {
                return "5";
            }
            return null;
        }
        List<Map<String, Object>> postsWitId = baseMapper.queryUserChosesPostsWitId(userId, level, promotionId);
        // 选择的岗位id
        List<String> stringList = postsWitId.stream().map(map -> String.valueOf(map.get("postId"))).collect(Collectors.toList());
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPromotionId, promotionId);
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getLevel, level);
        lambdaQuery.last("limit 1");
        FtbCultivatePromotionPostNew postNew = ftbCultivatePromotionPostNewMapper.selectOne(lambdaQuery);
        // 选学数量(根据选学数量控制学习数量)
        Integer selectCourseNumber = postNew.getSelectCourseNumber();
        // 查询当前人已学习岗位信息
        List<String> studyPostIds = hasStudyPostIdsList.stream().filter(stringList::contains).distinct().collect(Collectors.toList());
        // 空为已完成, 1 当前阶段未学习完成, 2岗位学习考试未完成, 3岗位学习实操鉴定未完成
        // 标记选学数量没有完成
        if (studyPostIds.size() < selectCourseNumber) {
            return "1";
        }
        List<String> exmList = new ArrayList<>();
        List<String> idemList = new ArrayList<>();
        int appCount = 0;
        List<String> strings = new ArrayList<>();
        for (String str : studyPostIds) {
            List<String> strings1 = baseMapper.checkIfThereAreExamsForThisPositionWithNew(str, userId);
            if (CollUtil.isNotEmpty(strings1)) exmList.addAll(strings1);
            List<String> isAPracticalAppraisal = baseMapper.checkWhetherThereIsAPracticalAppraisalWithNew(str, userId);
            if (!isAPracticalAppraisal.isEmpty()) {
                appCount += isAPracticalAppraisal.size();
                idemList.add(str);
                strings.addAll(isAPracticalAppraisal);
            }
        }
        //  考试判断
        List<Integer> collect = exmList.stream().map(str ->
                cultivateExamUserService.queryExamIsCompleteForUserIdAndPostionWithNew(str, learningMapSetting)
        ).collect(Collectors.toList());
        //  [1:已经完成考试或者合格   2:未完成考试, 3:考试未合格]
        if (!exmList.isEmpty() && collect.contains(2)) {
            return "2";
        } else if (!exmList.isEmpty() && collect.contains(3)) {
            return "4";
        }
        // 实操鉴定判断
        Integer count = 0;
        if (CollUtil.isNotEmpty(strings))
            count = baseMapper.queryTheNumberOfPracticalAppraisalStudies(idemList, userId, strings, learningMapSetting);
        if (appCount > count && learningMapSetting == 0) {
            return "3";
        } else if (appCount > count && learningMapSetting == 1) {
            return "5";
        }
        return null;
    }


    @Override
    public Boolean whetherTheJobLearningMapHasChanged(String userId, String postId) {
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            return false;
        }
        LambdaQueryWrapper<FtbCultivatePromotionNewMessage> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionNewMessage::getPromotionId, promotionId);
        lambdaQuery.eq(FtbCultivatePromotionNewMessage::getUserId, userId);
        lambdaQuery.eq(FtbCultivatePromotionNewMessage::getEnableMark, 0);
        List<FtbCultivatePromotionNewMessage> messages = messageMapper.selectList(lambdaQuery);
        if (CollUtil.isEmpty(messages)) {
            return false;
        }
        LambdaUpdateWrapper<FtbCultivatePromotionNewMessage> lambdaUpdate = Wrappers.lambdaUpdate();
        lambdaUpdate.in(BaseEntity::getId, messages.stream().map(BaseEntity::getId).collect(Collectors.toList()));
        lambdaUpdate.set(FtbCultivatePromotionNewMessage::getEnableMark, 1);
        messageMapper.update(null, lambdaUpdate);
        return true;
    }

    @Override
    public FtbCultivatePromotionWithPersonelVO queryTrainData(String userId, String postId) {
        FtbCultivatePromotionLevelMapVO vo = getLearnMapLevels(postId);
        FtbCultivatePromotionWithPersonelVO withPersonelVO = FtbCultivatePromotionWithPersonelVO.covert(vo);
        if (withPersonelVO == null) {
            return null;
        }
        String promotionId = withPersonelVO.getPromotionId();
        // 岗位层级
        List<FtbCultivatePromotionPostSelectCourseInfo> postChannelLevel = vo.getPostChannelLevel();
        List<BigDecimal> list = new ArrayList<>();
        List<FtbCultivatePromotionWithPersonnelInfo> personnelInfos = new ArrayList<>();
        for (FtbCultivatePromotionPostSelectCourseInfo postChannelLevelVO : postChannelLevel) {
            Integer level = postChannelLevelVO.getLevel();
            FtbCultivatePromotionWithPersonnelInfo info = new FtbCultivatePromotionWithPersonnelInfo();
            List<FtbCultivateLearnMapInfoVO> postInfo = new ArrayList<>();
            info.setLevel(level);
            if (level == 1) {
                // 当前岗位
                BigDecimal bigDecimal = statisticesService.jobLearningProgress(postId, userId);
                list.add(bigDecimal);
                info.setSelectCourseNumber(1);
                FtbCultivateLearnMapInfoVO ftbCultivateLearnMapInfoVO = new FtbCultivateLearnMapInfoVO();
                ftbCultivateLearnMapInfoVO.setPostId(postId);
//                PositionEntity positionEntity = positionApi.queryInfoById(postId);
                PositionVO positionEntity = userApiV2Util.infoPosition(postId, null);
                ftbCultivateLearnMapInfoVO.setPostName(positionEntity.getFullName());
                postInfo.add(ftbCultivateLearnMapInfoVO);
            } else {
                List<Map<String, Object>> postsWitId = baseMapper.queryUserChosesPostsWitId(userId, level, promotionId);
                for (Map<String, Object> map : postsWitId) {
                    String newPostId = String.valueOf(map.get("postId"));
                    BigDecimal bigDecimal = statisticesService.jobLearningProgress(newPostId, userId);
                    list.add(bigDecimal);
                }
                List<FtbCultivateLearnMapInfoVO> ftbCultivateLearnMapInfoVOS = baseMapper.viewLearningMapBasedOnPosition(userId, postId, level);
                info.setSelectCourseNumber(postChannelLevelVO.getSelectCourseNumber());
                postInfo.addAll(ftbCultivateLearnMapInfoVOS);
            }
            info.setPostInfo(postInfo);
            personnelInfos.add(info);

        }
        withPersonelVO.setLearnMapInfoVOS(personnelInfos);
        // 学习范围
        Integer learningScope = withPersonelVO.getLearningScope();
        // 获取所有已经选择的岗位学习进度
        BigDecimal reduce = list.stream().reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if (reduce.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal divide = reduce.divide(new BigDecimal(learningScope), 2, RoundingMode.HALF_UP);
            BigDecimal learningProgress = divide.multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            withPersonelVO.setLearningProgress(learningProgress);
        } else {
            withPersonelVO.setLearningProgress(BigDecimal.ZERO);
        }
        //  查询用户已学习岗位信息
        String hasStudyPostIds = baseMapper.queryThePositionsThatUsersHaveLearned(userId,
                Collections.singletonList(1), null);
        if (StringUtils.isNotEmpty(hasStudyPostIds)) {
            List<String> hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
//            List<PositionEntity> positionNameList = positionApi.getPositionName(hasStudyPostIdsList);
            List<PositionVO> positionNameList = userApiV2Util.listPositionDetailInfoByIds(hasStudyPostIdsList, null);
            if (CollUtil.isNotEmpty(positionNameList)) {
                List<String> stringListNames = positionNameList.stream().map(PositionVO::getFullName).collect(Collectors.toList());
                withPersonelVO.setPositionLearned(stringListNames);
            }
        }
        Map<String, String> map = cultivatePerUtils.coverPersonalIds(Collections.singletonList(userId));
        withPersonelVO.setUserId(userId);
        UserEntity userEntity = userApi.getInfoById(userId);
        if (userEntity != null) {
            withPersonelVO.setUserName(userEntity.getRealName());
        }
        withPersonelVO.setSysUserId(map.get(userId));
        return withPersonelVO;
    }

    @Override
    public Boolean verifyingThePostWillRelearnTheMap(String postId) {
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPostId, postId);
        List<FtbCultivatePromotionPostNew> postNews = ftbCultivatePromotionPostNewMapper.selectList(lambdaQuery);
        if (CollUtil.isNotEmpty(postNews)) {
            return true;
        }
        return false;
    }

    @Override
    public FtbCultivatelearningProgressVO learningProgress(String userId, String postId) {
        FtbCultivatelearningProgressVO ftbCultivatelearningProgressVO = new FtbCultivatelearningProgressVO();
        ftbCultivatelearningProgressVO.setIsConfigured(false);
        // 是否配置了岗位学习课程
        List<String> isConfigured = ftbCultivatePromotionPostNewMapper.isConfigured(postId);
        if (!isConfigured.isEmpty()) {
            ftbCultivatelearningProgressVO.setIsConfigured(true);
            // 学习进度
            Integer learnCount = ftbCultivatePromotionPostNewMapper.learningProgress(userId, isConfigured, List.of(1));
            Integer totalCount = ftbCultivatePromotionPostNewMapper.learningProgress(userId, isConfigured, null);
            BigDecimal bigDecimal = CultivatePerUtils.computeDivision(learnCount, totalCount);
            ftbCultivatelearningProgressVO.setLearningProgress(bigDecimal);
        }
        return ftbCultivatelearningProgressVO;
    }

    @Override
    public List<String> currentPersonChoosesAllPosition(String userId, String postId) {
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            return new ArrayList<>();
        }
        List<String> postIds = baseMapper.queryChosePostId(userId, promotionId);
        if (CollUtil.isNotEmpty(postIds)) {
            return postIds;
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> queryByInitPostIdMapPostId(String postId) {
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(postId);
        if (StringUtils.isEmpty(promotionId)) {
            return new ArrayList<>();
        }
        return baseMapper.queryMapPostId(promotionId);
    }

    @Override
    public List<String> querySelectedPersonnelBasedOnPositionID(List<String> postId) {
        List<String> strings = baseMapper.querySelectedPersonnelBasedOnPositionID(postId);
//        for (String str : strings) {
//            // 查询当前人有没有学习完该岗位课程
//            // 查询学习中的进行初始化
//            String postIds = baseMapper.queryThePositionsThatUsersHaveLearned(str, Collections.singletonList(2),postId);
//            if (StringUtils.isNotEmpty(postIds)  ){
//                List<String> postIdsList = Arrays.stream(postIds.split(",")).distinct().collect(Collectors.toList());
//                if (postIdsList.contains(postId)){
//                    usrIds.add(str);
//                }
//            }
//        }
        return strings;
    }

    @Override
    public Integer getMapPostNumber(String channelIniPoId) {
        // 学习范围
        String promotionId = baseMapper.initialPositionQueryLearningMapPrimaryKey(channelIniPoId);
        return baseMapper.queryStudyScope(promotionId);
    }

    /**
     * 获取对应的地图配置信息
     *
     * @param integer
     * @param collect
     * @param promotionId
     * @return
     */
    @NotNull
    private FtbCultivatePromotionPostSelectCourseInfo getCourseInfo(Integer integer, Map<Integer, List<FtbCultivatePromotionPostNew>> collect, String promotionId) {
        FtbCultivatePromotionPostSelectCourseInfo selectCourseInfo = new FtbCultivatePromotionPostSelectCourseInfo();
        List<FtbCultivatePromotionPostNew> dbPost = collect.get(integer);
        selectCourseInfo.setLevel(integer);
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.last("limit 1");
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getPromotionId, promotionId);
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getLevel, integer);
        FtbCultivatePromotionPostNew postNew = ftbCultivatePromotionPostNewMapper.selectOne(lambdaQuery);
        selectCourseInfo.setSelectCourseNumber(postNew.getSelectCourseNumber());
        // 岗位详情
        List<String> stringList = dbPost.stream().map(FtbCultivatePromotionPostNew::getPostName).collect(Collectors.toList());
        selectCourseInfo.setPostInfo(stringList);
        return selectCourseInfo;
    }

}
