package com.xy.xyaicpzs.controller;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.xy.xyaicpzs.domain.entity.ChatMessage;
import com.xy.xyaicpzs.service.ChatMessageService;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;

@RestController
public class ChatController {

    @Autowired
    private ChatMessageService chatMessageService;
    
    @Value("${dashscope.api-key}")
    private String dashscopeApiKey;

    /**
     * SSE流式聊天接口
     * @param message 用户消息
     * @param conversationId 会话ID
     * @param userId 用户ID
     * @return SseEmitter
     */
    @GetMapping("/chat/sse")
    public SseEmitter chatSseEmitter(
            @RequestParam String message,
            @RequestParam(required = false) String conversationId,
            @RequestParam(required = false) String userId) {
        
        // 保存用户消息到数据库
        saveMessage(conversationId, userId, "USER", message);
        
        // 创建一个超时时间较长的 SseEmitter
        SseEmitter emitter = new SseEmitter(180000L); // 3分钟超时
        
        // 用于收集完整的AI回复
        AtomicReference<StringBuilder> fullResponseRef = new AtomicReference<>(new StringBuilder());
        
        try {
            // 设置AI参数
            ApplicationParam param = ApplicationParam.builder()
                    .apiKey(dashscopeApiKey) // 使用配置文件中的API密钥
                    .appId("ec08d5b81ca248e8834228c1133e2c78")
                    .prompt(message)
                    .incrementalOutput(true)
                    .build();
            
            Application application = new Application();
            
            // 流式调用
            Flowable<ApplicationResult> result = application.streamCall(param);
            
            result.subscribe(
                    // 处理每条消息
                    data -> {
                        try {
                            String text = data.getOutput().getText();
                            // 发送数据到客户端
                            emitter.send(text);
                            // 收集完整响应
                            fullResponseRef.get().append(text);
                        } catch (IOException e) {
                            emitter.completeWithError(e);
                        }
                    },
                    // 处理错误
                    error -> {
                        emitter.completeWithError(error);
                        System.out.println("错误: " + error.getMessage());
                    },
                    // 处理完成
                    () -> {
                        // 保存AI回复到数据库
                        String fullResponse = fullResponseRef.get().toString();
                        saveMessage(conversationId, userId, "AI", fullResponse);
                        emitter.complete();
                    }
            );
            
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            try {
                emitter.send("错误: " + e.getMessage());
                emitter.complete();
            } catch (IOException ex) {
                emitter.completeWithError(ex);
            }
            System.out.println("异常: " + e.getMessage());
        }
        
        return emitter;
    }
    
    /**
     * 保存消息到数据库
     * @param conversationId 会话ID
     * @param userId 用户ID
     * @param messageType 消息类型(USER/AI)
     * @param content 消息内容
     */
    private void saveMessage(String conversationId, String userId, String messageType, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setConversationId(conversationId);
        chatMessage.setStudentId(userId);
        chatMessage.setMessageType(messageType);
        chatMessage.setContent(content);
        chatMessage.setCreateTime(new Date());
        chatMessage.setUpdateTime(new Date());
        chatMessage.setIsDelete(0);
        chatMessageService.save(chatMessage);
    }
} 