package jnpf.cultivate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.authority.service.FtbPermissionOrganizeService;
import jnpf.base.Pagination;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.mapper.FtbCultivateCertificateMapper;
import jnpf.cultivate.service.FtbCultivateCertificateService;
import jnpf.cultivate.service.FtbCultivateCertificateUserService;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.certificate.FtbCertificateOrgWisdomStatisticDTO;
import jnpf.model.cultivate.dto.certificate.FtbCertificatePersonWisdomStatisticDTO;
import jnpf.model.cultivate.po.certificate.CertificateUserPagination;
import jnpf.model.cultivate.po.certificate.FtbCertificateEntity;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.cultivate.v2.common.vo.V2BaseIdNameVo;
import jnpf.model.cultivate.vo.certificate.*;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.cultivate.vo.position.FtbCultivatePositionPersonStatisticesVO;
import jnpf.model.enums.CourseEnums;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.personnels.mapper.FtbPersonnelsStaffRosterMapper;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 证书模版表
 *
 * @author penghao
 */
@Service
public class FtbCultivateCertificateServiceImpl extends ServiceImpl<FtbCultivateCertificateMapper, FtbCertificateEntity> implements FtbCultivateCertificateService {

    private static final List<String> EMPTY_LIST = List.of("-1");
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private FtbCultivateCertificateUserService certificateUserService;

    @Autowired
    CultivatePerUtils cultivatePerUtils;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbPersonnelsStaffRosterMapper rosterMapper;

    @Autowired
    private FtbPermissionOrganizeService ftbPermissionOrganizeService;

    @Override
    public List<FtbCertificateEntity> getList(Pagination pagination) {
        //通过UserProvider获取用户信息
        QueryWrapper<FtbCertificateEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().and(
                    t -> t.like(FtbCertificateEntity::getName, pagination.getKeyword())
            );
        }
        queryWrapper.lambda().eq(FtbCertificateEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
        //排序
        queryWrapper.orderByDesc("F_LASTMODIFYTIME");
        Page<FtbCertificateEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<FtbCertificateEntity> userIPage = this.page(page, queryWrapper);
        return pagination.setData(userIPage.getRecords(), page.getTotal());
    }

    @Override
    public FtbCertificateEntity getInfo(String id) {
        QueryWrapper<FtbCertificateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FtbCertificateEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    @DSTransactional
    public void create(FtbCertificateEntity entity) {
        LambdaQueryWrapper<FtbCertificateEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.and(
                wp -> wp.eq(FtbCertificateEntity::getName, entity.getName())
        );
        wrapper.eq(FtbCertificateEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
        wrapper.last("limit 1");
        FtbCertificateEntity ftbCertificateEntity = baseMapper.selectOne(wrapper);
        if (ftbCertificateEntity != null && ftbCertificateEntity.getName().equals(entity.getName())) {
            throw new RuntimeException("证书名称已存在请勿重复添加!");
        }
        UserInfo userInfo = userProvider.get();
        entity.setId(IdWorker.getIdStr());
        entity.setCreatorUserId(userInfo.getUserId());
        entity.setTenantId(userInfo.getTenantId());
        entity.setLastModifyTime(new Date());
        entity.setStatus(CourseEnums.CertStatus.UP.getCode());
        entity.setEnabledMark(CourseEnums.EnabledMarkType.VALID.getCode());
        fill(entity);
        this.save(entity);
    }

    private void fill(FtbCertificateEntity entity) {
//        List<OrganizeEntity> organizeEntityList = organizeApi.getOrganizeId(userProvider.get().getOrganizeId());
        OrganizeGeneralDetailVO organizeGeneralDetailVO = userApiV2Util.organizeInfoById(userProvider.get().getOrganizeId(), null);
        if (organizeGeneralDetailVO != null) {
            entity.setCompanyName(organizeGeneralDetailVO.getOrganizeTreeName());
        }
    }


    @Transactional
    @Override
    public String updateEntity(String id, FtbCertificateEntity entity) {
        entity.setId(id);
        String string = repeatTheCheck(entity);
        if (!StringUtils.isEmpty(string)) {
            return string;
        }
        UserInfo userInfo = userProvider.get();
        entity.setId(id);
        entity.setLastModifyUserId(userInfo.getUserId());
        FtbCertificateEntity info = this.getInfo(id);
        if (!info.getName().equals(entity.getName())) {
            //更新用户证书名称
            certificateUserService.update(new FtbCertificateUserEntity().setCertificateName(entity.getName())
                    , new LambdaQueryWrapper<FtbCertificateUserEntity>().eq(FtbCertificateUserEntity::getCertificateId, id));
        }
        fill(entity);
        this.updateById(entity);
        return null;
    }

    /**
     * 重复校验
     *
     * @param entity
     */
    private String repeatTheCheck(FtbCertificateEntity entity) {
        LambdaQueryWrapper<FtbCertificateEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.and(
                wp -> wp.eq(FtbCertificateEntity::getName, entity.getName())
        );
        wrapper.eq(FtbCertificateEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
        wrapper.last("limit 1");
        FtbCertificateEntity ftbCertificateEntity = baseMapper.selectOne(wrapper);
        // 同时进行修改
        if (ObjectUtil.isEmpty(ftbCertificateEntity)) {
            return null;
        }
        // 修改状态
        if (entity.getId().equals(ftbCertificateEntity.getId()) &&
                !entity.getStatus().equals(ftbCertificateEntity.getStatus())) {
            return null;
        }
        // 判断是不是
        if (entity.getId().equals(ftbCertificateEntity.getId()) &&
                (entity.getName().equals(ftbCertificateEntity.getName()))
        ) {
            return null;
        }
        String tishi = "";
        boolean nameFlag = false;
        // 其他的用户想要修改为当前的名称
        if (!ftbCertificateEntity.getName().equals(entity.getName())) {
            nameFlag = true;
        } else if (ftbCertificateEntity.getName().equals(entity.getName()) && !ftbCertificateEntity.getId().equals(entity.getId())) {
            return null;
        } else {
            tishi += "该证书名称已存在!";
        }
        if (nameFlag) {
            tishi = null;
        }
        return tishi;
    }

    @Override
    public void delete(FtbCertificateEntity entity) {
        if (entity != null) {
            UserInfo userInfo = userProvider.get();
            FtbCertificateUserEntity userEntity = new FtbCertificateUserEntity();
            userEntity.setEnabledMark(CourseEnums.EnabledMarkType.INVALID.getCode());
            userEntity.setDeleteUserId(userInfo.getUserId());
            userEntity.setDeleteTime(new Date());
            certificateUserService.update(userEntity, new LambdaQueryWrapper<FtbCertificateUserEntity>().eq(FtbCertificateUserEntity::getCertificateId, entity.getId()));
            entity.setEnabledMark(CourseEnums.EnabledMarkType.INVALID.getCode());
            entity.setDeleteUserId(userInfo.getUserId());
            entity.setDeleteTime(new Date());
            this.updateById(entity);
        }
    }

    @Override
    public void deleteCertificate(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("主键不能为空!");
        }
        CertificateUserPagination pagination = new CertificateUserPagination();
        pagination.setCertificateId(id);
        List<FtbCertificateUserEntity> list = certificateUserService.getList(pagination);
        if (CollUtil.isNotEmpty(list)) {
            List<FtbCertificateUserEntity> collect =
                    list.stream().filter(item -> 0 == item.getStatus()).collect(Collectors.toList());
            // 查询所有未过期的数据
            if (CollUtil.isNotEmpty(collect)) {
                throw new RuntimeException("抱歉！删除失败，已颁发证书存在生效中的状态，请吊销后再进行删除！");
            }
        }
        baseMapper.deleteById(id);
    }

    @Override
    public PageListVO<FtbCertificateListVO> queryCertificateListByNotChoose(String keyWords, CultivatePage page) {
        LambdaQueryWrapper<FtbCertificateEntity> lambdaQuery = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(keyWords)) lambdaQuery.like(FtbCertificateEntity::getName, keyWords);
        lambdaQuery.eq(FtbCertificateEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
        lambdaQuery.eq(FtbCertificateEntity::getStatus, 1);
        lambdaQuery.orderByDesc(FtbCertificateEntity::getLastModifyTime);
        List<FtbCertificateEntity> entity = baseMapper.selectList(lambdaQuery);
//        // 查询岗位学习已经绑定的证书
//        LambdaQueryWrapper<FtbCultivatePositionCertificate> lambdaed = Wrappers.lambdaQuery();
//        lambdaed.eq(FtbCultivatePositionCertificate::getEnableMark,0);
//        List<FtbCultivatePositionCertificate> positionCertificates = cultivatePositionCertificateMapper.selectList(lambdaed);
//        List<String> certificateIds = positionCertificates.stream().map(FtbCultivatePositionCertificate::getCertificateId).collect(Collectors.toList());
//        entity= entity.stream().filter(item -> !certificateIds.contains(item.getId())).collect(Collectors.toList());
        List<FtbCertificateListVO> certificateListVOS = entity.stream().map(FtbCertificateListVO::covertVO).collect(Collectors.toList());
        //补充创建人
        if (CollUtil.isNotEmpty(certificateListVOS)) {
            fillCreateUserName(certificateListVOS);
        }
        Page<FtbCertificateListVO> cultivatePage = page.coverCultivatePage();
        return CultivatePage.paginate(certificateListVOS, cultivatePage);
    }

    @Override
    public List<V2BaseIdNameVo> getOption() {
        List<FtbCertificateEntity> list = this.list(new LambdaQueryWrapper<FtbCertificateEntity>()
                .eq(FtbCertificateEntity::getStatus, CourseEnums.CourseGroundingType.UP.getCode())
                .orderByDesc(FtbCertificateEntity::getCreatorTime));
        return BeanUtil.copyToList(list, V2BaseIdNameVo.class);
    }

    /**
     * 补充创建人姓名
     *
     * @param list
     * @return
     */
    public void fillCreateUserName(List<FtbCertificateListVO> list) {
        Set<String> userIds = new HashSet<>();
        for (FtbCertificateListVO ftbCertificateListVO : list) {
            if (StringUtils.isNotEmpty(ftbCertificateListVO.getCreatorUserId())) {
                userIds.add(ftbCertificateListVO.getCreatorUserId());
            }
        }
        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        //查询用户的姓名信息
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = new LambdaQueryWrapper<FtbPersonnelsStaffRoster>()
                .select(FtbPersonnelsStaffRoster::getId, FtbPersonnelsStaffRoster::getUserId, FtbPersonnelsStaffRoster::getName)
                .in(FtbPersonnelsStaffRoster::getUserId, userIds)
                .eq(FtbPersonnelsStaffRoster::getEnabledMark, 0);
        List<FtbPersonnelsStaffRoster> rosterList = rosterMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(rosterList)) {
            return;
        }


        Map<String, FtbPersonnelsStaffRoster> map = new HashMap<>();
        for (FtbPersonnelsStaffRoster roster : rosterList) {
            map.put(roster.getUserId(), roster);
        }
        for (FtbCertificateListVO ftbCertificateListVO : list) {
            if (StringUtils.isNotEmpty(ftbCertificateListVO.getCreatorUserId())) {
                FtbPersonnelsStaffRoster roster = map.get(ftbCertificateListVO.getCreatorUserId());
                if (roster != null) {
                    ftbCertificateListVO.setCreatorUserName(roster.getName());
                }
            }
        }
    }

    @Override
    public PageListVO<FtbCertificateOrgWisdomStatisticVO> organizationListStatistics(FtbCertificateOrgWisdomStatisticDTO statisticDTO) {
        if (statisticDTO.getPageSize() <= 0) {
            statisticDTO.setPageSize(20L);
        }
        if (statisticDTO.getCurrentPage() <= 0) {
            statisticDTO.setCurrentPage(1L);
        }

        List<String> powerOrgList = userApiV2Util.queryPowerOrgList();
        if (CollUtil.isEmpty(powerOrgList)) {
            return returnEmptyList(statisticDTO);
        }
        List<String> selectoAllorgIds = powerOrgList;


        if ("1".equals(statisticDTO.getSelectLogo()) && CollUtil.isNotEmpty(statisticDTO.getOrgId())) {
            List<String> allOrg = new ArrayList<>();
            for (String orgId : statisticDTO.getOrgId()) {
                List<String> allOrganize = cultivatePerUtils.getAllOrganize(orgId);
                if (CollUtil.isNotEmpty(allOrganize)) {
                    allOrg.addAll(allOrganize);
                }
            }
            List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, allOrg);
            if (CollUtil.isNotEmpty(intersection)) {
                selectoAllorgIds = intersection;
            } else {
                return returnEmptyList(statisticDTO);
            }
        } else {
            if (CollUtil.isNotEmpty(statisticDTO.getOrgId())) {
                List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, statisticDTO.getOrgId());
                if (CollUtil.isNotEmpty(intersection)) {
                    selectoAllorgIds = intersection;
                } else {
                    return returnEmptyList(statisticDTO);
                }
            }
        }

        // 默认情况
        // 手动输入
        String dtoOrgIds = statisticDTO.getOrgIds();
        if (StringUtils.isNotEmpty(dtoOrgIds)) {
            List<String> organizationalIdCollection = cultivatePerUtils.convertOrganizationalIdCollection(dtoOrgIds);
            if (CollUtil.isNotEmpty(organizationalIdCollection)) {
                List<String> intersection = UserApiV2Util.getIntersection(selectoAllorgIds, organizationalIdCollection);
                if (CollUtil.isNotEmpty(intersection)) {
                    selectoAllorgIds = intersection;
                } else {
                    return returnEmptyList(statisticDTO);
                }
            } else {
                return returnEmptyList(statisticDTO);
            }
        }
        List<OrganizeGeneralDetailVO> organizeGeneralDetailVOS = userApiV2Util.organizesByOrganizeIds(selectoAllorgIds, null);
        if (CollUtil.isEmpty(organizeGeneralDetailVOS)) {
            return returnEmptyList(statisticDTO);
        }

        List<FtbCertificateQueryStatisticAllVO> userCertList = baseMapper.organizationListStatisticsAll(statisticDTO);
        if (CollUtil.isEmpty(userCertList)) {
            return returnEmptyList(statisticDTO);
        }
        List<String> allUserIds = new ArrayList<>();
        Map<String, FtbCertificateInfoVO> allUserCertMap = new HashMap<>(); //证书id 到证书
        List<FtbCertificateInfoVO> allUserCertList = new ArrayList<>();
        Map<String, List<String>> certToUserMap = new HashMap<>(); //证书 的人员列表
        Map<String, OrganizeGeneralDetailVO> orgMap = organizeGeneralDetailVOS.stream().collect(Collectors.toMap(OrganizeGeneralDetailVO::getId, item -> item));


        for (FtbCertificateQueryStatisticAllVO ftbCertificateQueryStatisticAllVO : userCertList) {
            allUserIds.add(ftbCertificateQueryStatisticAllVO.getUserId());
            FtbCertificateInfoVO ftbCertificateInfoVO = allUserCertMap.get(ftbCertificateQueryStatisticAllVO.getId());
            if (ftbCertificateInfoVO == null) {
                ftbCertificateInfoVO = new FtbCertificateInfoVO();
                ftbCertificateInfoVO.setId(ftbCertificateQueryStatisticAllVO.getId());
                ftbCertificateInfoVO.setName(ftbCertificateQueryStatisticAllVO.getCertificateName());
                ftbCertificateInfoVO.setStatus(ftbCertificateQueryStatisticAllVO.getOnShelfStatus());
                allUserCertMap.put(ftbCertificateInfoVO.getId(), ftbCertificateInfoVO);
            }

            List<String> userBoundVOS = certToUserMap.get(ftbCertificateQueryStatisticAllVO.getId());
            if (userBoundVOS == null) {
                userBoundVOS = new ArrayList<>();
            }
            userBoundVOS.add(ftbCertificateQueryStatisticAllVO.getUserId());
            certToUserMap.put(ftbCertificateQueryStatisticAllVO.getId(), userBoundVOS);


        }
        if (allUserCertMap.size() > 0) {
            allUserCertList = allUserCertMap.values().stream().collect(Collectors.toList());
        }


        Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(allUserIds, null);

        List<FtbCertificateOrgWisdomStatisticVO> ret = buildReturnData(allUserCertList, certToUserMap, userPrimaryBoundBatch, orgMap);
        return UserApiV2Util.buildPage(ret, statisticDTO.getPageSize(), statisticDTO.getCurrentPage());
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCertificateOrgWisdomStatisticVO> returnEmptyList(FtbCertificateOrgWisdomStatisticDTO statisticDTO) {
        PageListVO<FtbCertificateOrgWisdomStatisticVO> 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;
    }

    private List<FtbCertificateOrgWisdomStatisticVO> buildReturnData(List<FtbCertificateInfoVO> allUserCertList, Map<String, List<String>> certToUserMap, Map<String, UserBoundVO> userBoundVOMap, Map<String, OrganizeGeneralDetailVO> orgMap) {
        List<FtbCertificateOrgWisdomStatisticVO> ret = new ArrayList<>();
        for (FtbCertificateInfoVO certificateInfoVO : allUserCertList) {
            List<String> currUserIds = certToUserMap.get(certificateInfoVO.getId());
            List<UserBoundVO> currUserBoundVOList = new ArrayList<>();
            currUserIds.forEach(userId -> {
                UserBoundVO userBoundVOS = userBoundVOMap.get(userId);
                if (userBoundVOS != null) {
                    currUserBoundVOList.add(userBoundVOS);
                }
            });
            if (CollUtil.isEmpty(currUserBoundVOList)) {
                continue;
            }
            //按照组织分组
            Map<String, List<UserBoundVO>> orgUserMap = currUserBoundVOList.stream().collect(Collectors.groupingBy(UserBoundVO::getOrganizeId));
            for (Map.Entry<String, List<UserBoundVO>> stringListEntry : orgUserMap.entrySet()) {
                String orgId = stringListEntry.getKey();
                List<UserBoundVO> value = stringListEntry.getValue();
                OrganizeGeneralDetailVO organizeGeneralDetailVO = orgMap.get(orgId);
                if (organizeGeneralDetailVO == null) {
                    continue;
                }
                FtbCertificateOrgWisdomStatisticVO vo = new FtbCertificateOrgWisdomStatisticVO();
                vo.setCertificateId(certificateInfoVO.getId());
                vo.setCertificateName(certificateInfoVO.getName());
                vo.setOnShelfStatus(String.valueOf(certificateInfoVO.getStatus()));
                vo.setOrgID(organizeGeneralDetailVO.getId());
                vo.setOrgName(organizeGeneralDetailVO.getOrganizeTreeName());
                vo.setNumberOfPeopleIssued(value.size());
                vo.setSysOrgID(organizeGeneralDetailVO.getEnCode());
                ret.add(vo);
            }
        }
        return ret;
    }

    @Override
    public PageListVO<FtbCertificatePersonWisdomStatisticVO> personalDimensionStatistics(FtbCertificatePersonWisdomStatisticDTO personWisdomStatisticDTO) {
        Page<FtbCertificatePersonWisdomStatisticVO> page = personWisdomStatisticDTO.coverCultivatePage();
        if (StringUtils.isNotEmpty(personWisdomStatisticDTO.getEmployeeIds())) {
            List<String> strings = cultivatePerUtils.convertEmployeeIdCollection(personWisdomStatisticDTO.getEmployeeIds());
            if (CollUtil.isEmpty(strings)) {
                return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
            }
            personWisdomStatisticDTO.setRealUserIds(strings);
        }
        if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getRealUserIds())) {
                List<String> intersection = UserApiV2Util.getIntersection(personWisdomStatisticDTO.getRealUserIds(), personWisdomStatisticDTO.getSelectPeoples());
                if (CollUtil.isEmpty(intersection)) {
                    return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
                }
                personWisdomStatisticDTO.setRealUserIds(intersection);
            }
            personWisdomStatisticDTO.setRealUserIds(personWisdomStatisticDTO.getSelectPeoples());
        }
        if (StringUtils.isNotEmpty(personWisdomStatisticDTO.getKeyWords())) {
            List<UserPageListVO> userForNameOrPhone = userApiV2Util.getUserForNameOrPhone(personWisdomStatisticDTO.getKeyWords(), "", UserProvider.getUser().getTenantId());
            if (CollUtil.isEmpty(userForNameOrPhone)) {
                return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
            }
            List<String> nameUserIds = userForNameOrPhone.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getRealUserIds())) {
                List<String> intersection = UserApiV2Util.getIntersection(nameUserIds, personWisdomStatisticDTO.getRealUserIds());
                if (CollUtil.isEmpty(intersection)) {
                    return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
                }
                personWisdomStatisticDTO.setRealUserIds(nameUserIds);
            }
        }
        if (StringUtils.isNotEmpty(personWisdomStatisticDTO.getOrgID())) {
            List<UserPageListVO> userListForOrgIds = userApiV2Util.getUserListForOrgIds(List.of(personWisdomStatisticDTO.getOrgID()), null);
            if (CollectionUtil.isEmpty(userListForOrgIds)) {
                return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
            }
            List<String> orgUserIds = userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getRealUserIds())) {
                List<String> intersection = UserApiV2Util.getIntersection(orgUserIds, personWisdomStatisticDTO.getRealUserIds());
                if (CollUtil.isEmpty(intersection)) {
                    return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
                }
                personWisdomStatisticDTO.setRealUserIds(intersection);
            } else {
                personWisdomStatisticDTO.setRealUserIds(orgUserIds);
            }
        }
        List<String> searchPostId = new ArrayList<>();
        if (StringUtils.isNotEmpty(personWisdomStatisticDTO.getPostIds())) {
            searchPostId = cultivatePerUtils.convertPositionIdCollection(personWisdomStatisticDTO.getPostIds());
            if (CollUtil.isEmpty(searchPostId)) {
                return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
            }
        }
        if (StringUtils.isNotEmpty(personWisdomStatisticDTO.getPostId())) {
            searchPostId.add(personWisdomStatisticDTO.getPostId());
        }
        if (CollUtil.isNotEmpty(searchPostId)) {
            List<UserBoundVO> userListForPositions = userApiV2Util.getUserListForPositions(searchPostId, UserProvider.getUser().getTenantId());
            if (CollUtil.isEmpty(userListForPositions)) {
                return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
            }
            List<String> positionUserIds = userListForPositions.stream().map(UserBoundVO::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getRealUserIds())) {
                List<String> intersection = UserApiV2Util.getIntersection(positionUserIds, personWisdomStatisticDTO.getRealUserIds());
                if (CollUtil.isEmpty(intersection)) {
                    return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
                }
                personWisdomStatisticDTO.setRealUserIds(intersection);
            } else {
                personWisdomStatisticDTO.setRealUserIds(positionUserIds);
            }
        }
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode() == 1) {
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getRealUserIds())) {
                List<String> intersection = UserApiV2Util.getIntersection(personWisdomStatisticDTO.getRealUserIds(), innerPowerUserVO.getUserIds());
                if (CollUtil.isEmpty(intersection)) {
                    return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
                }
                personWisdomStatisticDTO.setRealUserIds(intersection);
            } else {
                personWisdomStatisticDTO.setRealUserIds(innerPowerUserVO.getUserIds());
            }
        } else if (innerPowerUserVO.getCode() == 2) {
            return UserApiV2Util.returnEmptyListGeneric(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize());
        }
        page = baseMapper.personalDimensionStatistics(personWisdomStatisticDTO, page);
//        List<String> orgCollect = page.getRecords().stream().map(FtbCertificatePersonWisdomStatisticVO::getOrgID).collect(Collectors.toList());
//        List<String> postCollect = page.getRecords().stream().map(FtbCertificatePersonWisdomStatisticVO::getSysPostId).collect(Collectors.toList());
        List<String> employeeIdList = page.getRecords().stream().map(FtbCertificatePersonWisdomStatisticVO::getEmployeeID).collect(Collectors.toList());
        // 获取转换id
//        Map<String, String> orgMap = cultivatePerUtils.convertOrganizationalId(orgCollect);
        Map<String, String> perMap = cultivatePerUtils.coverPersonalIds(employeeIdList);
//        Map<String, String> postMap = cultivatePerUtils.convertPostId(postCollect);
        // 岗位id转换
        Map<String, List<UserBoundVO>> userIdMap = userApiV2Util.getUserPrimaryBoundBatchCompatible(employeeIdList, null);
        page.getRecords().forEach(item -> {
            if (userIdMap != null && userIdMap.containsKey(item.getEmployeeID())) {
                List<UserBoundVO> userBoundMoreInfoVOS = userIdMap.get(item.getEmployeeID());
                List<FtbCultivatePositionPersonStatisticesVO.PositionInfo> positionInfos = userBoundMoreInfoVOS.stream().map(a -> {
                    FtbCultivatePositionPersonStatisticesVO.PositionInfo positionInfo = new FtbCultivatePositionPersonStatisticesVO.PositionInfo();
                    positionInfo.setPositionName(a.getPositionName());
                    positionInfo.setPositionGradesName(a.getGradeName());
                    return positionInfo;
                }).collect(Collectors.toList());
//                String string = positionInfos.stream().map(vo -> vo.getPositionName() + "_" + vo.getPositionGradesName()).collect(Collectors.joining(";"));
                String string = "";
                if (CollUtil.isNotEmpty(userBoundMoreInfoVOS)) {
                    UserBoundVO userBoundVO = userBoundMoreInfoVOS.get(0);
                    string = userBoundVO.getPositionName();
                    if (StringUtil.isNotEmpty(userBoundVO.getGradeName())) {
                        string = string + "_" + userBoundVO.getGradeName();
                    }
                    item.setOrganizationSystemDisplayId(userBoundVO.getOrganizeEnCode());
                    item.setOrgName(userBoundVO.getOrganizeTreeName());
                    item.setSysEmployeeID(perMap.get(item.getEmployeeID()));
                    item.setPostId(userBoundVO.getPositionEnCode());
                }
                item.setPositionLevel(string);

            }

//            OrganizeEntity infoById = organizeApi.getInfoById(item.getOrgID());
//            OrganizeGeneralDetailVO infoById = userApiV2Util.organizeInfoById(item.getOrgID(), null);
//            if (infoById != null) {
//                item.setOrgName(infoById.getOrganizeTreeName());
//            }
//            item.setSysEmployeeID(perMap.get(item.getEmployeeID()));

        });
        return CultivatePage.coverPageList(page);
    }
}
