package jnpf.notice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.notice.domain.FtbNoticeUserGroupMembers;
import jnpf.model.notice.dto.FtbNoticeUserGroupMembersDto;
import jnpf.model.notice.dto.UserOrgAndPositionDto;
import jnpf.model.notice.req.group.ListGroupUserMemberReq;
import jnpf.notice.mapper.FtbNoticeUserGroupMembersMapper;
import jnpf.notice.service.FtbNoticeUserGroupMembersService;
import jnpf.notice.utils.NoticeUtils;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.UploaderUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author 许贵林
 * @description 针对表【ftb_notice_user_group_members(用户分组成员表)】的数据库操作Service实现
 * @createDate 2024-05-08 09:42:09
 */
@Service
public class FtbNoticeUserGroupMembersServiceImpl extends ServiceImpl<FtbNoticeUserGroupMembersMapper, FtbNoticeUserGroupMembers>
        implements FtbNoticeUserGroupMembersService {

    @Autowired
    private NoticeUtils noticeUtils;

    @Autowired
    private UserApiV2Util userApiV2Util;

    /**
     * 分页获取用户组成员列表 内存分页要过滤已经不存在的用户
     *
     * @param groupId 用户组ID，用于定位特定的用户组
     * @param req     包含分页信息和查询条件的请求对象
     * @return 返回分页的用户组成员列表
     */
    @Override
    public PageInfo<FtbNoticeUserGroupMembersDto> getPageList(List<String> powerUserIds, String groupId, ListGroupUserMemberReq req) {
        List<FtbNoticeUserGroupMembersDto> returnList = new ArrayList<>();
        int currentPage = (req.getCurrentPage() != null && req.getCurrentPage() > 0) ? req.getCurrentPage() : 1;
        int pageSize = (req.getPageSize() != null && req.getPageSize() > 0) ? req.getPageSize() : 20;

        Page<FtbNoticeUserGroupMembersDto> queryPage = baseMapper.pagingQuery(Page.of(1, -1), groupId, powerUserIds);
        List<FtbNoticeUserGroupMembersDto> records = queryPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> userIds = records.stream().map(FtbNoticeUserGroupMembersDto::getUserId).collect(Collectors.toList());
            Map<String, UserBoundVO> map = userApiV2Util.getUserPrimaryBoundBatch(new ArrayList<>(userIds), null);
            for (FtbNoticeUserGroupMembersDto noticeUserDto : records) {
                UserBoundVO userBoundVO = map.get(noticeUserDto.getUserId());
                if (userBoundVO != null) {
                    noticeUserDto.setUserId(userBoundVO.getId());
                    noticeUserDto.setUserName(userBoundVO.getName());
                    noticeUserDto.setHeadLogo(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
                    noticeUserDto.setFlowerName(userBoundVO.getNickname());
                    UserOrgAndPositionDto userOrgAndPositionDto = NoticeUtils.getUserOrgAndPositionDto(userBoundVO);
                    noticeUserDto.setOrgList(List.of(userOrgAndPositionDto));
                    returnList.add(noticeUserDto);
                }
            }
        }


        //构建分页返回数据
        PageInfo<FtbNoticeUserGroupMembersDto> pageInfo = new PageInfo<>();
        pageInfo.setTotal(returnList.size());
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(currentPage);
        if (CollectionUtil.isEmpty(returnList)) {
            pageInfo.setList(returnList);
        } else {
            List<List<FtbNoticeUserGroupMembersDto>> batchList = UserApiV2Util.batchList(returnList, pageSize);
            if (currentPage <= batchList.size()) {
                pageInfo.setList(batchList.get(currentPage - 1));
            } else {
                pageInfo.setList(new ArrayList<>());
            }
        }
        return pageInfo;
    }


    /**
     * 获取用户组的所有成员信息
     *
     * @param groupId                 用户组ID，用于定位特定的用户组
     * @param selectFlowerAndHeadLogo 指示是否需要同时查询用户的鲜花数和头像的布尔值
     * @return 返回用户组的所有成员信息列表
     */
    @Override
    public List<FtbNoticeUserGroupMembersDto> getAllList(String groupId, Boolean selectFlowerAndHeadLogo) {
        List<FtbNoticeUserGroupMembersDto> returnList = new ArrayList<>();
        List<String> powerUserIds = userApiV2Util.getPermissionUserIds();
        List<FtbNoticeUserGroupMembersDto> list = baseMapper.queryAllList(groupId, powerUserIds);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> userIds = list.stream().map(FtbNoticeUserGroupMembersDto::getUserId).collect(Collectors.toList());
            Map<String, UserBoundVO> map = userApiV2Util.getUserPrimaryBoundBatch(new ArrayList<>(userIds), null);
            for (FtbNoticeUserGroupMembersDto noticeUserDto : list) {
                UserBoundVO userBoundVO = map.get(noticeUserDto.getUserId());
                if (userBoundVO != null) {
                    noticeUserDto.setUserId(userBoundVO.getId());
                    noticeUserDto.setUserName(userBoundVO.getName());
                    noticeUserDto.setHeadLogo(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
                    noticeUserDto.setFlowerName(userBoundVO.getNickname());
                    UserOrgAndPositionDto userOrgAndPositionDto = NoticeUtils.getUserOrgAndPositionDto(userBoundVO);
                    noticeUserDto.setOrgList(List.of(userOrgAndPositionDto));
                    returnList.add(noticeUserDto);
                }
            }

        }
        return returnList;
    }

    /**
     * 批量添加用户到分组
     *
     * @param groupId  分组ID
     * @param userList 人员列表
     */
    @Override
    public void batchAddGroupUser(String groupId, List<String> userList) {
        if (StringUtils.isEmpty(groupId) || CollectionUtil.isEmpty(userList)) {
            return;
        }
        List<FtbNoticeUserGroupMembers> list = new ArrayList<>();
        for (String userId : userList) {
            FtbNoticeUserGroupMembers member = new FtbNoticeUserGroupMembers();
            member.setUserId(userId);
            member.setGroupId(groupId);
            list.add(member);
        }
        saveBatch(list);
    }

    /**
     * 批量删除用户从分组
     *
     * @param groupId 分组ID
     */
    @Override
    public void batchDeleteGroupUser(String groupId) {
        if (StringUtils.isEmpty(groupId)) {
            return;
        }
        LambdaQueryWrapper<FtbNoticeUserGroupMembers> wrapper = new LambdaQueryWrapper<FtbNoticeUserGroupMembers>()
                .eq(FtbNoticeUserGroupMembers::getGroupId, groupId);
        remove(wrapper);
    }

    /**
     * 根据组ID列表获取所有列表
     * 该方法用于根据提供的组ID列表返回所有相关的列表
     *
     * @param groupIds 组ID列表，用于识别和查询相关的列表
     * @return 返回一个字符串列表，包含所有与提供的组ID相关的项目
     */
    @Override
    public List<String> getAllListByGroupIds(List<String> groupIds, List<String> powerUserIds) {
        List<FtbNoticeUserGroupMembersDto> list = baseMapper.queryAllListForGroupIds(groupIds, powerUserIds);
        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        Set<String> userIdSet = new HashSet<>();
        for (FtbNoticeUserGroupMembersDto ftbNoticeUserGroupMembersDto : list) {
            userIdSet.add(ftbNoticeUserGroupMembersDto.getUserId());
        }
        List<UserBoundVO> userPrimaryBoundBatchReturnList = userApiV2Util.getUserPrimaryBoundBatchReturnList(new ArrayList<>(userIdSet), null);
        if(CollectionUtil.isEmpty(userPrimaryBoundBatchReturnList)){
            return new ArrayList<>();
        }
        return userPrimaryBoundBatchReturnList.stream().map(UserBoundVO::getId).collect(Collectors.toList());

    }

    /**
     * 批量查询用户组内用户的应用情况
     *
     * @param groupIdList 组ID列表，用于识别和查询组内用户的应用情况
     * @return
     */
    @Override
    public List<FtbNoticeUserGroupMembersDto> queryBatchGroupUserApp(List<String> groupIdList, List<String> powerUserIds) {
        List<FtbNoticeUserGroupMembersDto> list = baseMapper.queryAllListForGroupIds(groupIdList, powerUserIds);
        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        if (CollectionUtil.isNotEmpty(list)) {
            //补充人员的花名和 头像
            noticeUtils.fillFlowerAndHeadLog(list);
        }
        return list;
    }

}




