package org.xyzh.workcase.service;

import java.util.Date;
import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.xyzh.common.redis.service.RedisService;
import org.springframework.transaction.annotation.Transactional;
import org.xyzh.api.workcase.dto.TbChatRoomMessageDTO;
import org.xyzh.api.workcase.dto.TbChatRoomDTO;
import org.xyzh.api.workcase.dto.TbChatRoomMemberDTO;
import org.xyzh.api.workcase.dto.TbCustomerServiceDTO;
import org.xyzh.api.workcase.service.ChatRoomService;
import org.xyzh.api.workcase.vo.ChatMemberVO;
import org.xyzh.api.workcase.vo.ChatRoomMessageVO;
import org.xyzh.api.workcase.vo.ChatRoomVO;
import org.xyzh.api.workcase.vo.CustomerServiceVO;
import org.xyzh.api.ai.dto.TbChat;
import org.xyzh.api.ai.dto.TbChatMessage;
import org.xyzh.api.ai.service.AgentChatService;
import org.xyzh.api.workcase.constant.WorkcaseConstant;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.utils.NonUtils;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.workcase.mapper.TbChatMessageMapper;
import org.xyzh.workcase.mapper.TbChatRoomMapper;
import org.xyzh.workcase.mapper.TbChatRoomMemberMapper;
import org.xyzh.workcase.mapper.TbCustomerServiceMapper;


/**
 * @description    聊天室服务实现类
 * @filename    ChatRoomServiceImpl.java
 * @author    cascade
 * @copyright xyzh
 * @since 2025-12-22
 */
@DubboService(version = "1.0.0", group = "workcase", timeout = 30000, retries = 0)
public class ChatRoomServiceImpl implements ChatRoomService {
    private static final Logger logger = LoggerFactory.getLogger(ChatRoomServiceImpl.class);

    @Autowired
    private TbChatRoomMapper chatRoomMapper;

    @Autowired
    private TbChatRoomMemberMapper chatRoomMemberMapper;

    @Autowired
    private TbChatMessageMapper chatMessageMapper;

    @Autowired
    private TbCustomerServiceMapper customerServiceMapper;

    @Autowired
    private RedisService redisService;

    @DubboReference(version = "1.0.0", group = "ai", timeout = 30000, retries = 0)
    private AgentChatService agentChatService;

    // ========================= 聊天室管理 ==========================

    @Override
    @Transactional
    public ResultDomain<TbChatRoomDTO> createChatRoom(TbChatRoomDTO chatRoom) {
        logger.info("创建聊天室: guestId={}, aiSessionId={}", chatRoom.getGuestId(), chatRoom.getAiSessionId());

        // 如果关联工单，检查工单是否已有聊天室
        if (chatRoom.getWorkcaseId() != null && !chatRoom.getWorkcaseId().isEmpty()) {
            TbChatRoomDTO filter = new TbChatRoomDTO();
            filter.setWorkcaseId(chatRoom.getWorkcaseId());
            List<ChatRoomVO> existingRooms = chatRoomMapper.selectChatRoomList(filter);
            if (existingRooms != null && !existingRooms.isEmpty()) {
                return ResultDomain.failure("该工单已存在聊天室");
            }
        }

        if (chatRoom.getRoomId() == null || chatRoom.getRoomId().isEmpty()) {
            chatRoom.setRoomId(IdUtil.generateUUID());
        }
        if (chatRoom.getOptsn() == null || chatRoom.getOptsn().isEmpty()) {
            chatRoom.setOptsn(IdUtil.getOptsn());
        }
        if (chatRoom.getStatus() == null || chatRoom.getStatus().isEmpty()) {
            chatRoom.setStatus("active");
        }

        int rows = chatRoomMapper.insertChatRoom(chatRoom);
        if (rows > 0) {
            logger.info("聊天室创建成功: roomId={}", chatRoom.getRoomId());

            // 添加来客到成员表
            if (chatRoom.getGuestId() != null && !chatRoom.getGuestId().isEmpty()) {
                TbChatRoomMemberDTO guestMember = new TbChatRoomMemberDTO();
                guestMember.setMemberId(IdUtil.generateUUID());
                guestMember.setOptsn(IdUtil.getOptsn());
                guestMember.setRoomId(chatRoom.getRoomId());
                guestMember.setUserId(chatRoom.getGuestId());
                guestMember.setUserName(chatRoom.getGuestName());
                guestMember.setUserType("guest");
                guestMember.setStatus("active");
                guestMember.setJoinTime(new Date());
                guestMember.setCreator(chatRoom.getGuestId());
                guestMember.setUnreadCount(0);
                chatRoomMemberMapper.insertChatRoomMember(guestMember);
            }

            // 自动分配客服并添加到成员表
            ResultDomain<CustomerServiceVO> assignResult = assignCustomerService(chatRoom.getRoomId());
            if (Boolean.TRUE.equals(assignResult.getSuccess()) && assignResult.getData() != null) {
                // 更新聊天室当前客服ID
                TbChatRoomDTO updateRoom = new TbChatRoomDTO();
                updateRoom.setRoomId(chatRoom.getRoomId());
                updateRoom.setCurrentAgentId(assignResult.getData().getUserId());
                chatRoomMapper.updateChatRoom(updateRoom);
            }
            // 从AI同步对话历史
            if(NonUtils.isNotEmpty(chatRoom.getAiSessionId())){
                try{
                    syncAiChatMessages(chatRoom);
                }catch(Exception ex){
                    return ResultDomain.failure("创建失败");
                }
            }

            return ResultDomain.success("创建成功", chatRoom);
        }
        return ResultDomain.failure("创建失败");
    }

    @Override
    public ResultDomain<TbChatRoomDTO> updateChatRoom(TbChatRoomDTO chatRoom) {
        logger.info("更新聊天室: roomId={}", chatRoom.getRoomId());

        TbChatRoomDTO existing = chatRoomMapper.selectChatRoomById(chatRoom.getRoomId());
        if (existing == null) {
            return ResultDomain.failure("聊天室不存在");
        }

        int rows = chatRoomMapper.updateChatRoom(chatRoom);
        if (rows > 0) {
            TbChatRoomDTO updated = chatRoomMapper.selectChatRoomById(chatRoom.getRoomId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<Boolean> closeChatRoom(String roomId, String closedBy) {
        logger.info("关闭聊天室: roomId={}, closedBy={}", roomId, closedBy);

        TbChatRoomDTO existing = chatRoomMapper.selectChatRoomById(roomId);
        if (existing == null) {
            return ResultDomain.failure("聊天室不存在");
        }

        TbChatRoomDTO chatRoom = new TbChatRoomDTO();
        chatRoom.setRoomId(roomId);
        chatRoom.setStatus("closed");
        chatRoom.setClosedBy(closedBy);
        chatRoom.setClosedTime(new Date());

        int rows = chatRoomMapper.updateChatRoom(chatRoom);
        if (rows > 0) {
            // 清理Redis中的在线用户
            String onlineUsersKey = WorkcaseConstant.REDIS_CHAT_ONLINE + roomId;
            redisService.delete(onlineUsersKey);
            return ResultDomain.success("关闭成功", true);
        }
        return ResultDomain.failure("关闭失败");
    }

    @Override
    public ResultDomain<Boolean> deleteChatRoom(String roomId) {
        logger.info("删除聊天室: roomId={}", roomId);

        TbChatRoomDTO existing = chatRoomMapper.selectChatRoomById(roomId);
        if (existing == null) {
            return ResultDomain.failure("聊天室不存在");
        }

        TbChatRoomDTO chatRoom = new TbChatRoomDTO();
        chatRoom.setRoomId(roomId);
        int rows = chatRoomMapper.deleteChatRoom(chatRoom);
        if (rows > 0) {
            return ResultDomain.success("删除成功", true);
        }
        return ResultDomain.failure("删除失败");
    }

    @Override
    public ResultDomain<TbChatRoomDTO> getChatRoomById(String roomId) {
        TbChatRoomDTO chatRoom = chatRoomMapper.selectChatRoomById(roomId);
        if (chatRoom != null) {
            return ResultDomain.success("查询聊天室成功", chatRoom);
        }
        return ResultDomain.failure("聊天室不存在");
    }

    @Override
    public ResultDomain<ChatRoomVO> getChatRoomPage(PageRequest<TbChatRoomDTO> pageRequest, String userId) {
        TbChatRoomDTO filter = pageRequest.getFilter();
        if (filter == null) {
            filter = new TbChatRoomDTO();
        }

        PageParam pageParam = pageRequest.getPageParam();
        List<ChatRoomVO> list = chatRoomMapper.selectChatRoomPage(filter, pageParam, userId);
        long total = chatRoomMapper.countChatRooms(filter);
        pageParam.setTotal((int)total);

        PageDomain<ChatRoomVO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询聊天室成功", pageDomain);
    }

    // ========================= 聊天室成员管理 ==========================

    @Override
    public ResultDomain<TbChatRoomMemberDTO> addChatRoomMember(TbChatRoomMemberDTO member) {
        logger.info("添加聊天室成员: roomId={}, userId={}", member.getRoomId(), member.getUserId());

        // 检查聊天室是否存在
        TbChatRoomDTO room = chatRoomMapper.selectChatRoomById(member.getRoomId());
        if (room == null) {
            return ResultDomain.failure("聊天室不存在");
        }

        // 检查是否已是成员
        TbChatRoomMemberDTO filter = new TbChatRoomMemberDTO();
        filter.setRoomId(member.getRoomId());
        filter.setUserId(member.getUserId());
        List<ChatMemberVO> existingMembers = chatRoomMemberMapper.selectChatRoomMemberList(filter);
        if (existingMembers != null && !existingMembers.isEmpty()) {
            // 重置未读数量
            TbChatRoomMemberDTO updateMember = new TbChatRoomMemberDTO();
            updateMember.setMemberId(existingMembers.get(0).getMemberId());
            updateMember.setUnreadCount(0);
            chatRoomMemberMapper.updateChatRoomMember(updateMember);

            return ResultDomain.failure("用户已是聊天室成员，更新未读");
        }

        if (member.getMemberId() == null || member.getMemberId().isEmpty()) {
            member.setMemberId(IdUtil.generateUUID());
        }
        if (member.getOptsn() == null || member.getOptsn().isEmpty()) {
            member.setOptsn(IdUtil.getOptsn());
        }
        if (member.getStatus() == null || member.getStatus().isEmpty()) {
            member.setStatus("active");
        }
        member.setJoinTime(new Date());
        member.setCreator(member.getUserId());

        int rows = chatRoomMemberMapper.insertChatRoomMember(member);
        if (rows > 0) {
            // 更新聊天室成员数
            TbChatRoomDTO updateRoom = new TbChatRoomDTO();
            updateRoom.setRoomId(member.getRoomId());
            updateRoom.setAgentCount(room.getAgentCount() != null ? room.getAgentCount() + 1 : 1);
            chatRoomMapper.updateChatRoom(updateRoom);

            return ResultDomain.success("添加成功", member);
        }
        return ResultDomain.failure("添加失败");
    }

    @Override
    public ResultDomain<Boolean> removeChatRoomMember(String memberId) {
        logger.info("移除聊天室成员: memberId={}", memberId);

        TbChatRoomMemberDTO existing = chatRoomMemberMapper.selectChatRoomMemberById(memberId);
        if (existing == null) {
            return ResultDomain.failure("成员不存在");
        }

        TbChatRoomMemberDTO member = new TbChatRoomMemberDTO();
        member.setMemberId(memberId);
        int rows = chatRoomMemberMapper.deleteChatRoomMember(member);
        if (rows > 0) {
            // 更新聊天室成员数
            TbChatRoomDTO room = chatRoomMapper.selectChatRoomById(existing.getRoomId());
            if (room != null && room.getAgentCount() != null && room.getAgentCount() > 0) {
                TbChatRoomDTO updateRoom = new TbChatRoomDTO();
                updateRoom.setRoomId(existing.getRoomId());
                updateRoom.setAgentCount(room.getAgentCount() - 1);
                chatRoomMapper.updateChatRoom(updateRoom);
            }

            // 从Redis移除在线状态
            String onlineUsersKey = WorkcaseConstant.REDIS_CHAT_ONLINE + existing.getRoomId();
            redisService.sRemove(onlineUsersKey, existing.getUserId());

            return ResultDomain.success("移除成功", true);
        }
        return ResultDomain.failure("移除失败");
    }

    @Override
    public ResultDomain<TbChatRoomMemberDTO> updateChatRoomMember(TbChatRoomMemberDTO member) {
        logger.info("更新聊天室成员: memberId={}", member.getMemberId());

        TbChatRoomMemberDTO existing = chatRoomMemberMapper.selectChatRoomMemberById(member.getMemberId());
        if (existing == null) {
            return ResultDomain.failure("成员不存在");
        }

        int rows = chatRoomMemberMapper.updateChatRoomMember(member);
        if (rows > 0) {
            TbChatRoomMemberDTO updated = chatRoomMemberMapper.selectChatRoomMemberById(member.getMemberId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<ChatMemberVO> getChatRoomMemberList(String roomId) {
        TbChatRoomMemberDTO filter = new TbChatRoomMemberDTO();
        filter.setRoomId(roomId);
        List<ChatMemberVO> list = chatRoomMemberMapper.selectChatRoomMemberList(filter);
        return ResultDomain.success("查询成功", list);
    }

    @Override
    public ResultDomain<Boolean> updateMemberReadStatus(String memberId, String lastReadMsgId) {
        logger.info("更新已读状态: memberId={}, lastReadMsgId={}", memberId, lastReadMsgId);

        TbChatRoomMemberDTO member = new TbChatRoomMemberDTO();
        member.setMemberId(memberId);
        member.setLastReadMsgId(lastReadMsgId);
        member.setLastReadTime(new Date());

        int rows = chatRoomMemberMapper.updateChatRoomMember(member);
        if (rows > 0) {
            return ResultDomain.success("更新成功", true);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<Integer> getUnreadCount(String roomId, String userId) {
        logger.info("查询未读消息数: roomId={}, userId={}", roomId, userId);

        TbChatRoomMemberDTO filter = new TbChatRoomMemberDTO();
        filter.setRoomId(roomId);
        filter.setUserId(userId);
        List<ChatMemberVO> members = chatRoomMemberMapper.selectChatRoomMemberList(filter);
        
        if (members.isEmpty()) {
            return ResultDomain.success("查询成功", 0);
        }
        
        Integer unreadCount = members.get(0).getUnreadCount();
        return ResultDomain.success("查询成功", unreadCount != null ? unreadCount : 0);
    }

    // ========================= 聊天消息管理 ==========================

    @Override
    public ResultDomain<TbChatRoomMessageDTO> sendMessage(TbChatRoomMessageDTO message) {
        logger.info("发送消息: roomId={}, senderId={}, messageType={}",
                message.getRoomId(), message.getSenderId(), message.getMessageType());

        // 检查聊天室是否存在
        TbChatRoomDTO room = chatRoomMapper.selectChatRoomById(message.getRoomId());
        if (room == null) {
            return ResultDomain.failure("聊天室不存在");
        }
        if ("closed".equals(room.getStatus())) {
            return ResultDomain.failure("聊天室已关闭");
        }

        if (message.getMessageId() == null || message.getMessageId().isEmpty()) {
            message.setMessageId(IdUtil.generateUUID());
        }
        if (message.getOptsn() == null || message.getOptsn().isEmpty()) {
            message.setOptsn(IdUtil.getOptsn());
        }
        if (message.getStatus() == null || message.getStatus().isEmpty()) {
            message.setStatus("sent");
        }
        message.setCreator(message.getSenderId());

        // 使用Redis保证消息时间戳递增，避免并发乱序
        String lockKey = WorkcaseConstant.REDIS_CHAT_LOCK + message.getRoomId();
        String timeKey = WorkcaseConstant.REDIS_CHAT_LASTTIME + message.getRoomId();
        
        try {
            // 获取分布式锁（简单实现：SETNX + 过期时间）
            int maxRetry = 10;
            int retry = 0;
            while (retry < maxRetry) {
                Boolean locked = redisService.setIfAbsent(lockKey, "1", 5);
                if (Boolean.TRUE.equals(locked)) {
                    break;
                }
                retry++;
                Thread.sleep(50);
            }
            if (retry >= maxRetry) {
                return ResultDomain.failure("消息发送繁忙，请稍后重试");
            }

            // 获取上一条消息的时间戳，确保时间递增
            long currentTime = System.currentTimeMillis();
            Object lastTimeObj = redisService.get(timeKey);
            if (lastTimeObj != null) {
                long lastTime = Long.parseLong(lastTimeObj.toString());
                if (currentTime <= lastTime) {
                    currentTime = lastTime + 1;
                }
            }
            message.setSendTime(new Date(currentTime));
            
            // 更新Redis中的最后消息时间
            redisService.set(timeKey, String.valueOf(currentTime));

            int rows = chatMessageMapper.insertChatMessage(message);
            if (rows > 0) {
                // 更新聊天室最后消息信息
                TbChatRoomDTO updateRoom = new TbChatRoomDTO();
                updateRoom.setRoomId(message.getRoomId());
                updateRoom.setLastMessage(message.getContent());
                updateRoom.setLastMessageTime(message.getSendTime());
                updateRoom.setMessageCount(room.getMessageCount() != null ? room.getMessageCount() + 1 : 1);
                chatRoomMapper.updateChatRoom(updateRoom);

                // 更新聊天室成员的未读数（除发送者外的所有成员 +1）
                updateMembersUnreadCount(message.getRoomId(), message.getSenderId());

                // 发布消息到Redis Pub/Sub（聊天窗口）
                publishMessageToRedis(message);

                // 发布列表更新通知（聊天室列表）
                publishListUpdateToRedis(message);

                return ResultDomain.success("发送成功", message);
            }
            return ResultDomain.failure("发送失败");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return ResultDomain.failure("消息发送被中断");
        } finally {
            // 释放锁
            redisService.delete(lockKey);
        }
    }

    @Override
    public ResultDomain<ChatRoomMessageVO> getChatMessagePage(PageRequest<TbChatRoomMessageDTO> pageRequest) {
        TbChatRoomMessageDTO filter = pageRequest.getFilter();
        if (filter == null) {
            filter = new TbChatRoomMessageDTO();
        }

        PageParam pageParam = pageRequest.getPageParam();
        List<ChatRoomMessageVO> list = chatMessageMapper.selectChatMessagePage(filter, pageParam);
        long total = chatMessageMapper.countChatMessages(filter);
        pageParam.setTotal((int) total);

        PageDomain<ChatRoomMessageVO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

    @Override
    public ResultDomain<Boolean> deleteMessage(String messageId) {
        logger.info("删除消息: messageId={}", messageId);

        TbChatRoomMessageDTO existing = chatMessageMapper.selectChatMessageById(messageId);
        if (existing == null) {
            return ResultDomain.failure("消息不存在");
        }

        TbChatRoomMessageDTO message = new TbChatRoomMessageDTO();
        message.setMessageId(messageId);
        int rows = chatMessageMapper.deleteChatMessage(message);
        if (rows > 0) {
            return ResultDomain.success("删除成功", true);
        }
        return ResultDomain.failure("删除失败");
    }

    // ========================= 客服人员管理 ==========================

    @Override
    public ResultDomain<TbCustomerServiceDTO> addCustomerService(TbCustomerServiceDTO customerService) {
        logger.info("添加客服人员: userId={}, username={}", customerService.getUserId(), customerService.getUsername());

        // 检查是否已存在
        TbCustomerServiceDTO existing = customerServiceMapper.selectCustomerServiceById(customerService.getUserId());
        if (existing != null) {
            return ResultDomain.failure("该员工已是客服人员");
        }

        if (customerService.getOptsn() == null || customerService.getOptsn().isEmpty()) {
            customerService.setOptsn(IdUtil.getOptsn());
        }
        if (customerService.getStatus() == null || customerService.getStatus().isEmpty()) {
            customerService.setStatus("offline");
        }
        if (customerService.getMaxConcurrent() == null) {
            customerService.setMaxConcurrent(5);
        }
        if (customerService.getCurrentWorkload() == null) {
            customerService.setCurrentWorkload(0);
        }

        int rows = customerServiceMapper.insertCustomerService(customerService);
        if (rows > 0) {
            return ResultDomain.success("添加成功", customerService);
        }
        return ResultDomain.failure("添加失败");
    }

    @Override
    public ResultDomain<TbCustomerServiceDTO> updateCustomerService(TbCustomerServiceDTO customerService) {
        logger.info("更新客服人员: userId={}", customerService.getUserId());

        TbCustomerServiceDTO existing = customerServiceMapper.selectCustomerServiceById(customerService.getUserId());
        if (existing == null) {
            return ResultDomain.failure("客服人员不存在");
        }

        int rows = customerServiceMapper.updateCustomerService(customerService);
        if (rows > 0) {
            TbCustomerServiceDTO updated = customerServiceMapper.selectCustomerServiceById(customerService.getUserId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<Boolean> deleteCustomerService(String userId) {
        logger.info("删除客服人员: userId={}", userId);

        TbCustomerServiceDTO existing = customerServiceMapper.selectCustomerServiceById(userId);
        if (existing == null) {
            return ResultDomain.failure("客服人员不存在");
        }

        TbCustomerServiceDTO customerService = new TbCustomerServiceDTO();
        customerService.setUserId(userId);
        int rows = customerServiceMapper.deleteCustomerService(customerService);
        if (rows > 0) {
            return ResultDomain.success("删除成功", true);
        }
        return ResultDomain.failure("删除失败");
    }

    @Override
    public ResultDomain<CustomerServiceVO> getCustomerServicePage(PageRequest<TbCustomerServiceDTO> pageRequest) {
        TbCustomerServiceDTO filter = pageRequest.getFilter();
        if (filter == null) {
            filter = new TbCustomerServiceDTO();
        }

        PageParam pageParam = pageRequest.getPageParam();
        List<CustomerServiceVO> list = customerServiceMapper.selectCustomerServicePage(filter, pageParam);
        long total = customerServiceMapper.countCustomerServices(filter);
        pageParam.setTotal((int) total);

        PageDomain<CustomerServiceVO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

    @Override
    public ResultDomain<Boolean> updateCustomerServiceStatus(String userId, String status) {
        logger.info("更新客服状态: userId={}, status={}", userId, status);

        TbCustomerServiceDTO customerService = new TbCustomerServiceDTO();
        customerService.setUserId(userId);
        customerService.setStatus(status);

        int rows = customerServiceMapper.updateCustomerService(customerService);
        if (rows > 0) {
            return ResultDomain.success("更新成功", true);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<CustomerServiceVO> getAvailableCustomerServices() {
        TbCustomerServiceDTO filter = new TbCustomerServiceDTO();
        filter.setStatus("online");
        List<CustomerServiceVO> list = customerServiceMapper.selectCustomerServiceList(filter);

        return ResultDomain.success("查询成功", list);
    }

    @Override
    @Transactional
    public ResultDomain<CustomerServiceVO> assignCustomerService(String roomId) {
        logger.info("分配所有客服到聊天室: roomId={}", roomId);

        // 获取所有在线客服列表
        TbCustomerServiceDTO filter = new TbCustomerServiceDTO();
        filter.setStatus("online");
        List<CustomerServiceVO> allServices = customerServiceMapper.selectCustomerServiceList(filter);

        if (allServices == null || allServices.isEmpty()) {
            return ResultDomain.failure("当前没有在线的客服人员");
        }

        // 把所有客服都加入聊天室
        int addedCount = 0;
        for (CustomerServiceVO service : allServices) {
            TbChatRoomMemberDTO member = new TbChatRoomMemberDTO();
            member.setMemberId(IdUtil.generateUUID());
            member.setOptsn(IdUtil.getOptsn());
            member.setRoomId(roomId);
            member.setUserId(service.getUserId());
            member.setCreator(service.getUserId());
            member.setUserType("staff");
            member.setUserName(service.getUsername());
            member.setStatus("active");
            member.setJoinTime(new Date());
            member.setUnreadCount(0);
            chatRoomMemberMapper.insertChatRoomMember(member);

            // 更新客服工作量
            TbCustomerServiceDTO updateService = new TbCustomerServiceDTO();
            updateService.setUserId(service.getUserId());
            updateService.setCurrentWorkload(
                    (service.getCurrentWorkload() != null ? service.getCurrentWorkload() : 0) + 1);
            customerServiceMapper.updateCustomerService(updateService);
            addedCount++;
        }

        // 更新聊天室客服人数
        TbChatRoomDTO updateRoom = new TbChatRoomDTO();
        updateRoom.setRoomId(roomId);
        updateRoom.setAgentCount(addedCount);
        chatRoomMapper.updateChatRoom(updateRoom);

        logger.info("已添加{}名客服到聊天室: roomId={}", addedCount, roomId);
        return ResultDomain.success("分配成功，共添加" + addedCount + "名客服", allServices.get(0));
    }

    // ========================= 私有方法 ==========================

    /**
     * 从AI同步对话历史到聊天室
     * @param chatRoom 聊天室信息（包含aiSessionId和guestId）
     */
    private void syncAiChatMessages(TbChatRoomDTO chatRoom) {
        try {
            // 1. 构建查询条件获取AI对话消息列表
            TbChat filter = new TbChat();
            filter.setChatId(chatRoom.getAiSessionId());
            filter.setUserId(chatRoom.getGuestId());
            filter.setUserType(false); // 来客

            ResultDomain<TbChatMessage> result = agentChatService.getChatMessageList(filter);
            if (!Boolean.TRUE.equals(result.getSuccess()) || result.getDataList() == null) {
                logger.warn("获取AI对话消息失败: aiSessionId={}, message={}", 
                    chatRoom.getAiSessionId(), result.getMessage());
                return;
            }

            List<TbChatMessage> aiMessages = result.getDataList();
            if (aiMessages.isEmpty()) {
                logger.info("AI对话消息为空: aiSessionId={}", chatRoom.getAiSessionId());
                return;
            }

            // 2. 转换并存入聊天室消息表
            int syncCount = 0;
            long baseTime = System.currentTimeMillis() - aiMessages.size() * 1000L; // 保持消息顺序
            
            for (int i = 0; i < aiMessages.size(); i++) {
                TbChatMessage aiMsg = aiMessages.get(i);
                TbChatRoomMessageDTO roomMsg = new TbChatRoomMessageDTO();
                
                roomMsg.setMessageId(IdUtil.generateUUID());
                roomMsg.setOptsn(IdUtil.getOptsn());
                roomMsg.setRoomId(chatRoom.getRoomId());
                roomMsg.setContent(aiMsg.getContent());
                roomMsg.setMessageType("text");
                roomMsg.setStatus("sent");
                roomMsg.setFiles(aiMsg.getFiles());
                roomMsg.setSendTime(aiMsg.getCreateTime());
                roomMsg.setCreateTime(aiMsg.getCreateTime());
                roomMsg.setIsAiMessage(true);
                roomMsg.setAiMessageId(aiMsg.getMessageId());
                roomMsg.setCreator(chatRoom.getGuestId());

                // 根据角色设置发送者信息
                if ("user".equals(aiMsg.getRole())) {
                    roomMsg.setSenderId(chatRoom.getGuestId());
                    roomMsg.setSenderName(chatRoom.getGuestName());
                    roomMsg.setSenderType("guest");
                    roomMsg.setIsAiMessage(false);
                } else {
                    // AI回复
                    roomMsg.setSenderId("AI");
                    roomMsg.setSenderName("智能助手");
                    roomMsg.setSenderType("ai");
                }

                chatMessageMapper.insertChatMessage(roomMsg);
                syncCount++;
            }

            // 3. 更新聊天室消息数和最后消息
            if (syncCount > 0) {
                TbChatMessage lastAiMsg = aiMessages.get(aiMessages.size() - 1);
                TbChatRoomDTO updateRoom = new TbChatRoomDTO();
                updateRoom.setRoomId(chatRoom.getRoomId());
                updateRoom.setLastMessage(lastAiMsg.getContent());
                updateRoom.setLastMessageTime(new Date());
                updateRoom.setMessageCount(syncCount);
                chatRoomMapper.updateChatRoom(updateRoom);
            }

            logger.info("AI对话同步完成: roomId={}, aiSessionId={}, syncCount={}", 
                chatRoom.getRoomId(), chatRoom.getAiSessionId(), syncCount);

        } catch (Exception e) {
            logger.error("同步AI对话失败: aiSessionId={}", chatRoom.getAiSessionId(), e);
        }
    }

    /**
     * 更新聊天室成员的未读数（除发送者外的所有成员 +1）
     */
    private void updateMembersUnreadCount(String roomId, String senderId) {
        try {
            TbChatRoomMemberDTO filter = new TbChatRoomMemberDTO();
            filter.setRoomId(roomId);
            List<ChatMemberVO> members = chatRoomMemberMapper.selectChatRoomMemberList(filter);
            
            for (ChatMemberVO member : members) {
                if (!senderId.equals(member.getUserId())) {
                    TbChatRoomMemberDTO updateMember = new TbChatRoomMemberDTO();
                    updateMember.setMemberId(member.getMemberId());
                    updateMember.setUnreadCount((member.getUnreadCount() != null ? member.getUnreadCount() : 0) + 1);
                    chatRoomMemberMapper.updateChatRoomMember(updateMember);
                }
            }
            logger.debug("已更新聊天室成员未读数: roomId={}, 更新成员数={}", roomId, members.size() - 1);
        } catch (Exception e) {
            logger.error("更新聊天室成员未读数失败: roomId={}", roomId, e);
        }
    }

    private void publishMessageToRedis(TbChatRoomMessageDTO message) {
        try {
            String channel = WorkcaseConstant.REDIS_CHAT_PREFIX + message.getRoomId();
            // RedisService内部已配置FastJson2JsonRedisSerializer，会自动序列化
            redisService.publish(channel, message);
            logger.debug("消息已发布到Redis频道: {}", channel);
        } catch (Exception e) {
            logger.error("发布消息到Redis失败", e);
        }
    }

    private void publishListUpdateToRedis(TbChatRoomMessageDTO message) {
        try {
            // 发布到列表更新频道，前端订阅此频道刷新聊天室列表
            redisService.publish(WorkcaseConstant.REDIS_CHAT_LIST_UPDATE, message);
            logger.debug("列表更新已发布到Redis频道: {}", WorkcaseConstant.REDIS_CHAT_LIST_UPDATE);
        } catch (Exception e) {
            logger.error("发布列表更新到Redis失败", e);
        }
    }

    // ========================= 聊天室评分管理 ==========================

    @Override
    @Transactional
    public ResultDomain<Boolean> submitCommentLevel(String roomId, Integer commentLevel, String userId) {
        logger.info("提交聊天室服务评分: roomId={}, commentLevel={}, userId={}", roomId, commentLevel, userId);

        // 参数校验
        if (NonUtils.isEmpty(roomId)) {
            return ResultDomain.failure("聊天室ID不能为空");
        }
        if (commentLevel == null || commentLevel < 1 || commentLevel > 5) {
            return ResultDomain.failure("评分必须在1-5星之间");
        }

        try {
            // 1. 检查聊天室是否存在
            TbChatRoomDTO chatRoom = chatRoomMapper.selectChatRoomById(roomId);
            if (chatRoom == null) {
                return ResultDomain.failure("聊天室不存在");
            }

            // 2. 检查用户是否是聊天室成员（来客）
            if (!userId.equals(chatRoom.getGuestId())) {
                return ResultDomain.failure("只有来客可以对服务进行评分");
            }

            // 3. 检查是否已评分
            if (chatRoom.getCommentLevel() != null && chatRoom.getCommentLevel() > 0) {
                return ResultDomain.failure("已经评分过了，不能重复评分");
            }

            // 4. 更新评分
            TbChatRoomDTO updateRoom = new TbChatRoomDTO();
            updateRoom.setRoomId(roomId);
            updateRoom.setCommentLevel(commentLevel);

            int rows = chatRoomMapper.updateChatRoom(updateRoom);
            if (rows > 0) {
                logger.info("聊天室服务评分成功: roomId={}, commentLevel={}", roomId, commentLevel);

                // TODO: 后续可以在这里更新客服人员的平均满意度评分
                // updateCustomerServiceSatisfaction(chatRoom, commentLevel);

                return ResultDomain.success("评分成功",true);
            } else {
                return ResultDomain.failure("评分提交失败");
            }

        } catch (Exception e) {
            logger.error("提交聊天室服务评分失败: roomId={}, commentLevel={}", roomId, commentLevel, e);
            return ResultDomain.failure("评分提交失败: " + e.getMessage());
        }
    }
}

