package com.yushu.web.controller.chat;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.yushu.common.annotation.Log;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.common.enums.BusinessType;
import com.yushu.common.utils.SecurityUtils;
import com.yushu.common.utils.spring.SpringUtils;
import com.yushu.system.domain.SysChatMessage;
import com.yushu.system.domain.SysConversation;
import com.yushu.system.service.ISysConversationService;
import com.yushu.system.service.ISysChatMessageService;
import com.yushu.web.websocket.MessageNotifier;

/**
 * 聊天Controller
 * 
 * @author yushu
 * @date 2025-11-12
 */
@RestController
@RequestMapping("/chat")
public class ChatController extends BaseController
{
    @Autowired
    private ISysConversationService conversationService;

    @Autowired
    private ISysChatMessageService chatMessageService;

    /**
     * 获取会话列表
     */
    @GetMapping("/conversations")
    public AjaxResult getConversationList()
    {
        List<Map<String, Object>> list = conversationService.getUserConversationList();
        return AjaxResult.success(list);
    }

    /**
     * 创建或获取私聊会话
     */
    @PostMapping("/conversation/private/{otherUserId}")
    public AjaxResult createPrivateConversation(@PathVariable("otherUserId") Long otherUserId)
    {
        String conversationId = conversationService.createOrGetPrivateConversation(otherUserId);
        return AjaxResult.success(conversationId);
    }

    /**
     * 获取会话消息列表
     */
    @GetMapping("/conversation/{conversationId}/messages")
    public AjaxResult getConversationMessages(@PathVariable("conversationId") String conversationId,
                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "50") Integer pageSize)
    {
        // 直接调用Service，不使用分页插件
        List<SysChatMessage> list = chatMessageService.selectConversationMessages(conversationId, pageNum, pageSize);
        return AjaxResult.success(list);
    }

    /**
     * 发送消息
     */
    @Log(title = "发送消息", businessType = BusinessType.INSERT)
    @PostMapping("/conversation/{conversationId}/message")
    public AjaxResult sendMessage(@PathVariable("conversationId") String conversationId,
                                @RequestBody Map<String, String> params)
    {
        String content = params.get("content");
        if (content == null || content.trim().isEmpty()) {
            return AjaxResult.error("消息内容不能为空");
        }
        
        int result = chatMessageService.sendMessage(conversationId, content.trim());
        
        // 消息发送成功后，更新接收者未读数并通过WebSocket通知
        if (result > 0) {
            try {
                Long currentUserId = SecurityUtils.getUserId();
                logger.info("[Chat] 发送消息: 会话={}, 发送者={}", conversationId, currentUserId);
                
                // 获取会话信息，找出接收者
                SysConversation conversation = conversationService.selectSysConversationByConversationId(conversationId);
                if (conversation != null) {
                    // 获取会话的所有成员
                    java.util.List<Long> memberIds = conversationService.getConversationMemberIds(conversationId);
                    logger.info("[Chat] 会话成员: {}", memberIds);
                    
                    if (memberIds != null && !memberIds.isEmpty()) {
                        // 为所有接收者（除了发送者）增加未读数
                        for (Long memberId : memberIds) {
                            if (!memberId.equals(currentUserId)) {
                                chatMessageService.incrementUnreadCount(conversationId, memberId);
                            }
                        }
                        
                        // 获取最后发送的消息
                        SysChatMessage lastMessage = chatMessageService.selectLastMessage(conversationId);
                        
                        if (lastMessage != null) {
                            // 构建消息数据
                            Map<String, Object> messageData = Map.of(
                                "messageId", lastMessage.getMessageId(),
                                "conversationId", conversationId,
                                "senderId", lastMessage.getSenderId(),
                                "senderName", lastMessage.getSenderName(),
                                "content", lastMessage.getContent(),
                                "messageType", "1",  // 1表示对话消息
                                "createTime", lastMessage.getCreateTime()
                            );
                            
                            // 只通知接收者（排除发送者自己）
                            java.util.List<Long> receiverIds = new java.util.ArrayList<>();
                            for (Long memberId : memberIds) {
                                if (!memberId.equals(currentUserId)) {
                                    receiverIds.add(memberId);
                                }
                            }
                            
                            if (!receiverIds.isEmpty()) {
                                logger.info("[Chat] 推送WebSocket通知给接收者: {}", receiverIds);
                                MessageNotifier notifier = SpringUtils.getBean(MessageNotifier.class);
                                notifier.notifyNewMessage(receiverIds, messageData);
                            } else {
                                logger.warn("[Chat] 没有需要通知的接收者");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("发送WebSocket通知失败", e);
                // 不影响消息发送结果
            }
        }
        
        return toAjax(result);
    }

    /**
     * 设置会话备注
     */
    @Log(title = "设置会话备注", businessType = BusinessType.UPDATE)
    @PutMapping("/conversation/{conversationId}/remark")
    public AjaxResult setConversationRemark(@PathVariable("conversationId") String conversationId,
                                          @RequestBody Map<String, String> params)
    {
        String remarkName = params.get("remarkName");
        int result = conversationService.updateMemberRemark(conversationId, remarkName);
        return toAjax(result);
    }

    /**
     * 获取会话未读消息数
     */
    @GetMapping("/conversation/{conversationId}/unread")
    public AjaxResult getUnreadCount(@PathVariable("conversationId") String conversationId)
    {
        int count = chatMessageService.countUnreadMessages(conversationId);
        return AjaxResult.success(count);
    }

    /**
     * 标记会话为已读
     */
    @Log(title = "标记会话已读", businessType = BusinessType.UPDATE)
    @PutMapping("/conversation/{conversationId}/read")
    public AjaxResult markConversationAsRead(@PathVariable("conversationId") String conversationId)
    {
        int result = chatMessageService.markConversationAsRead(conversationId);
        return toAjax(result);
    }

    /**
     * 删除会话
     */
    @Log(title = "删除会话", businessType = BusinessType.DELETE)
    @DeleteMapping("/conversation/{conversationId}")
    public AjaxResult deleteConversation(@PathVariable("conversationId") String conversationId)
    {
        int result = conversationService.deleteSysConversationByConversationId(conversationId);
        return toAjax(result);
    }
}
