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.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.mapper.CultivateIdentifyTableMapper;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskIdentificationMapper;
import jnpf.cultivate.service.*;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.CultivateIdentifyApplyTableBackups;
import jnpf.entity.cultivate.CultivateIdentifyItems;
import jnpf.entity.cultivate.CultivateIdentifyTable;
import jnpf.enums.cultivate.ApplyStatusEnum;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.identify.*;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskIdentification;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.cultivate.vo.identify.*;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.UserApi;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.position.PositionBaseInfoVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 实操鉴定表
 *
 * @author shitou
 * @email shitou@niujiekeji.com
 * @date 2023-12-19 11:10:53
 */
@Slf4j
@Service("cultivateIdentifyTableService")
public class CultivateIdentifyTableServiceImpl extends ServiceImpl<CultivateIdentifyTableMapper, CultivateIdentifyTable> implements CultivateIdentifyTableService {
    private static final List<String> EMPTY_USER_LIST = List.of("-1");

    @Autowired
    private UserApi userApi;
    @Autowired
    private UserApiV2Util userApiV2Util;
    @Autowired
    private CultivateIdentifyItemsService itemsService;
    @Autowired
    private CultivateIdentifyApplyService applyService;
    @Autowired
    private PositionCultivateIdentifyService cultivateIdentifyService;
    @Autowired
    private CultivateIdentifyApplyTableBackupsService applyTableBackupsService;
    @Autowired
    private CultivatePerUtils cultivatePerUtils;

    @Autowired
    private FtbCultivateLearnTaskIdentificationMapper ftbCultivateLearnTaskIdentificationMapper;

    @Autowired
    private FtbPersonnelsStaffRosterService ftbPersonnelsStaffRosterService;

    @Override
    public PageInfo<IdentifyTableListVo> getPageList(IdentifyTableListDto req) {
        PageHelper.startPage(Math.toIntExact(req.getCurrentPage()), Math.toIntExact(req.getPageSize()));
        return new PageInfo<>(this.baseMapper.getPageList(req));
    }

    @Override
    public IdentifyTableInfoVo getInfo(IdentifyTableInfoDto req) {
        CultivateIdentifyTable table = this.baseMapper.selectById(req.getId());
        ServiceException.notNull(table, "未查询到鉴定表记录");
        IdentifyTableInfoVo tableInfoVo = new IdentifyTableInfoVo();
        BeanUtils.copyProperties(table, tableInfoVo);
        tableInfoVo.setId(table.getId());
        tableInfoVo.setIdentifyItemList(this.itemsService.lambdaQuery()
                .eq(CultivateIdentifyItems::getTableId, table.getId())
                .eq(CultivateIdentifyItems::getDeleteMark, ConstantUtil.NUM_FALSE)
                .list().stream().map(items -> {
                    IdentifyItemsInfoVo infoVo = new IdentifyItemsInfoVo();
                    BeanUtils.copyProperties(items, infoVo);
                    infoVo.setId(items.getId());
                    return infoVo;
                }).collect(Collectors.toList()));
        return tableInfoVo;
    }

    @Override
    @DSTransactional
    public void saveData(IdentifyTableSaveDto req) {
        OptionalUtils.ifPresent(req.getName(), (name) -> {
            ServiceException.isTrue(this.lambdaQuery()
                    .eq(CultivateIdentifyTable::getName, name)
                    .eq(CultivateIdentifyTable::getDeleteMark, ConstantUtil.NUM_FALSE)
                    .count() <= 0, String.format("鉴定表%s已存在,请勿重复添加", name));
        });
        CultivateIdentifyTable tableSave = new CultivateIdentifyTable();
        tableSave.setId(RandomUtil.uuId());
        tableSave.setRuleId(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.IDENTIFY));
        BeanUtils.copyProperties(req, tableSave);
        tableSave.setCreatorTime(new Date());
        tableSave.setLastModifyTime(new Date());
        ServiceException.isTrue(CollectionUtil.isNotEmpty(req.getIdentifyItemList()), "未查询到鉴定表记录");
        //批量新增鉴定项
        List<CultivateIdentifyItems> batchSaveItemsList = req.getIdentifyItemList().stream().map(p -> {
            CultivateIdentifyItems identifyItems = new CultivateIdentifyItems();
            identifyItems.setId(RandomUtil.uuId());
            identifyItems.setTableId(tableSave.getId());
            BeanUtils.copyProperties(p, identifyItems);
            return identifyItems;
        }).collect(Collectors.toList());
        this.baseMapper.insert(tableSave);
        if (CollectionUtil.isNotEmpty(batchSaveItemsList)) {
            this.itemsService.saveBatch(batchSaveItemsList);
        }
    }

    @Override
    @DSTransactional
    public void updateData(IdentifyTableUpdateDto req) {
        CultivateIdentifyTable tableUpdate = this.baseMapper.selectById(req.getId());
        ServiceException.notNull(tableUpdate, "未查询到鉴定表记录");
        if (!tableUpdate.getName().equals(req.getName())) {
            OptionalUtils.ifPresent(req.getName(), (name) -> {
                ServiceException.isTrue(this.lambdaQuery()
                        .eq(CultivateIdentifyTable::getName, name)
                        .eq(CultivateIdentifyTable::getDeleteMark, ConstantUtil.NUM_FALSE)
                        .count() <= 0, String.format("鉴定表%s已存在,请勿重复添加", name));
            });
        }
        BeanUtils.copyProperties(req, tableUpdate);
        this.baseMapper.updateById(tableUpdate);
        //批量修改鉴定项
        List<CultivateIdentifyItems> batchUpdateItemsList = this.itemsService.lambdaQuery()
                .eq(CultivateIdentifyItems::getTableId, tableUpdate.getId())
                .eq(CultivateIdentifyItems::getDeleteMark, ConstantUtil.NUM_FALSE)
                .list();
        Map<String, IdentifyItemsUpdateVo> identifyItemsMap = req.getIdentifyItemList().stream().filter(m -> StringUtil.isNotEmpty(m.getId()))
                .collect(Collectors.toMap(IdentifyItemsUpdateVo::getId, a -> a, (k1, k2) -> k1));
        if (CollectionUtil.isNotEmpty(batchUpdateItemsList)) {
            batchUpdateItemsList.forEach(item -> {
                IdentifyItemsUpdateVo updateVo = identifyItemsMap.get(item.getId());
                if (Objects.isNull(updateVo)) {
                    item.setDeleteMark(ConstantUtil.NUM_TRUE);
                } else {
                    BeanUtils.copyProperties(updateVo, item);
                }
            });
            this.itemsService.updateBatchById(batchUpdateItemsList);
        }
        //处理新增鉴定项
        List<IdentifyItemsUpdateVo> addVoList = req.getIdentifyItemList().stream().filter(m -> StringUtil.isEmpty(m.getId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(addVoList)) {
            this.itemsService.saveBatch(addVoList.stream().map(item -> {
                CultivateIdentifyItems identifyItems = new CultivateIdentifyItems();
                identifyItems.setId(RandomUtil.uuId());
                BeanUtils.copyProperties(item, identifyItems);
                identifyItems.setTableId(tableUpdate.getId());
                return identifyItems;
            }).collect(Collectors.toList()));
        }
    }

    @Override
    @DSTransactional
    public IdentifyTableDeleteVo deleteData(IdentifyTableInfoDto req) {
        IdentifyTableDeleteVo tableDeleteVo = new IdentifyTableDeleteVo();
        CultivateIdentifyTable tableDelete = this.baseMapper.selectById(req.getId());
        // 任务必修课程是否全部学完
        ServiceException.notNull(tableDelete, "未查询到鉴定表记录");


        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> taskIdenWrapper = Wrappers.lambdaQuery();
        taskIdenWrapper.eq(FtbCultivateLearnTaskIdentification::getIdentificationId, req.getId());
        taskIdenWrapper.eq(FtbCultivateLearnTaskIdentification::getEnableMark, 0);
        Long taskIdentNum = ftbCultivateLearnTaskIdentificationMapper.selectCount(taskIdenWrapper);
        if (taskIdentNum > 0) {
            throw new RuntimeException("有培训任务配置了该鉴定表,不能删除");
        }
        List<CultivateIdentifyApplyTableBackups> applyTableBackupsList = this.applyTableBackupsService.lambdaQuery()
                .eq(CultivateIdentifyApplyTableBackups::getTableId, tableDelete.getId())
                .eq(CultivateIdentifyApplyTableBackups::getDeleteMark, ConstantUtil.NUM_FALSE).list();
        List<ManuallyInitiateVo> manuallyInitiateVoList = CollectionUtil.newArrayList();
        List<PostAndCourseVo> postAndCourseVoList = CollectionUtil.newArrayList();
        //判断手动发起的鉴定是否有未走完流程的数据
        if (CollectionUtil.isNotEmpty(applyTableBackupsList)) {
            List<String> tableIds = applyTableBackupsList.stream().map(CultivateIdentifyApplyTableBackups::getId).distinct().collect(Collectors.toList());
            List<CultivateIdentifyApply> applyList = this.applyService.lambdaQuery()
                    .in(CultivateIdentifyApply::getTableId, tableIds)
                    .eq(CultivateIdentifyApply::getDeleteMark, ConstantUtil.NUM_FALSE)
                    .eq(CultivateIdentifyApply::getIsVisible, 0)
                    .ne(CultivateIdentifyApply::getStatus, ApplyStatusEnum.YJD.getCode()).list();
            if (CollectionUtil.isNotEmpty(applyList)) {
                //查询到人员名称-服务调用
                List<String> userIdList = applyList.stream().map(CultivateIdentifyApply::getBeIdentifyUserId).collect(Collectors.toList());
                Map<String, PartUserInfoVo> userMap = userApi.getInfoMapByIds(userIdList);
                manuallyInitiateVoList = applyList.stream().map(apply -> {
                    ManuallyInitiateVo manuallyInitiateVo = new ManuallyInitiateVo();
                    manuallyInitiateVo.setName(apply.getName());
                    manuallyInitiateVo.setUserName(Objects.isNull(userMap.get(apply.getBeIdentifyUserId())) ? "未找到该用户" :
                            userMap.get(apply.getBeIdentifyUserId()).getRealName());
                    return manuallyInitiateVo;
                }).collect(Collectors.toList());
                tableDeleteVo.setManuallyInitiateVoList(manuallyInitiateVoList);
            }
        }

        List<PostAndCourseCorrelationVo> correlationVoList = cultivateIdentifyService.selectCorrelationDataList(tableDelete.getId());
        if (CollectionUtil.isNotEmpty(correlationVoList)) {
            postAndCourseVoList.addAll(correlationVoList.stream().map(item -> {
                PostAndCourseVo vo = new PostAndCourseVo();
                vo.setPost(item.getPostName());
                vo.setOfficialRank(item.getOfficialRankName());
                vo.setCourseName(item.getCourseName());
                return vo;
            }).collect(Collectors.toList()));
        }
        tableDeleteVo.setPostAndCourseVoList(postAndCourseVoList);
        if (CollectionUtil.isEmpty(manuallyInitiateVoList) && CollectionUtil.isEmpty(postAndCourseVoList)) {
            tableDelete.setDeleteMark(ConstantUtil.NUM_TRUE);
            this.baseMapper.updateById(tableDelete);
            //删除鉴定项
            List<CultivateIdentifyItems> identifyItemsList = this.itemsService.lambdaQuery()
                    .eq(CultivateIdentifyItems::getTableId, tableDelete.getId())
                    .eq(CultivateIdentifyItems::getDeleteMark, ConstantUtil.NUM_FALSE)
                    .list();
            if (CollectionUtil.isNotEmpty(identifyItemsList)) {
                identifyItemsList.forEach(item -> {
                    item.setDeleteMark(ConstantUtil.NUM_TRUE);
                });
                this.itemsService.updateBatchById(identifyItemsList);
            }
        }
        return tableDeleteVo;
    }

    @Override
    public List<IdentifyTableInfoApiVo> getTableListInfo(List<String> ids) {
        List<CultivateIdentifyTable> tableList = this.lambdaQuery()
                .in(CultivateIdentifyTable::getId, ids)
                .list();
        if (CollectionUtil.isNotEmpty(tableList)) {
            return tableList.stream().map(item -> {
                IdentifyTableInfoApiVo identifyTable = new IdentifyTableInfoApiVo();
                BeanUtils.copyProperties(item, identifyTable);
                identifyTable.setId(item.getId());
                return identifyTable;
            }).collect(Collectors.toList());
        }
        return CollectionUtil.newArrayList();
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateIdentityOrgWisdomStatisticVO> returnEmptyList(FtbIdentityOrgWisdomStatisticDTO statisticDTO) {
        PageListVO<FtbCultivateIdentityOrgWisdomStatisticVO> 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<FtbCultivateIdentityOrgWisdomStatisticVO> organizationListStatistics(FtbIdentityOrgWisdomStatisticDTO statisticDTO) {
        Page<FtbCultivateIdentityOrgWisdomStatisticVO> 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.getOrgId())) {
            List<String> allOrg = new ArrayList<>();
            allOrg.addAll(statisticDTO.getOrgId());
            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)) {
                orgIds = intersection;
            } else {
                return returnEmptyList(statisticDTO);
            }

        } else if (CollUtil.isNotEmpty(statisticDTO.getOrgId())) {
            List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, statisticDTO.getOrgId());
            if (CollUtil.isNotEmpty(intersection)) {
                orgIds = intersection;
            } else {
                return returnEmptyList(statisticDTO);
            }
        } else {
            orgIds = powerOrgList;
        }
        orgIds = UserApiV2Util.uniqueStringList(orgIds);
        Map<String, List<UserPageListVO>> userListForOrgIdsReturnMap = userApiV2Util.getUserListForOrgIdsReturnMap(orgIds, null);
        List<OrganizeGeneralDetailVO> organizeEntityList = userApiV2Util.organizesByOrganizeIds(orgIds, null);
        Map<String, String> orgNameMap = organizeEntityList.stream().collect(Collectors
                .toMap(OrganizeGeneralDetailVO::getId, OrganizeGeneralDetailVO::getName, (a, b) -> a));
        Map<String, String> orgIdMap = cultivatePerUtils.convertOrganizationalId(orgIds);
        List<FtbCultivateIdentityOrgWisdomStatisticVO> records = new ArrayList<>();
        for (String orgId : orgIds) {
            List<UserPageListVO> listFeign = userListForOrgIdsReturnMap.get(orgId);
            if (CollUtil.isNotEmpty(listFeign)) {
                List<String> userIds = listFeign.stream().map(UserPageListVO::getId).collect(Collectors.toList());
                statisticDTO.setUserIds(userIds);
            } else {
                log.error("统计，获取组织id:{}，所对应的人员为空", orgId);
                statisticDTO.setUserIds(EMPTY_USER_LIST);
            }
            List<FtbCultivateIdentityOrgWisdomStatisticVO> list = baseMapper.organizationListStatisticsForUser(statisticDTO);
            list.forEach(item -> {
                if (orgIdMap.containsKey(orgId)) {
                    item.setSysOrganizationID(orgIdMap.get(orgId));
                }
                if (orgNameMap.containsKey(orgId)) {
                    item.setNameOfAssociation(orgNameMap.get(orgId));
                }
                item.setOrganizationID(orgId);
                // 岗位id
//                ActionResult<List<PositionInfoNewVO>> listByOrganizeIds = positionApi.getListByOrganizeIds(orgId);
                List<PositionBaseInfoVO> listByOrganizeIds = userApiV2Util.listPositionBaseInfoByIds(List.of(orgId), null);
                List<String> postionIds = listByOrganizeIds
                        .stream()
                        .map(PositionBaseInfoVO::getId)
                        .collect(Collectors.toList());
                // 岗位学习应鉴定人数
                if (CollUtil.isEmpty(postionIds)) {
                    item.setNumberOfAppraisers(0L);
                } else {
                    List<String> numberOfAppraiserss = baseMapper.numberOfAppraisers(postionIds, item.getTableId());
                    Long numberOfAppraisers = 0L;
                    for (String numberOfAppraiser : numberOfAppraiserss) {
                        ActionResult<Long> userCount = userApi.getUserCount(orgId, numberOfAppraiser);
                        if (userCount != null && userCount.getCode() == 200) {
                            numberOfAppraisers = numberOfAppraisers + userCount.getData();
                        }
                    }
                    item.setNumberOfAppraisers(numberOfAppraisers);
                }
            });
            records.addAll(list);
        }
        return CultivatePage.paginate(records, page);
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateIdentityPersonWisdomStatisticVO> returnEmptyList(FtbIdentityPersonWisdomStatisticDTO statisticDTO) {
        PageListVO<FtbCultivateIdentityPersonWisdomStatisticVO> 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<FtbCultivateIdentityPersonWisdomStatisticVO> personListStatistics(FtbIdentityPersonWisdomStatisticDTO personWisdomStatisticDTO) {
        if (StringUtil.isNotEmpty(personWisdomStatisticDTO.getPostId())) {
            List<UserBoundVO> partUserInfoVos = userApiV2Util.getUserListForPositions(List.of(personWisdomStatisticDTO.getPostId()), null);
            if (CollUtil.isNotEmpty(partUserInfoVos)) {
                List<String> collect = partUserInfoVos.stream().map(UserBoundVO::getId).collect(Collectors.toList());
                if (CollUtil.isEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                    personWisdomStatisticDTO.setSelectPeoples(collect);
                } else {
                    List<String> intersection = UserApiV2Util.getIntersection(collect, personWisdomStatisticDTO.getSelectPeoples());
                    if (CollUtil.isNotEmpty(intersection)) {
                        personWisdomStatisticDTO.setSelectPeoples(intersection);
                    } else {
                        return returnEmptyList(personWisdomStatisticDTO);
                    }
                }
            } else {
                return returnEmptyList(personWisdomStatisticDTO);
            }
        }
        // 人员跳转问题
        if (StringUtil.isNotEmpty(personWisdomStatisticDTO.getOrganizationID())) {
            List<UserPageListVO> listFeign = userApiV2Util.getUserListForOrgIds(List.of(personWisdomStatisticDTO.getOrganizationID()), null);
            if (CollUtil.isNotEmpty(listFeign)) {
                List<String> userIds = listFeign.stream().map(UserPageListVO::getId).collect(Collectors.toList());
                if (CollUtil.isEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                    personWisdomStatisticDTO.setSelectPeoples(userIds);
                } else {
                    List<String> intersection = UserApiV2Util.getIntersection(userIds, personWisdomStatisticDTO.getSelectPeoples());
                    if (CollUtil.isNotEmpty(intersection)) {
                        personWisdomStatisticDTO.setSelectPeoples(intersection);
                    } else {
                        return returnEmptyList(personWisdomStatisticDTO);
                    }
                }
            } else {
                log.error("统计，获取组织id:{}，所对应的人员为空", personWisdomStatisticDTO.getOrganizationID());
                return returnEmptyList(personWisdomStatisticDTO);
            }
        }
        //
        if (StringUtil.isNotEmpty(personWisdomStatisticDTO.getKeyWords())) {
            List<String> keywordUserIds = userApiV2Util.matchUserNameOrSystemId(personWisdomStatisticDTO.getKeyWords());
            if (CollUtil.isEmpty(keywordUserIds)) {
                return returnEmptyList(personWisdomStatisticDTO);
            }
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                List<String> intersection = UserApiV2Util.getIntersection(keywordUserIds, personWisdomStatisticDTO.getSelectPeoples());
                if (CollUtil.isEmpty(intersection)) {
                    return returnEmptyList(personWisdomStatisticDTO);
                }
                personWisdomStatisticDTO.setSelectPeoples(intersection);
            } else {
                personWisdomStatisticDTO.setSelectPeoples(keywordUserIds);
            }
        }

        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode() == 1) {
            if (CollUtil.isNotEmpty(personWisdomStatisticDTO.getSelectPeoples())) {
                List<String> intersection = UserApiV2Util.getIntersection(innerPowerUserVO.getUserIds(), personWisdomStatisticDTO.getSelectPeoples());
                if (CollUtil.isEmpty(intersection)) {
                    return returnEmptyList(personWisdomStatisticDTO);
                } else {
                    personWisdomStatisticDTO.setSelectPeoples(intersection);
                }
            } else {
                personWisdomStatisticDTO.setSelectPeoples(innerPowerUserVO.getUserIds());
            }
        } else if (innerPowerUserVO.getCode() == 2) {
            return returnEmptyList(personWisdomStatisticDTO);
        }
//        personWisdomStatisticDTO.setLeaverUserIds(userApiV2Util.queryLeaveUserId());
        Page<FtbCultivateIdentityPersonWisdomStatisticVO> pageResult = baseMapper.personListStatistics(personWisdomStatisticDTO, Page.of(personWisdomStatisticDTO.getCurrentPage(), personWisdomStatisticDTO.getPageSize()));

        List<FtbCultivateIdentityPersonWisdomStatisticVO> records = pageResult.getRecords();
        
        // 收集所有需要查询的用户ID(员工ID + 考核人ID)
        List<String> employeeIdList = records.stream()
                .flatMap(vo -> {
                    List<String> ids = new ArrayList<>();
                    if (StringUtil.isNotEmpty(vo.getEmployeeID())) {
                        ids.addAll(Arrays.asList(vo.getEmployeeID().split(",")));
                    }
                    if (StringUtil.isNotEmpty(vo.getExaminerId())) {
                        ids.addAll(Arrays.asList(vo.getExaminerId().split(",")));
                    }
                    return ids.stream();
                })
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询用户信息
        Map<String, UserBoundVO> userIdMap = userApiV2Util.getUserPrimaryBoundBatch(employeeIdList, null);
        
        // 填充员工信息和考核人名称
        records.forEach(item -> {
            fillEmployeeInfo(item, userIdMap);
            fillExaminerName(item, userIdMap);
        });
        return CultivatePage.coverPageList(pageResult);
    }

    /**
     * 填充员工信息
     *
     * @param item      统计VO对象
     * @param userIdMap 用户ID映射表
     */
    private void fillEmployeeInfo(FtbCultivateIdentityPersonWisdomStatisticVO item, Map<String, UserBoundVO> userIdMap) {
        UserBoundVO userBoundVO = userIdMap.get(item.getEmployeeID());
        if (userBoundVO == null) {
            return;
        }

        // 构建岗位名称(岗位_职级)
        String positionName = userBoundVO.getPositionName();
        if (StringUtil.isNotEmpty(userBoundVO.getGradeName())) {
            positionName = positionName + "_" + userBoundVO.getGradeName();
        }

        // 设置员工相关信息
        item.setSysJobID(userBoundVO.getPositionEnCode());
        item.setJobID(userBoundVO.getPositionId());
        item.setThisPost(positionName);
        item.setEmployeeSName(userBoundVO.getUserName());
        item.setNameOfAssociation(userBoundVO.getOrganizeName());
        item.setSysOrganizationID(userBoundVO.getOrganizeEnCode());
        item.setSysEmployeeID(userBoundVO.getSystemWorkerId());
    }

    /**
     * 填充考核人名称
     *
     * @param item      统计VO对象
     * @param userIdMap 用户ID映射表
     */
    private void fillExaminerName(FtbCultivateIdentityPersonWisdomStatisticVO item, Map<String, UserBoundVO> userIdMap) {
        if (StringUtils.isEmpty(item.getExaminerId())) {
            return;
        }

        String examinerNames = Arrays.stream(item.getExaminerId().split(","))
                .map(userIdMap::get)
                .filter(ObjectUtil::isNotEmpty)
                .map(UserBoundVO::getUserName)
                .collect(Collectors.joining(","));

        item.setExaminerName(examinerNames);
    }
}
