package jnpf.notice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.PageDto;
import jnpf.model.notice.domain.FtbNoticeUserGroups;
import jnpf.model.notice.dto.FtbNoticeUserGroupMembersDto;
import jnpf.model.notice.dto.FtbNoticeUserGroupsDto;
import jnpf.model.notice.enums.NoticeEnums;
import jnpf.model.notice.req.group.AddUserGroupReq;
import jnpf.model.notice.req.group.ListGroupUserMemberReq;
import jnpf.model.notice.req.group.UpdateUserGroupReq;
import jnpf.notice.mapper.FtbNoticeUserGroupsMapper;
import jnpf.notice.service.FtbNoticeUserGroupMembersService;
import jnpf.notice.service.FtbNoticeUserGroupsService;
import jnpf.notice.utils.NoticeAsyncDealUtil;
import jnpf.notice.utils.NoticeUtils;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 许贵林
 * @description 针对表【ftb_notice_user_groups(用户分组表)】的数据库操作Service实现
 * @createDate 2024-05-08 09:42:09
 */
@Service
public class FtbNoticeUserGroupsServiceImpl extends ServiceImpl<FtbNoticeUserGroupsMapper, FtbNoticeUserGroups>
        implements FtbNoticeUserGroupsService {

    @Autowired
    private FtbNoticeUserGroupMembersService ftbNoticeUserGroupMembersService;

    @Autowired
    private NoticeUtils noticeUtils;

    @Autowired
    private NoticeAsyncDealUtil noticeAsyncDealUtil;

    @Autowired
    private UserApiV2Util userApiV2Util;

    /**
     * 查询所有分组信息
     * @return
     */
    @Override
    public List<FtbNoticeUserGroupsDto> queryWebAllGroup() {
        String loginUserId = UserProvider.getLoginUserId();
        QueryWrapper<FtbNoticeUserGroups> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbNoticeUserGroups::getEnabledMark, NoticeEnums.DeleteType.VALID.getCode())
                .eq(FtbNoticeUserGroups::getCreatorUserId, loginUserId)
                .orderByAsc(FtbNoticeUserGroups::getCreatorTime);
        List<FtbNoticeUserGroups> list = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        //查询离职人员
        List<String> powerUserIds = userApiV2Util.getPermissionUserIds();
        List<FtbNoticeUserGroupsDto> dtoList = BeanUtil.copyToList(list, FtbNoticeUserGroupsDto.class);
        //循环查询每个分组的人员数量和第一个用户
        ListGroupUserMemberReq req = new ListGroupUserMemberReq();
        req.setPageSize(1);
        req.setCurrentPage(1);
        req.setSelectFlowerAndHeadLogo(true);
        for (FtbNoticeUserGroupsDto dto : dtoList) {
            PageInfo<FtbNoticeUserGroupMembersDto> page = pageSelectGroupUser(powerUserIds, dto.getId(), req);
            dto.setUserCount(page.getTotal());
            dto.setUserList(page.getList());
        }
        return dtoList;
    }

    /**
     * 分页查询分组信息
     * @param req 分页查询请求对象
     * @return
     */
    @Override
    public PageInfo<FtbNoticeUserGroupsDto> queryAppPage(PageDto req) {
        String loginUserId = UserProvider.getLoginUserId();
        Page<FtbNoticeUserGroupsDto> queryPage = baseMapper.pagingQuery(Page.of(req.getCurrentPage(), req.getPageSize()),loginUserId);
        List<FtbNoticeUserGroupsDto> records = queryPage.getRecords();

        if (CollectionUtil.isNotEmpty(records)) {
            //查询离职人员
            ListGroupUserMemberReq memberReq = new ListGroupUserMemberReq();
            memberReq.setPageSize(5);
            memberReq.setCurrentPage(1);
            memberReq.setSelectFlowerAndHeadLogo(true);
            List<String> powerUserIds = userApiV2Util.getPermissionUserIds();
            for (FtbNoticeUserGroupsDto dto : records) {
                PageInfo<FtbNoticeUserGroupMembersDto> page = pageSelectGroupUser(powerUserIds, dto.getId(), memberReq);
                dto.setUserCount(page.getTotal());
                dto.setUserList(page.getList());
            }
        }
        //构建分页返回数据
        PageInfo<FtbNoticeUserGroupsDto> pageInfo = new PageInfo<>();
        pageInfo.setList(records);
        pageInfo.setPageSize((int) queryPage.getSize());
        pageInfo.setPageNum((int) queryPage.getCurrent());
        pageInfo.setTotal((int) queryPage.getTotal());
        return pageInfo;
    }

    /**
     * 批量查询用户组人员信息
     * @param groupIds 用户组的标识列表
     * @return
     */
    @Override
    public List<String> queryBatchGroupUser(String groupIds) {
        if (StringUtils.isEmpty(groupIds)) {
            return new ArrayList<>();
        }
        // 将数组转换为 List
        List<String> groupIdList = Arrays.asList(groupIds.split(","));
        if (CollectionUtil.isEmpty(groupIdList)) {
            return new ArrayList<>();
        }
        List<String> powerUserIds = userApiV2Util.getPermissionUserIds();
        return ftbNoticeUserGroupMembersService.getAllListByGroupIds(groupIdList, powerUserIds);

    }

    /**
     * 批量查询用户组人员信息
     * @param groupIds 用户组的标识列表
     * @return
     */
    @Override
    public List<FtbNoticeUserGroupMembersDto> queryBatchGroupUserApp(String groupIds) {
        if (StringUtils.isEmpty(groupIds)) {
            return new ArrayList<>();
        }
        // 将数组转换为 List
        List<String> groupIdList = Arrays.asList(groupIds.split(","));
        if (CollectionUtil.isEmpty(groupIdList)) {
            return new ArrayList<>();
        }
        List<String> powerUserIds = userApiV2Util.getPermissionUserIds();
        return ftbNoticeUserGroupMembersService.queryBatchGroupUserApp(groupIdList, powerUserIds);
    }

    public PageInfo<FtbNoticeUserGroupMembersDto> pageSelectGroupUser(List<String> powerUserIds, String groupId, ListGroupUserMemberReq req) {
        return ftbNoticeUserGroupMembersService.getPageList(powerUserIds, groupId, req);
    }

    /**
     * 新增用户组
     * @param req 包含要插入用户组信息的请求对象
     * @return
     */
    @Override
    @Transactional
    public String insertData(AddUserGroupReq req) {
        String loginUserId = UserProvider.getLoginUserId();
        //检测名称是否重复
        QueryWrapper<FtbNoticeUserGroups> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbNoticeUserGroups::getGroupName, req.getGroupName())
                .eq(FtbNoticeUserGroups::getCreatorUserId, loginUserId)
                .eq(FtbNoticeUserGroups::getEnabledMark, NoticeEnums.DeleteType.VALID.getCode());
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("分组名称已经存在");
        }


        if (CollectionUtil.isEmpty(req.getUserList())) {
            throw new RuntimeException("分组人员不能为空");
        }


        //添加分组
        FtbNoticeUserGroups entity = new FtbNoticeUserGroups();
        entity.setGroupName(req.getGroupName());
        entity.setEnabledMark(NoticeEnums.DeleteType.VALID.getCode());
        entity.setCreatorUserId(loginUserId);
        baseMapper.insert(entity);

        //异步添加用户到分组成员列表
        batchAddGroupUser(entity.getId(), noticeUtils.uniqueStringList(req.getUserList()));

        return entity.getId();
    }

    /**
     * 修改用户组信息
     * @param id 用户组的唯一标识
     * @param req 包含要更新用户组信息的请求对象
     */
    @Override
    @Transactional
    public void updateData(String id, UpdateUserGroupReq req) {
        String loginUserId = UserProvider.getLoginUserId();
        //检测是否删除
        FtbNoticeUserGroups ftbNoticeUserGroups = queryAndCheckById(id);
        if(!ftbNoticeUserGroups.getCreatorUserId().equals(loginUserId)){
            throw new RuntimeException("您没有权限修改此分组信息");
        }
        //检测名称是否重复
        QueryWrapper<FtbNoticeUserGroups> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbNoticeUserGroups::getGroupName, req.getGroupName())
                .ne(FtbNoticeUserGroups::getId, id)
                .eq(FtbNoticeUserGroups::getCreatorUserId, loginUserId)
                .eq(FtbNoticeUserGroups::getEnabledMark, NoticeEnums.DeleteType.VALID.getCode());
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("分组名称已经存在");
        }

        if (CollectionUtil.isEmpty(req.getUserList())) {
            throw new RuntimeException("分组人员不能为空");
        }


        //修改
        FtbNoticeUserGroups entity = new FtbNoticeUserGroups();
        entity.setId(id);
        entity.setEnabledMark(NoticeEnums.DeleteType.VALID.getCode());
        entity.setGroupName(req.getGroupName());
        baseMapper.updateById(entity);
        //异步调整分组人员
        batchUpdateGroupUser(entity.getId(), noticeUtils.uniqueStringList(req.getUserList()));


    }

    /**
     * 查询用户组信息
     * @param id 用户组的唯一标识
     * @return
     */
    @Override
    public FtbNoticeUserGroupsDto getInfo(String id) {
        //检测是否删除
        FtbNoticeUserGroups oldGroup = queryAndCheckById(id);
        FtbNoticeUserGroupsDto ftbNoticeUserGroupsDto = BeanUtil.copyProperties(oldGroup, FtbNoticeUserGroupsDto.class);

        //查询分组的全部人员
        List<FtbNoticeUserGroupMembersDto> userList = ftbNoticeUserGroupMembersService.getAllList(id, true);
        ftbNoticeUserGroupsDto.setUserList(userList);
        ftbNoticeUserGroupsDto.setUserCount((long) userList.size());
        return ftbNoticeUserGroupsDto;
    }

    /**
     * 删除用户组
     * @param id 用户组的唯一标识
     */
    @Override
    @Transactional
    public void deleteData(String id) {
        String loginUserId = UserProvider.getLoginUserId();
        //检测是否删除
        FtbNoticeUserGroups ftbNoticeUserGroups = queryAndCheckById(id);
        if(!ftbNoticeUserGroups.getCreatorUserId().equals(loginUserId)){
            throw new RuntimeException("您没有权限删除此分组信息");
        }

        //删除分组
        FtbNoticeUserGroups entity = new FtbNoticeUserGroups();
        entity.setId(id);
        entity.setEnabledMark(NoticeEnums.DeleteType.INVALID.getCode());
        baseMapper.updateById(entity);

        //删除分组人员
        batchDeleteGroupUser(id);
    }

    /**
     * 查询并检查用户组是否存在
     * @param id
     * @return
     */
    private FtbNoticeUserGroups queryAndCheckById(String id) {
        FtbNoticeUserGroups entity = baseMapper.selectById(id);
        if (null == entity) {
            throw new RuntimeException("分组不存在");
        }
        if (entity.getEnabledMark().equals(NoticeEnums.DeleteType.INVALID.getCode())) {
            throw new RuntimeException("分组已经删除");
        }
        return entity;
    }

    /**
     * 异步添加用户到分组成员列表
     * @param groupId 分组唯一标识
     * @param userList 用户列表集合
     */
    private void batchAddGroupUser(String groupId, List<String> userList) {
        String tenantId = noticeUtils.getTenantId();
        Map<String, String> headers = noticeUtils.getHeadersForLogin();
        noticeAsyncDealUtil.asyncAddUserGroupMember(tenantId, groupId, userList, headers);
    }

    /**
     * 异步修改分组人员
     * @param groupId 分组唯一标识
     * @param userList 用户集合
     */
    private void batchUpdateGroupUser(String groupId, List<String> userList) {
        String tenantId = noticeUtils.getTenantId();
        Map<String, String> headers = noticeUtils.getHeadersForLogin();
        noticeAsyncDealUtil.asyncUpdateUserGroupMember(tenantId, groupId, userList, headers);
    }

    /**
     * 异步删除分组人员
     * @param groupId 分组唯一标识
     */
    private void batchDeleteGroupUser(String groupId) {
        String tenantId = noticeUtils.getTenantId();
        Map<String, String> headers = noticeUtils.getHeadersForLogin();
        noticeAsyncDealUtil.asyncDeleteUserGroupMember(tenantId, groupId, headers);
    }
}




