package com.zhentao.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.entity.ChatConversation;
import com.zhentao.entity.ChatMessage;
import com.zhentao.service.ChatMessageService;
import com.zhentao.service.OnlineUserService;
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;

    /**
     * 获取会话消息列表（优化版：添加更多参数支持）
     * 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");
            
            // TODO: 实现会话删除
            // conversationService.deleteConversation(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/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;
    }
    
    /**
     * 健康检查
     * 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;
    }
}
