package com.yushu.web.controller.system;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.system.service.IAiChatService;

import java.util.Map;

/**
 * AI对话Controller
 * 
 * @author yushu
 * @date 2024-11-06
 */
@RestController
@RequestMapping("/system/ai/chat")
public class AiChatController extends BaseController {
    
    @Autowired
    private IAiChatService aiChatService;

    /**
     * 发送聊天消息（非流式）
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:send')")
    @PostMapping("/send")
    public AjaxResult sendMessage(@RequestBody Map<String, Object> params) {
        try {
            // 兼容 serviceId 和 configId
            Object idObj = params.get("serviceId");
            if (idObj == null) {
                idObj = params.get("configId");
            }
            if (idObj == null) {
                return error("请选择AI服务");
            }
            if (params.get("message") == null || params.get("message").toString().trim().isEmpty()) {
                return error("消息内容不能为空");
            }
            
            Long serviceId = Long.valueOf(idObj.toString());
            String message = params.get("message").toString();
            Long conversationId = null;
            
            if (params.containsKey("conversationId") && params.get("conversationId") != null) {
                conversationId = Long.valueOf(params.get("conversationId").toString());
            }
            
            String thinkingType = null;
            if (params.containsKey("thinkingType") && params.get("thinkingType") != null) {
                thinkingType = params.get("thinkingType").toString();
            }
            
            Map<String, Object> result = aiChatService.sendMessage(serviceId, message, conversationId, thinkingType);
            return success(result);
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return error("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 发送聊天消息（流式）
     * 注意：EventSource不支持自定义Header，所以使用GET请求
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:send')")
    @GetMapping("/stream")
    public SseEmitter streamMessage(
            @RequestParam(required = false) Long serviceId,
            @RequestParam(required = false) Long configId,
            @RequestParam String message,
            @RequestParam(required = false) Long conversationId,
            @RequestParam(required = false) String thinkingType,
            @RequestParam(required = false) Boolean enableSearch,
            @RequestParam(required = false) String images,
            @RequestParam(required = false) String Authorization,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            // 设置SSE响应头
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Connection", "keep-alive");
            
            // 兼容 serviceId 和 configId
            Long finalServiceId = serviceId != null ? serviceId : configId;
            return aiChatService.streamMessage(finalServiceId, message, conversationId, thinkingType, enableSearch, images, null);
        } catch (Exception e) {
            logger.error("流式发送消息失败", e);
            SseEmitter emitter = new SseEmitter();
            try {
                emitter.send(SseEmitter.event().name("error").data("发送失败: " + e.getMessage()));
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
            return emitter;
        }
    }

    /**
     * 发送聊天消息（流式 POST）
     * 使用 POST 请求以支持大数据（如图片 base64）
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:send')")
    @PostMapping("/stream")
    public SseEmitter streamMessagePost(
            @RequestBody Map<String, Object> params,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            // 设置SSE响应头
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Connection", "keep-alive");
            
            // 解析参数
            Long serviceId = params.get("serviceId") != null ? Long.valueOf(params.get("serviceId").toString()) : null;
            String message = (String) params.get("message");
            Long conversationId = params.get("conversationId") != null ? Long.valueOf(params.get("conversationId").toString()) : null;
            String thinkingType = (String) params.get("thinkingType");
            Boolean enableSearch = params.get("enableSearch") != null ? Boolean.valueOf(params.get("enableSearch").toString()) : null;
            String images = params.get("images") != null ? params.get("images").toString() : null;
            String fileUrls = params.get("fileUrls") != null ? params.get("fileUrls").toString() : null;
            
            return aiChatService.streamMessage(serviceId, message, conversationId, thinkingType, enableSearch, images, fileUrls);
        } catch (Exception e) {
            logger.error("流式发送消息失败", e);
            SseEmitter emitter = new SseEmitter();
            try {
                emitter.send(SseEmitter.event().name("error").data("发送失败: " + e.getMessage()));
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
            return emitter;
        }
    }

    /**
     * 获取会话历史
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:query')")
    @GetMapping("/history/{conversationId}")
    public AjaxResult getHistory(@PathVariable Long conversationId) {
        return success(aiChatService.getConversationHistory(conversationId));
    }

    /**
     * 创建新会话
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:add')")
    @PostMapping("/conversation")
    public AjaxResult createConversation(@RequestBody Map<String, Object> params) {
        // 兼容 serviceId 和 configId
        Object idObj = params.get("serviceId");
        if (idObj == null) {
            idObj = params.get("configId");
        }
        if (idObj == null) {
            return error("缺少serviceId参数");
        }
        Long serviceId = Long.valueOf(idObj.toString());
        String title = params.getOrDefault("title", "新对话").toString();
        return success(aiChatService.createConversation(serviceId, title));
    }

    /**
     * 获取用户的会话列表
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:list')")
    @GetMapping("/conversations")
    public AjaxResult getConversations() {
        return success(aiChatService.getUserConversations());
    }

    /**
     * 删除会话
     */
    @PreAuthorize("@ss.hasPermi('ai:chat:remove')")
    @DeleteMapping("/conversation/{conversationId}")
    public AjaxResult deleteConversation(@PathVariable Long conversationId) {
        return toAjax(aiChatService.deleteConversation(conversationId));
    }
}




