package jnpf.cultivate.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
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.CollectionUtils;
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.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.FtbCultivatePromotionMemberService;
import jnpf.cultivate.service.FtbCultivatePromotionNewService;
import jnpf.cultivate.service.FtbCultivatePromotionPostService;
import jnpf.cultivate.service.FtbCultivatePromotionService;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionCreatDto;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionDto;
import jnpf.model.cultivate.dto.promotion.FtbMapsOrgWisdomStatisticDTO;
import jnpf.model.cultivate.dto.promotion.FtbMapsPersonWisdomStatisticDTO;
import jnpf.model.cultivate.entiy.BaseEntity;
import jnpf.model.cultivate.po.position.FtbCultivatePosition;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourse;
import jnpf.model.cultivate.po.position.FtbCultivatePositionExam;
import jnpf.model.cultivate.po.position.FtbCultivatePositionExamIdentify;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotion;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionMember;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionPost;
import jnpf.model.cultivate.vo.certificate.FtbCertificateOrgWisdomStatisticVO;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.cultivate.vo.promotion.*;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.PositionApi;
import jnpf.permission.UserApi;
import jnpf.permission.model.position.PositionGradesInfoBoundVO;
import jnpf.permission.vo.v2.grades.GradeVO;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.permission.vo.v2.user.UserRelationBaseVO;
import jnpf.util.SelfGrowthUtil;
import jnpf.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FtbCultivatePromotionServiceImpl extends ServiceImpl<FtbCultivatePromotionMapper, FtbCultivatePromotion> implements FtbCultivatePromotionService {
    private static final List<String> EMPTY_USER_LIST = List.of("-1");

    @Resource
    private FtbCultivatePromotionMapper promotionMapper;

    @Resource
    private FtbCultivatePromotionPostService postService;

    @Resource
    private FtbCultivatePromotionMemberService promotionMemberService;
    @Resource
    private FtbCultivatePositionCourseMapper ftbCultivatePositionCourseMapper;
    @Resource
    private FtbCultivatePositionExamMapper ftbCultivatePositionExamMapper;
    @Resource
    private FtbCultivatePositionExamIdentifyMapper ftbCultivatePositionExamIdentifyMapper;
    @Resource
    private FtbCultivatePositionMapper ftbCultivatePositionMapper;

    @Resource
    PositionApi positionApi;

    @Autowired
    private CultivatePerUtils cultivatePerUtils;

    @Autowired
    private FtbCultivatePromotionNewService promotionNewService;

    @Autowired
    private FtbCultivatePromotionNewMapper ftbCultivatePromotionNewMapper;

    @Autowired
    UserApi userApi;
    @Autowired
    private UserApiV2Util userApiV2Util;


    @Override
    public PageListVO<FtbCultivatePromotionVO> getList(CultivatePage oldPage, FtbCultivatePromotionDto dto) {
        Page<FtbCultivatePromotionVO> page = oldPage.coverCultivatePage();
        page = promotionMapper.getList(page, dto);
        return CultivatePage.coverPageList(page);
    }

    @Override
    public void VerifyPromotion(String postId, String gradeId) {
        // 岗位池判断岗位是否存在晋升通道
        if (StringUtil.isNotEmpty(postId)) {
            FtbCultivatePromotionDto dto = new FtbCultivatePromotionDto();
            dto.setPostId(postId);
            Page<FtbCultivatePromotionNewVO> page = new Page<>();
            // v1.1进行调整使用最新的岗位地图
            Page<FtbCultivatePromotionNewVO> list = ftbCultivatePromotionNewMapper.getList(page, dto);
            //   Page<FtbCultivatePromotionVO> list = promotionMapper.getList(page, dto);
            if (CollUtil.isNotEmpty(list.getRecords())) {
                throw new RuntimeException("该岗位存在于学习地图内，不允许删除");
            }
            // 该岗位已绑定岗位学习，不允许删除
            try {
                //                ActionResult<PositionInfoNewVO>  infoNew = positionApi.getInfoNew(postId);
//                if (infoNew.getCode().equals(HttpStatus.BAD_REQUEST)){
//                    throw new RuntimeException(infoNew.getMsg());
//                }
//                PositionInfoNewVO data = infoNew.getData();
                List<GradeVO> gradeVOS = userApiV2Util.listGrades(postId, null);
                List<String> collect = gradeVOS.stream().distinct().map(GradeVO::getId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(collect)) {
                    postLevelDeletionVerification(collect);
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        if (StringUtil.isNotEmpty(gradeId)) {
            postLevelDeletionVerification(List.of(gradeId));
        }
    }

    @Override
    public List<FtbCultivatePromotionVO> queryListByIds(List<String> promotionIds) {

        return promotionMapper.queryListByIds(promotionIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(FtbCultivatePromotionCreatDto creatDto) {
        if (ObjectUtil.isNotEmpty(creatDto.getId())) {
            throw new RuntimeException("新增失败");
        }
        extracted(creatDto);
    }

    private void extracted(FtbCultivatePromotionCreatDto creatDto) {
        FtbCultivatePromotion cultivatePromotion = FtbCultivatePromotionCreatDto.
                coverFtbCultivatePromotionCreatDto(creatDto);
        // 新增岗位通道
        String promotionBusinessId = SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.PROMOTION);
        //设置对应的key
        cultivatePromotion.setPromotionBusinessId(promotionBusinessId);
        promotionMapper.insert(cultivatePromotion);
        //晋升通道id
        String promotionId = cultivatePromotion.getId();
        //新增对应的岗位级别
        List<FtbCultivatePromotionPostVO> postVOList = creatDto.getPostChannelLevel();
        Set<String> postIds = postVOList.stream().map(FtbCultivatePromotionPostVO::getPostId).collect(Collectors.toSet());
        if (postIds.size() != postVOList.size()) {
            throw new RuntimeException("职位列表中存在重复的岗位，请重新检查!");
        }
        // 添加职位数据库校验是否为相同职位相同级别
        whetherThereIsTheSamePromotionChannel(postIds);
        // 添加通道岗位
        savePromotion(postVOList, promotionId);
    }

    /**
     * 校验是否存在相同的晋升通道
     *
     * @param postIds
     */
    private void whetherThereIsTheSamePromotionChannel(Set<String> postIds) {
        List<FtbCultivatePromotionPostVO> list = postService.queryPostHasExist();
        // 不存在数据的情况
        if (ObjectUtil.isEmpty(list)) {
            return;
        }
        Map<String, List<FtbCultivatePromotionPostVO>> postVOMap = list.stream().collect(Collectors.groupingBy(FtbCultivatePromotionPostVO::getPromotionId, Collectors.toList()));
        Set<String> strings = postVOMap.keySet();
        for (String str : strings) {
            List<FtbCultivatePromotionPostVO> postVOListOld = postVOMap.get(str);
            Set<String> postIdsOld = postVOListOld.stream().map(FtbCultivatePromotionPostVO::getPostId).collect(Collectors.toSet());
            if (postIds.equals(postIdsOld)) {
                throw new RuntimeException("系统已存在相同岗位晋升通道，请重新检查!");
            }
        }
    }

    /**
     * 新增数据
     *
     * @param postVOList  岗位列表
     * @param promotionId 通道主键
     */
    private void savePromotion(List<FtbCultivatePromotionPostVO> postVOList, String promotionId) {
        postVOList.forEach(item -> {
            FtbCultivatePromotionPost ftbCultivatePromotionPost = FtbCultivatePromotionPostVO.coverFtbCultivatePromotionPostVO(item);
            //设置晋升通道id
            ftbCultivatePromotionPost.setPromotionId(promotionId);
            postService.save(ftbCultivatePromotionPost);
        });
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addList(List<FtbCultivatePromotionCreatDto> creatDtoList) {
        creatDtoList.forEach(this::extracted);
    }

    @Override
    public void postLevelDeletionVerification(List<String> postRankId) {
        if (CollectionUtils.isEmpty(postRankId)) {
            return;
        }
        // 岗位id获取
        List<PositionGradesInfoBoundVO> positionGradesInfoBoundVOS = positionApi.listPositionGradesInfoByPositionGrades(postRankId.get(0));
        if (CollUtil.isNotEmpty(positionGradesInfoBoundVOS)) {
            String positionId = positionGradesInfoBoundVOS.get(0).getPositionId();
            LambdaQueryWrapper<FtbCultivatePosition> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(FtbCultivatePosition::getEnabledMark, 0);
            queryWrapper.eq(FtbCultivatePosition::getPostId, positionId);
            if (ftbCultivatePositionMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("该岗位已绑定岗位学习，不允许删除!");
            }
        }
        // 岗位学习课程
        LambdaQueryWrapper<FtbCultivatePositionCourse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivatePositionCourse::getEnabledMark, 0);
        queryWrapper.in(FtbCultivatePositionCourse::getPostRankId, postRankId);
        if (ftbCultivatePositionCourseMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("该岗位已绑定岗位学习，不允许删除!");
        }
        // 岗位考试
        LambdaQueryWrapper<FtbCultivatePositionExam> ftbCultivatePositionExamLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbCultivatePositionExamLambdaQueryWrapper.eq(FtbCultivatePositionExam::getEnabledMark, 0);
        ftbCultivatePositionExamLambdaQueryWrapper.in(FtbCultivatePositionExam::getPostRankId, postRankId);
        if (ftbCultivatePositionExamMapper.selectCount(ftbCultivatePositionExamLambdaQueryWrapper) > 0) {
            throw new RuntimeException("该岗位已绑定岗位考试，不允许删除!");
        }
        // 岗位实操鉴定
        LambdaQueryWrapper<FtbCultivatePositionExamIdentify> ftbCultivatePositionExamIdentifyLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbCultivatePositionExamIdentifyLambdaQueryWrapper.eq(FtbCultivatePositionExamIdentify::getEnabledMark, 0);
        ftbCultivatePositionExamIdentifyLambdaQueryWrapper.in(FtbCultivatePositionExamIdentify::getPostRankId, postRankId);
        if (ftbCultivatePositionExamIdentifyMapper.selectCount(ftbCultivatePositionExamIdentifyLambdaQueryWrapper) > 0) {
            throw new RuntimeException("该岗位已绑定岗位实操鉴定，不允许删除!");
        }
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateMapsOrgWisdomStatisticVO> returnEmptyList(FtbMapsOrgWisdomStatisticDTO statisticDTO) {
        PageListVO<FtbCultivateMapsOrgWisdomStatisticVO> pageInfo = new PageListVO<>();
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(statisticDTO.getCurrentPage());
        pagination.setPageSize(statisticDTO.getPageSize());
        pagination.setTotal(0);
        pageInfo.setList(new ArrayList<>());
        pageInfo.setPagination(pagination);
        return pageInfo;
    }

    @Override
    public PageListVO<FtbCultivateMapsOrgWisdomStatisticVO> organizationListStatistics(FtbMapsOrgWisdomStatisticDTO statisticDTO) {
//        Page<FtbCultivateMapsOrgWisdomStatisticVO> page = statisticDTO.coverCultivatePage();
        List<String> orgIds = new ArrayList<>();
        List<String> powerOrgList = userApiV2Util.queryPowerOrgList();
        if (CollUtil.isEmpty(powerOrgList)) {
            return returnEmptyList(statisticDTO);
        }

        if ("1".equals(statisticDTO.getSelectLogo()) && CollUtil.isNotEmpty(statisticDTO.getSelectOrganization())) {
            List<String> allOrganize = cultivatePerUtils.batchAllOrganize(statisticDTO.getSelectOrganization());
            allOrganize.addAll(statisticDTO.getSelectOrganization());
            List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, allOrganize);
            if (CollUtil.isEmpty(intersection)) {
                returnEmptyList(statisticDTO);
            }
            orgIds = intersection;
        } else if (CollUtil.isNotEmpty(statisticDTO.getSelectOrganization())) {
            List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, statisticDTO.getSelectOrganization());
            if (CollUtil.isEmpty(intersection)) {
                returnEmptyList(statisticDTO);
            }
            orgIds = intersection;
        } else if (CollUtil.isEmpty(statisticDTO.getSelectOrganization())) {
            orgIds = powerOrgList;
        }
        Map<String, OrganizeGeneralDetailVO> orgMap = userApiV2Util.organizesByOrganizeIdsReturenMap(orgIds, null);
        //查询学习地图
        List<FtbCultivateMapSimpleDto> mapLists = baseMapper.queryStudyMapList(statisticDTO);
        if (CollUtil.isEmpty(mapLists)) {
            return returnEmptyList(statisticDTO);
        }
        List<String> queryPromotionIds = mapLists.stream().map(FtbCultivateMapSimpleDto::getPromotionId).collect(Collectors.toList());
        List<FtbCultivateMapStudyUserDto> studyUserDtoList = baseMapper.queryStudyUser(statisticDTO, queryPromotionIds);
        if (CollUtil.isEmpty(studyUserDtoList)) {
            return returnEmptyList(statisticDTO);
        }
//        List<FtbCultivatePromotionLevelMapVO> mapPostNum = baseMapper.queryMapPostNum(queryPromotionIds);
        Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatch(studyUserDtoList.stream().map(FtbCultivateMapStudyUserDto::getUserId).collect(Collectors.toList()), null);
        List<FtbCultivateMapsOrgWisdomStatisticVO> ret = buildReturnList(orgMap, mapLists, studyUserDtoList, userMap);
        if (CollUtil.isEmpty(ret)) {
            return returnEmptyList(statisticDTO);
        }
//        statisticDTO.setSelectOrganization(orgIds);
//        page = baseMapper.organizationListStatistics(statisticDTO, page);
//        List<FtbCultivateMapsOrgWisdomStatisticVO> records = page.getRecords();
//        records.forEach(item -> {
//            String id = item.getId();
//            FtbCultivatePromotionLevelMapVO learnMapLevels = promotionNewService.getLearnMapLevelsWithMapId(id);
//            ActionResult<Long> userCount = userApi.getUserCount(item.getEnableOrgId(), item.getIniPostId());
//            if (ObjectUtil.isNotEmpty(userCount)) {
//                Long data = userCount.getData();
//                item.setCurrentNum(data);
//            }
//            item.setNumberOfMapPositions(learnMapLevels.getLearningScope());
//            item.setMapLevel(learnMapLevels);
//            OrganizeGeneralDetailVO organizeGeneralDetailVO = orgMap.get(item.getEnableOrgId());
//            if (organizeGeneralDetailVO != null) {
//                item.setEnableOrgName(organizeGeneralDetailVO.getName());
//            }
//        });
//        return CultivatePage.coverPageList(page);
        PageListVO<FtbCultivateMapsOrgWisdomStatisticVO> pageInfo = new PageListVO<>();
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(statisticDTO.getCurrentPage());
        pagination.setPageSize(statisticDTO.getPageSize());
        pagination.setTotal(ret.size());
        pageInfo.setPagination(pagination);

        List<List<FtbCultivateMapsOrgWisdomStatisticVO>> batchList = UserApiV2Util.batchList(ret, (int) statisticDTO.getPageSize());
        if (statisticDTO.getCurrentPage() <= batchList.size()) {
            pageInfo.setList(batchList.get((int) statisticDTO.getCurrentPage() - 1));
        } else {
            pageInfo.setList(new ArrayList<>());
        }

        return pageInfo;
    }

    /**
     * 构建学习地图组织维度统计列表
     *
     * @param orgMap           组织信息映射，key为组织ID，value为组织详情
     * @param mapLists         学习地图列表
     * @param studyUserDtoList 学习用户列表
     * @param userMap          用户信息映射，key为用户ID，value为用户详情
     * @return 学习地图组织维度统计列表
     */
    private List<FtbCultivateMapsOrgWisdomStatisticVO> buildReturnList(Map<String, OrganizeGeneralDetailVO> orgMap, List<FtbCultivateMapSimpleDto> mapLists,
                                                                       List<FtbCultivateMapStudyUserDto> studyUserDtoList, Map<String, UserBoundVO> userMap) {
        List<FtbCultivateMapsOrgWisdomStatisticVO> ret = new ArrayList<>();
        //按照学习地图id分组
        Map<String, List<FtbCultivateMapStudyUserDto>> mapProUserListMap = studyUserDtoList.stream().collect(Collectors.groupingBy(FtbCultivateMapStudyUserDto::getPromotionId));
        Map<String, PositionVO> stringPositionVOMap = userApiV2Util.listPositionDetailInfoByIdsReturnMap(mapLists.stream().map(FtbCultivateMapSimpleDto::getPostId).collect(Collectors.toList()), null);
        for (FtbCultivateMapSimpleDto mapList : mapLists) {
            List<FtbCultivateMapStudyUserDto> studyList = mapProUserListMap.get(mapList.getPromotionId());
            if (CollUtil.isEmpty(studyList)) {
                continue;
            }
            List<UserBoundVO> tempUser = new ArrayList<>();
            for (FtbCultivateMapStudyUserDto ftbCultivateMapStudyUserDto : studyList) {
                UserBoundVO userBoundVO = userMap.get(ftbCultivateMapStudyUserDto.getUserId());
                if (userBoundVO != null) {
                    tempUser.add(userBoundVO);
                }
            }
            if (CollUtil.isEmpty(tempUser)) {
                continue;
            }
            FtbCultivatePromotionLevelMapVO learnMapLevels = promotionNewService.getLearnMapLevelsWithMapId(mapList.getPromotionId());
            //按照组织分组
            Map<String, List<UserBoundVO>> orgUserMap = tempUser.stream().collect(Collectors.groupingBy(UserBoundVO::getOrganizeId));
            for (Map.Entry<String, List<UserBoundVO>> stringListEntry : orgUserMap.entrySet()) {
                String orgId = stringListEntry.getKey();
                OrganizeGeneralDetailVO organizeGeneralDetailVO = orgMap.get(orgId);
                if (organizeGeneralDetailVO == null) {
                    continue;
                }
                List<UserBoundVO> value = stringListEntry.getValue();
                FtbCultivateMapsOrgWisdomStatisticVO vo = new FtbCultivateMapsOrgWisdomStatisticVO();
                vo.setMapName(mapList.getPromotionName());
                vo.setMapID(mapList.getPromotionBusinessId());
                vo.setCreationTime(mapList.getCreatorTime());
                vo.setEnableOrgId(orgId);
                vo.setEnableOrgName(organizeGeneralDetailVO.getName());
                PositionVO positionVO = stringPositionVOMap.get(mapList.getPostId());
                if (positionVO != null) {
                    vo.setIniPosition(positionVO.getFullName());
                }
                vo.setNumberOfEmplo(value.size() + "");

                vo.setId(mapList.getPromotionId());
                vo.setIniPostId(mapList.getPostId());
                vo.setNumberOfMapPositions(learnMapLevels.getLearningScope());
                vo.setMapLevel(learnMapLevels);
                List<UserRelationBaseVO> userListForOrgIdAndPositionId = userApiV2Util.getUserListForOrgIdAndPositionId(orgId, mapList.getPostId(), null);
                if (CollUtil.isNotEmpty(userListForOrgIdAndPositionId)) {
                    vo.setCurrentNum(Long.valueOf(userListForOrgIdAndPositionId.size()));
                }
                ret.add(vo);
            }

        }
        return ret;
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateMapsPersonWisdomStatisticVO> returnEmptyList(FtbMapsPersonWisdomStatisticDTO statisticDTO) {
        PageListVO<FtbCultivateMapsPersonWisdomStatisticVO> pageInfo = new PageListVO<>();
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(statisticDTO.getCurrentPage());
        pagination.setPageSize(statisticDTO.getPageSize());
        pagination.setTotal(0);
        pageInfo.setList(new ArrayList<>());
        pageInfo.setPagination(pagination);
        return pageInfo;
    }

    @Override
    public PageListVO<FtbCultivateMapsPersonWisdomStatisticVO> personListStatistics(FtbMapsPersonWisdomStatisticDTO personWisdomStatisticDTO) {
        Page<FtbCultivateMapsPersonWisdomStatisticVO> page = personWisdomStatisticDTO.coverCultivatePage();
        if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getSelectOrganization())) {
            List<UserPageListVO> userListForOrgIds = userApiV2Util.getUserListForOrgIds(personWisdomStatisticDTO.getSelectOrganization(), null);
            if (CollUtil.isEmpty(userListForOrgIds)) {
                return returnEmptyList(personWisdomStatisticDTO);
            }
            if (CollUtil.isEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                personWisdomStatisticDTO.setSelectPeoples(userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList()));
            } else {
                List<String> intersection = UserApiV2Util.getIntersection(personWisdomStatisticDTO.getSelectPeoples(), userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList()));
                if (CollUtil.isEmpty(intersection)) {
                    return returnEmptyList(personWisdomStatisticDTO);
                }
                personWisdomStatisticDTO.setSelectPeoples(intersection);
            }
        }
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode() == 1) {
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                List<String> intersection = UserApiV2Util.getIntersection(innerPowerUserVO.getUserIds(), personWisdomStatisticDTO.getSelectPeoples());
                if (CollUtil.isNotEmpty(intersection)) {
                    personWisdomStatisticDTO.setSelectPeoples(intersection);
                } else {
                    return returnEmptyList(personWisdomStatisticDTO);
                }
            } else {
                personWisdomStatisticDTO.setSelectPeoples(innerPowerUserVO.getUserIds());
            }
        } else if (innerPowerUserVO.getCode() == 2) {
            return returnEmptyList(personWisdomStatisticDTO);
        }


        page = baseMapper.personListStatistics(personWisdomStatisticDTO, page);
        List<FtbCultivateMapsPersonWisdomStatisticVO> records = page.getRecords();
        List<String> employeeIdList = page.getRecords().stream().map(FtbCultivateMapsPersonWisdomStatisticVO::getEmployeeID).collect(Collectors.toList());
        // 获取转换id
        Map<String, String> perMap = cultivatePerUtils.coverPersonalIds(employeeIdList);

        if (CollUtil.isNotEmpty(records)) {
            Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(records.stream().map(FtbCultivateMapsPersonWisdomStatisticVO::getEmployeeID).collect(Collectors.toList()), null);
            for (FtbCultivateMapsPersonWisdomStatisticVO item : records) {
                UserBoundVO userBoundVO = userPrimaryBoundBatch.get(item.getEmployeeID());
                if(userBoundVO!=null){
                    item.setFullName(userBoundVO.getUserName());
                    item.setOrganization(userBoundVO.getOrganizeName());
                    String employeeSCurrentPosition = "";
                    if(StringUtil.isNotEmpty(userBoundVO.getPositionName())){
                        employeeSCurrentPosition = userBoundVO.getPositionName();
                    }
                    if(StringUtil.isNotEmpty(userBoundVO.getGradeName())){
                        employeeSCurrentPosition =employeeSCurrentPosition+"_"+userBoundVO.getGradeName();
                    }
                    item.setEmployeeSCurrentPosition(employeeSCurrentPosition);
                }
                String promotionId = item.getPromotionId();
                FtbCultivatePromotionLevelMapVO learnMapLevels = promotionNewService.getLearnMapLevelsWithMapId(promotionId);
                // 学习岗位数
                item.setNumberOfMapPositions(learnMapLevels.getLearningScope());
                item.setMapLevel(learnMapLevels);
                String employeeID = item.getEmployeeID();
                item.setSysEmployeeID(perMap.get(employeeID));
                //  查询用户已学习岗位信息
                List<Integer> relist = new ArrayList<>();
                relist.add(1);
                relist.add(2);
                String hasStudyPostIds = ftbCultivatePromotionNewMapper.queryThePositionsThatUsersHaveLearned(employeeID, relist);
                if (StringUtils.isNotEmpty(hasStudyPostIds)) {
                    List<String> hasStudyPostIdsList = Arrays.stream(hasStudyPostIds.split(",")).distinct().collect(Collectors.toList());
                    List<String> postIds = ftbCultivatePromotionNewMapper.queryChosePostId(employeeID, promotionId);
                    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());
                        item.setPositionLearned(stringListNames.stream().collect(Collectors.joining(",")));
                    }
                }
            }
        }
        return CultivatePage.coverPageList(page);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePromotion(FtbCultivatePromotionCreatDto creatDto) {
        FtbCultivatePromotion cultivatePromotion = FtbCultivatePromotionCreatDto.
                coverFtbCultivatePromotionCreatDto(creatDto);
        //新增对应的岗位级别
        List<FtbCultivatePromotionPostVO> postVOList = creatDto.getPostChannelLevel();
        Set<String> postIds = postVOList.stream().map(FtbCultivatePromotionPostVO::getPostId).collect(Collectors.toSet());
        if (postIds.size() != postVOList.size()) {
            throw new RuntimeException("职位列表中存在重复的岗位，请重新检查!");
        }
        promotionMapper.updateById(cultivatePromotion);
        LambdaUpdateWrapper<FtbCultivatePromotionPost> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(FtbCultivatePromotionPost::getPromotionId, cultivatePromotion.getId());
        // 修改重构数据
        postService.remove(wrapper);
        // 添加通道岗位
        savePromotion(postVOList, cultivatePromotion.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(String id, boolean flag) {

        // 判断结果1：是-二次确认提示：请谨慎删除，
        // 该通道的初始岗位在岗位学习进行了学习配置，
        // 删除该通道会导致APP端应用了该通道的用户重新选择晋升通道，目前共有X位用户应用了该通道。
        // 确定删除后在APP端将触发重新选择晋升通道
        if (!flag) { //一次删除
            FtbCultivatePromotionDto dto = new FtbCultivatePromotionDto();
            dto.setPromotionId(id);
            PageListVO<FtbCultivatePromotionMemberVO> list = getPromotionMbeList(dto, new CultivatePage());
            // 查询是否存在关联数据
            if (!list.getList().isEmpty()) {
                return false;
            }
        }
        // 二次确认删除
        return deleteByPromotionId(id);
    }

    /**
     * 删除晋升通道
     *
     * @param id
     * @return
     */
    public boolean deleteByPromotionId(String id) {
        LambdaUpdateWrapper<FtbCultivatePromotion> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(FtbCultivatePromotion::getEnableMark, "1");
        updateWrapper.eq(BaseEntity::getId, id);
        // 判断结果2：否-二次确认提示：您确认要删除该通道吗？点击确认后删除
        // 软删除
        promotionMapper.update(new FtbCultivatePromotion(), updateWrapper);
        LambdaUpdateWrapper<FtbCultivatePromotionPost> wrapper = Wrappers.lambdaUpdate();
        // 移除晋升通道岗位信息
        wrapper.eq(FtbCultivatePromotionPost::getPromotionId, id);
        postService.remove(wrapper);
        // 移除关联数据
        LambdaUpdateWrapper<FtbCultivatePromotionMember> memberLambdaUpdateWrapper = Wrappers.lambdaUpdate();
        memberLambdaUpdateWrapper.eq(FtbCultivatePromotionMember::getPromotionId, id);
        promotionMemberService.remove(memberLambdaUpdateWrapper);
        return true;
    }

    @Override
    public PageListVO<FtbCultivatePromotionMemberVO> getPromotionMbeList(FtbCultivatePromotionDto dto, CultivatePage objectPage) {
        Page<FtbCultivatePromotionMemberVO> page = objectPage.coverCultivatePage();
        page = promotionMapper.getPromotionMbeList(dto, page);
        List<FtbCultivatePromotionMemberVO> mbeListRecords = page.getRecords();
        // 获取当前传入用户绑定信息
        mbeListRecords.forEach(vo -> {
            vo.setPoAndGradesName(vo.getPositionName() + "(" + vo.getPositionGradesName() + ");");
        });
        return CultivatePage.coverPageList(page);
    }

}
