package com.custom.webui.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.custom.webui.dto.req.ChatGroupRequest; import com.custom.webui.dto.resp.ChatGroupDTO; import com.custom.webui.entity.Chat; import com.custom.webui.entity.ChatGroup; import com.custom.webui.exception.BusinessException; import com.custom.webui.mapper.ChatGroupMapper; import com.custom.webui.mapper.ChatMapper; import com.custom.webui.service.ChatGroupService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** 对话分组服务实现。 */ @Slf4j @Service @RequiredArgsConstructor public class ChatGroupServiceImpl implements ChatGroupService { private final ChatGroupMapper chatGroupMapper; private final ChatMapper chatMapper; @Override public List listByUser(Long userId) { List groups = chatGroupMapper.selectList( Wrappers.lambdaQuery() .eq(ChatGroup::getUserId, userId) .orderByAsc(ChatGroup::getId)); if (groups.isEmpty()) { return Collections.emptyList(); } // 一次聚合出每个分组的会话数,避免逐个分组查一次(N+1) Map countByGroup = chatMapper.selectList( Wrappers.lambdaQuery() .select(Chat::getGroupId) .eq(Chat::getUserId, userId) .eq(Chat::getArchived, false) .isNotNull(Chat::getGroupId)) .stream() .collect(Collectors.groupingBy(Chat::getGroupId, Collectors.counting())); return groups.stream().map(g -> toDto(g, countByGroup.getOrDefault(g.getId(), 0L))).toList(); } @Override @Transactional(rollbackFor = Exception.class) public ChatGroupDTO create(Long userId, ChatGroupRequest request) { String name = normalizeName(request.getName()); requireNameAvailable(userId, name, null); ChatGroup group = new ChatGroup(); group.setUserId(userId); group.setName(name); group.setCreatedAt(LocalDateTime.now()); chatGroupMapper.insert(group); log.info("新建对话分组 userId={} groupId={} name={}", userId, group.getId(), name); return toDto(group, 0L); } @Override @Transactional(rollbackFor = Exception.class) public ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request) { requireOwnedGroup(userId, groupId); String name = normalizeName(request.getName()); requireNameAvailable(userId, name, groupId); ChatGroup update = new ChatGroup(); update.setId(groupId); update.setName(name); chatGroupMapper.updateById(update); Long count = chatMapper.selectCount( Wrappers.lambdaQuery() .eq(Chat::getGroupId, groupId) .eq(Chat::getArchived, false)); return toDto(chatGroupMapper.selectById(groupId), count); } @Override @Transactional(rollbackFor = Exception.class) public int delete(Long userId, Long groupId) { requireOwnedGroup(userId, groupId); // 只解除关联,**不删会话**:删文件夹不该毁掉里面的东西。 // 把 group_id 显式置 NULL 用 UpdateWrapper —— 实体的 null 字段 // 会被 MyBatis-Plus 忽略,表达不了「置空」这个意图。 int moved = chatMapper.update(null, Wrappers.lambdaUpdate() .eq(Chat::getGroupId, groupId) .eq(Chat::getUserId, userId) .set(Chat::getGroupId, null)); chatGroupMapper.deleteById(groupId); log.info("删除对话分组 userId={} groupId={},{} 条会话回到未分组", userId, groupId, moved); return moved; } @Override public ChatGroup requireOwnedGroup(Long userId, Long groupId) { if (groupId == null) { throw BusinessException.badRequest("分组 id 不能为空"); } ChatGroup group = chatGroupMapper.selectById(groupId); // 不存在与不属于当前用户统一 404:返回 403 等于确认「这个 id 存在」 if (group == null || !group.getUserId().equals(userId)) { throw BusinessException.notFound("分组不存在或无权访问"); } return group; } // ==================== 内部辅助 ==================== private String normalizeName(String raw) { String name = raw == null ? "" : raw.trim(); if (name.isEmpty()) { throw BusinessException.badRequest("分组名不能为空"); } // 列宽 64,超长直接截断而不是抛数据库异常 return name.length() > 64 ? name.substring(0, 64) : name; } /** * 检查重名。 * *

先查一次是为了给用户一句「已有同名分组」的人话提示; * 数据库上的唯一键仍然保留,用于兜住并发插入(两个请求同时通过检查)。 */ private void requireNameAvailable(Long userId, String name, Long excludeId) { ChatGroup exists = chatGroupMapper.selectOne( Wrappers.lambdaQuery() .eq(ChatGroup::getUserId, userId) .eq(ChatGroup::getName, name) .last("LIMIT 1")); if (exists != null && !exists.getId().equals(excludeId)) { throw BusinessException.badRequest("已有同名分组:" + name); } } private ChatGroupDTO toDto(ChatGroup group, Long chatCount) { ChatGroupDTO dto = new ChatGroupDTO(); dto.setId(group.getId()); dto.setName(group.getName()); dto.setChatCount(chatCount == null ? 0L : chatCount); return dto; } }