package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
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.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.ChatHistory;
import com.ruoyi.system.service.IChatHistoryService;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 聊天记录App接口Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/system/chatHistory/app")
public class ChatHistoryAppController extends BaseController
{
    @Autowired
    private IChatHistoryService chatHistoryService;

    /**
     * 根据会话ID查询聊天记录
     */
    @GetMapping("/session/{sessionId}")
    public AjaxResult getChatHistoryBySession(@PathVariable("sessionId") String sessionId)
    {
        try {
            List<ChatHistory> list = chatHistoryService.selectChatHistoryBySessionId(sessionId);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("查询聊天记录失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询聊天记录
     */
    @GetMapping("/user/{userId}")
    public AjaxResult getChatHistoryByUser(@PathVariable("userId") String userId)
    {
        try {
            List<ChatHistory> list = chatHistoryService.selectChatHistoryByUserId(userId);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("查询聊天记录失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增聊天记录
     */
    @PostMapping
    public AjaxResult add(@RequestBody ChatHistory chatHistory)
    {
        try {
            int result = chatHistoryService.insertChatHistory(chatHistory);
            chatHistory.setCreateTime(new Date());
            return toAjax(result);
        } catch (Exception e) {
            logger.error("新增聊天记录失败", e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 批量新增聊天记录
     */
    @PostMapping("/batch")
    public AjaxResult batchAdd(@RequestBody List<ChatHistory> chatHistoryList)
    {
        try {
            int result = chatHistoryService.batchInsertChatHistory(chatHistoryList);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("批量新增聊天记录失败", e);
            return AjaxResult.error("批量新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改聊天记录
     */
    @PutMapping
    public AjaxResult edit(@RequestBody ChatHistory chatHistory)
    {
        try {
            int result = chatHistoryService.updateChatHistory(chatHistory);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("修改聊天记录失败", e);
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除指定会话的聊天记录
     */
    @DeleteMapping("/session/{sessionId}")
    public AjaxResult removeBySession(@PathVariable("sessionId") String sessionId)
    {
        try {
            int result = chatHistoryService.deleteChatHistoryBySessionId(sessionId);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("删除聊天记录失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 删除指定用户的聊天记录
     */
    @DeleteMapping("/user/{userId}")
    public AjaxResult removeByUser(@PathVariable("userId") String userId)
    {
        try {
            int result = chatHistoryService.deleteChatHistoryByUserId(userId);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("删除聊天记录失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 保存用户聊天记录（包含用户消息和客服回复）
     */
    @PostMapping("/saveChat")
    public AjaxResult saveChat(@RequestBody List<ChatHistory> chatHistoryList)
    {
        try {
            if (chatHistoryList == null || chatHistoryList.isEmpty()) {
                return AjaxResult.error("聊天记录不能为空");
            }
            
            int result = chatHistoryService.batchInsertChatHistory(chatHistoryList);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("保存聊天记录失败", e);
            return AjaxResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户最新的聊天记录
     */
    @GetMapping("/latest/{userId}")
    public AjaxResult getLatestChatHistory(@PathVariable("userId") String userId, 
                                          @RequestParam(value = "limit", defaultValue = "20") Integer limit)
    {
        try {
            ChatHistory query = new ChatHistory();
            query.setUserId(userId);
            List<ChatHistory> list = chatHistoryService.selectChatHistoryList(query);
            
            // 限制返回数量
            if (limit != null && limit > 0 && list.size() > limit) {
                list = list.subList(list.size() - limit, list.size());
            }
            
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("查询最新聊天记录失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
} 