package com.zhentao.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.entity.ChatConversation;
import com.zhentao.entity.ChatMessage;
import com.zhentao.entity.MatchmakerChatMessage;
import com.zhentao.service.ChatMessageService;
import com.zhentao.service.MatchmakerChatMessageService;
import com.zhentao.service.OnlineUserService;
import com.zhentao.service.UserVipService;
import com.zhentao.utils.ContactFilter;
import com.zhentao.dto.BlockDto;
import com.zhentao.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 聊天HTTP接口控制器
 * 提供查询历史消息、会话列表等功能
 */
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private OnlineUserService onlineUserService;
    
    @Autowired
    private com.zhentao.repository.ChatConversationMapper conversationMapper;
    
    @Autowired
    private com.zhentao.service.ChatConversationService conversationService;

    @Autowired
    private UserVipService userVipService;
    
    @Autowired
    private MatchmakerChatMessageService matchmakerChatMessageService;
    
    @GetMapping("/test")
    public String test() {
        return "ChatController is working!";
    }

    /**
     * 获取会话消息列表（优化版：添加更多参数支持）
     * GET /api/chat/messages?userId=10001&targetUserId=10002&page=0&size=20&lastMessageId=xxx
     */
    @GetMapping("/messages")
    public Map<String, Object> getMessages(
            @RequestParam Long userId,
            @RequestParam Long targetUserId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String lastMessageId) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            IPage<ChatMessage> messages;
            
            // 如果提供了lastMessageId，使用游标分页（性能更好）
            if (lastMessageId != null && !lastMessageId.isEmpty()) {
                messages = chatMessageService.getConversationMessagesWithCursor(
                    userId, targetUserId, lastMessageId, size
                );
            } else {
                // 否则使用普通分页
                messages = chatMessageService.getConversationMessages(
                    userId, targetUserId, page, size
                );
            }
            
            // 构建响应
            Map<String, Object> data = new HashMap<>();
            data.put("messages", messages.getRecords());
            data.put("total", messages.getTotal());
            data.put("hasMore", messages.getCurrent() < messages.getPages());
            data.put("currentPage", messages.getCurrent());
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", data);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取会话列表（优化版：使用分页查询）
     * GET /api/chat/conversations?userId=10001&pageNum=1&pageSize=20
     */
    @GetMapping("/conversations")
    public Map<String, Object> getConversations(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 使用分页查询，避免全量加载
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<ChatConversation> page = 
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ChatConversation> queryWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                        .orderByDesc("last_message_time");
            
            IPage<ChatConversation> pageResult = conversationMapper.selectPage(page, queryWrapper);
            
            // 构建分页结果
            Map<String, Object> data = new HashMap<>();
            data.put("content", pageResult.getRecords());
            data.put("totalElements", pageResult.getTotal());
            data.put("totalPages", pageResult.getPages());
            data.put("currentPage", pageResult.getCurrent());
            data.put("pageSize", pageResult.getSize());
            data.put("hasMore", pageResult.getCurrent() < pageResult.getPages());
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", data);
            
            System.out.println("✅ 查询会话列表成功，用户ID: " + userId + ", 会话数: " + pageResult.getTotal());
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
            System.err.println("❌ 查询会话列表失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 标记消息为已读
     * POST /api/chat/read
     * Body: {"userId": 10001, "targetUserId": 10002}
     */
    @PostMapping("/read")
    public Map<String, Object> markAsRead(@RequestBody Map<String, Long> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long userId = params.get("userId");
            Long targetUserId = params.get("targetUserId");
            
            chatMessageService.markMessagesAsRead(userId, targetUserId);
            
            result.put("code", 200);
            result.put("message", "标记成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "标记失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取未读消息总数
     * GET /api/chat/unread/count?userId=10001
     */
    @GetMapping("/unread/count")
    public Map<String, Object> getUnreadCount(@RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // TODO: 实现未读消息统计
            // long unreadCount = chatMessageService.getUnreadCount(userId);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", 0);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除会话
     * DELETE /api/chat/conversation
     * Body: {"userId": 10001, "targetUserId": 10002}
     */
    @DeleteMapping("/conversation")
    public Map<String, Object> deleteConversation(@RequestBody Map<String, Long> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long userId = params.get("userId");
            Long targetUserId = params.get("targetUserId");
            
            // 验证参数
            if (userId == null || targetUserId == null) {
                result.put("code", 400);
                result.put("message", "用户ID和目标用户ID不能为空");
                return result;
            }
            
            // 调用服务层删除会话
            BlockDto blockDto = new BlockDto();
            blockDto.setUserId(userId);
            blockDto.setTargetUserId(targetUserId);
            conversationService.deleteChatConversation(blockDto);
            
            result.put("code", 200);
            result.put("message", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "删除失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 检查用户在线状态
     * GET /api/chat/online/status?userId=10001
     */
    @GetMapping("/online/status")
    public Map<String, Object> checkOnlineStatus(@RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean isOnline = onlineUserService.isUserOnline(userId);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", isOnline);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 同步TIM消息到MySQL（双重存储保障）
     * POST /api/chat/syncTIMMessage
     * Body: {
     *   "messageId": "xxx",
     *   "fromUserId": 1,
     *   "toUserId": 7,
     *   "messageType": 1,
     *   "content": "消息内容",
     *   "sendTime": 1234567890
     * }
     */
    @PostMapping("/syncTIMMessage")
    public Map<String, Object> syncTIMMessage(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("🔄 开始同步TIM消息到MySQL...");
            
            // 构建ChatMessage实体
            ChatMessage chatMessage = new ChatMessage();
            
            // 基本信息
            chatMessage.setMessageId(params.get("messageId").toString());
            chatMessage.setFromUserId(Long.valueOf(params.get("fromUserId").toString()));
            chatMessage.setToUserId(Long.valueOf(params.get("toUserId").toString()));
            chatMessage.setMessageType(Integer.valueOf(params.get("messageType").toString()));
            chatMessage.setContent(params.get("content") != null ? params.get("content").toString() : "");
            
            // 会话ID（格式：userId小_userId大）
            Long userId1 = chatMessage.getFromUserId();
            Long userId2 = chatMessage.getToUserId();
            String conversationId = userId1 < userId2 ? 
                userId1 + "_" + userId2 : userId2 + "_" + userId1;
            chatMessage.setConversationId(conversationId);
            
            // 时间信息
            if (params.containsKey("sendTime")) {
                long sendTime = Long.parseLong(params.get("sendTime").toString());
                // TIM返回的是秒级时间戳，需要转换为毫秒
                if (sendTime < 10000000000L) {
                    sendTime = sendTime * 1000;
                }
                chatMessage.setSendTime(new java.util.Date(sendTime));
            } else {
                chatMessage.setSendTime(new java.util.Date());
            }
            
            // 发送状态（从TIM同步过来的消息默认为已送达）
            chatMessage.setSendStatus(2);
            chatMessage.setDeliverTime(new java.util.Date());
            
            // 用户信息（可选）
            if (params.containsKey("fromUserName")) {
                chatMessage.setFromUserName(params.get("fromUserName").toString());
            }
            if (params.containsKey("toUserName")) {
                chatMessage.setToUserName(params.get("toUserName").toString());
            }
            if (params.containsKey("fromUserAvatar")) {
                chatMessage.setFromUserAvatar(params.get("fromUserAvatar").toString());
            }
            
            // 媒体信息（可选）
            if (params.containsKey("mediaUrl")) {
                chatMessage.setMediaUrl(params.get("mediaUrl").toString());
            }
            if (params.containsKey("thumbnailUrl")) {
                chatMessage.setThumbnailUrl(params.get("thumbnailUrl").toString());
            }
            if (params.containsKey("mediaSize")) {
                chatMessage.setMediaSize(Long.valueOf(params.get("mediaSize").toString()));
            }
            if (params.containsKey("duration")) {
                chatMessage.setDuration(Integer.valueOf(params.get("duration").toString()));
            }
            
            // 设置创建时间和更新时间（必填字段）
            java.util.Date now = new java.util.Date();
            chatMessage.setCreateTime(now);
            chatMessage.setUpdateTime(now);
            
            // 检查消息是否已存在（避免重复插入）
            ChatMessage existingMessage = chatMessageService.getMessageByMessageId(chatMessage.getMessageId());
            if (existingMessage != null) {
                System.out.println("⚠️ 消息已存在，跳过: " + chatMessage.getMessageId());
                result.put("code", 200);
                result.put("message", "消息已存在");
                result.put("data", null);
                return result;
            }
            
            // 保存到MySQL
            chatMessageService.saveChatMessage(chatMessage);
            
            // 更新会话表
            chatMessageService.updateOrCreateConversation(
                chatMessage.getFromUserId(),
                chatMessage.getToUserId(),
                chatMessage.getContent(),
                chatMessage.getMessageType(),
                chatMessage.getSendTime()
            );
            
            System.out.println("✅ TIM消息已同步到MySQL: " + chatMessage.getMessageId());
            
            result.put("code", 200);
            result.put("message", "同步成功");
            result.put("data", chatMessage.getMessageId());
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("❌ 同步TIM消息失败: " + e.getMessage());
            result.put("code", 500);
            result.put("message", "同步失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 同步TIM消息到MySQL（支持红娘消息）
     * POST /api/chat/syncTIMMessageV2
     * Body: {
     *   "messageId": "xxx",
     *   "fromTimUserId": "m_123" 或 "456",  // TIM用户ID，红娘以m_开头
     *   "toTimUserId": "456" 或 "m_123",    // TIM用户ID
     *   "messageType": 1,
     *   "content": "消息内容",
     *   "sendTime": 1234567890,
     *   "mediaUrl": "xxx" (可选)
     * }
     */
    @PostMapping("/syncTIMMessageV2")
    public Map<String, Object> syncTIMMessageV2(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("🔄 开始同步TIM消息到MySQL（V2版本）...");
            
            String messageId = params.get("messageId").toString();
            String fromTimUserId = params.get("fromTimUserId").toString();
            String toTimUserId = params.get("toTimUserId").toString();
            Integer messageType = Integer.valueOf(params.get("messageType").toString());
            String content = params.get("content") != null ? params.get("content").toString() : "";
            String mediaUrl = params.containsKey("mediaUrl") ? params.get("mediaUrl").toString() : null;
            
            // 解析发送时间
            java.util.Date sendTime;
            if (params.containsKey("sendTime")) {
                long sendTimeMs = Long.parseLong(params.get("sendTime").toString());
                // TIM返回的是秒级时间戳，需要转换为毫秒
                if (sendTimeMs < 10000000000L) {
                    sendTimeMs = sendTimeMs * 1000;
                }
                sendTime = new java.util.Date(sendTimeMs);
            } else {
                sendTime = new java.util.Date();
            }
            
            // 判断是否是红娘相关消息
            boolean isFromMatchmaker = MatchmakerChatMessage.isMatchmaker(fromTimUserId);
            boolean isToMatchmaker = MatchmakerChatMessage.isMatchmaker(toTimUserId);
            
            if (isFromMatchmaker || isToMatchmaker) {
                // 红娘消息，保存到 matchmaker_chat_message 表
                System.out.println("📌 检测到红娘消息，保存到红娘消息表...");
                
                MatchmakerChatMessage matchmakerMessage = matchmakerChatMessageService.saveFromTimMessage(
                    fromTimUserId, toTimUserId, messageType, content, mediaUrl, messageId
                );
                
                if (matchmakerMessage != null) {
                    // 更新发送时间
                    matchmakerMessage.setSendTime(sendTime);
                    
                    System.out.println("✅ 红娘消息已同步: " + messageId);
                    result.put("code", 200);
                    result.put("message", "红娘消息同步成功");
                    result.put("data", messageId);
                    result.put("type", "matchmaker");
                } else {
                    result.put("code", 400);
                    result.put("message", "无法解析红娘消息");
                }
            } else {
                // 普通用户消息，保存到 chat_message 表
                System.out.println("📌 普通用户消息，保存到用户消息表...");
                
                Long fromUserId = Long.valueOf(fromTimUserId);
                Long toUserId = Long.valueOf(toTimUserId);
                
                // 检查消息是否已存在
                ChatMessage existingMessage = chatMessageService.getMessageByMessageId(messageId);
                if (existingMessage != null) {
                    System.out.println("⚠️ 消息已存在，跳过: " + messageId);
                    result.put("code", 200);
                    result.put("message", "消息已存在");
                    result.put("data", null);
                    return result;
                }
                
                // 构建ChatMessage实体
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setMessageId(messageId);
                chatMessage.setFromUserId(fromUserId);
                chatMessage.setToUserId(toUserId);
                chatMessage.setMessageType(messageType);
                chatMessage.setContent(content);
                chatMessage.setMediaUrl(mediaUrl);
                chatMessage.setSendTime(sendTime);
                chatMessage.setSendStatus(2); // 已送达
                chatMessage.setDeliverTime(new java.util.Date());
                
                // 会话ID
                String conversationId = fromUserId < toUserId ? 
                    fromUserId + "_" + toUserId : toUserId + "_" + fromUserId;
                chatMessage.setConversationId(conversationId);
                
                // 设置创建时间和更新时间
                java.util.Date now = new java.util.Date();
                chatMessage.setCreateTime(now);
                chatMessage.setUpdateTime(now);
                
                // 保存到MySQL
                chatMessageService.saveChatMessage(chatMessage);
                
                // 更新会话表
                chatMessageService.updateOrCreateConversation(
                    fromUserId, toUserId, content, messageType, sendTime
                );
                
                System.out.println("✅ 用户消息已同步: " + messageId);
                result.put("code", 200);
                result.put("message", "用户消息同步成功");
                result.put("data", messageId);
                result.put("type", "user");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("❌ 同步TIM消息失败: " + e.getMessage());
            result.put("code", 500);
            result.put("message", "同步失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取红娘与用户的聊天记录
     * GET /api/chat/matchmakerMessages?matchmakerId=123&userId=456&page=0&size=20
     */
    @GetMapping("/matchmakerMessages")
    public Map<String, Object> getMatchmakerMessages(
            @RequestParam Long matchmakerId,
            @RequestParam Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            IPage<MatchmakerChatMessage> messages = matchmakerChatMessageService.getConversationMessages(
                matchmakerId, userId, page, size
            );
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", messages.getRecords());
            result.put("total", messages.getTotal());
            result.put("pages", messages.getPages());
            result.put("current", messages.getCurrent());
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 标记红娘消息为已读
     * POST /api/chat/markMatchmakerMessagesRead
     * Body: {"matchmakerId": 123, "userId": 456, "readerType": 1}
     * readerType: 1-用户阅读 2-红娘阅读
     */
    @PostMapping("/markMatchmakerMessagesRead")
    public Map<String, Object> markMatchmakerMessagesRead(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long matchmakerId = Long.valueOf(params.get("matchmakerId").toString());
            Long userId = Long.valueOf(params.get("userId").toString());
            Integer readerType = Integer.valueOf(params.get("readerType").toString());
            
            matchmakerChatMessageService.markMessagesAsRead(matchmakerId, userId, readerType);
            
            result.put("code", 200);
            result.put("message", "标记成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "标记失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 健康检查
     * GET /api/chat/health
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "WebSocket Chat Service");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }

//    获取用户消息限制
    @GetMapping("/getUserMessageLimit")
    public ResultVo getUserMessageLimit(@RequestParam("userId")Long userId,@RequestParam("targetUserId")Long targetUserId){
        return userVipService.getUserMessageLimit(userId,targetUserId);
    }

    @GetMapping("/updateMessageCount")
    public ResultVo updateMessageCount(@RequestParam("userId")Long userId,@RequestParam("targetUserId")Long targetUserId){
        return userVipService.updateMessageCount(userId,targetUserId);
    }

    /**
     * 消息内容审核接口
     * POST /api/chat/checkMessage
     * Body: {"userId": 10001, "content": "消息内容"}
     */
    @PostMapping("/checkMessage")
    public Map<String, Object> checkMessage(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String userId = params.get("userId").toString();
            String content = params.get("content").toString();
            
            if (content == null || content.trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "消息内容不能为空");
                result.put("data", false);
                return result;
            }
            
            // 使用ContactFilter进行审核
            boolean hasContact = ContactFilter.hasContact(userId, content);
            
            if (hasContact) {
                System.out.println("⚠️ 消息被拦截 - 用户ID: " + userId + ", 内容: " + content);
                result.put("code", 400);
                result.put("message", "消息包含敏感信息,发送失败");
                result.put("data", false);
            } else {
                result.put("code", 200);
                result.put("message", "审核通过");
                result.put("data", true);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("❌ 消息审核失败: " + e.getMessage());
            result.put("code", 500);
            result.put("message", "审核失败: " + e.getMessage());
            result.put("data", false);
        }
        
        return result;
    }
}
