package com.goafanti.ChatAI.controller;

import com.alibaba.fastjson.JSON;
import com.goafanti.ChatAI.bo.*;
import com.goafanti.ChatAI.service.ChatAiService;
import com.goafanti.common.bo.SseEmitterUTF8;
import com.goafanti.common.utils.LoggerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping(value = "/chat")
public class ChatAiController {

    @Autowired
    private ChatAiService chatAiService;

    @RequestMapping(value = "/send")
    public Object sendChat(@RequestBody InputSendChat in){
        if (in.getUserId()==null ){
            in.setUserId(UUID.randomUUID().toString());
            in.setStream(true);
        }
        return chatAiService.sendChat(in);
    }

    @RequestMapping(value = "/sendGLM")
    public Object sendGLM(@RequestBody InputsendGLM in){
        return chatAiService.sendGLM(in);
    }



    @RequestMapping("/start")
    public SseEmitter testSseEmitter(String clientId) {
        // 默认30秒超时,设置为0L则永不超时
        SseEmitterUTF8 sseEmitter = new SseEmitterUTF8(3600_000L);
//        if (clientId==null)clientId=UUID.randomUUID().toString();
        SseMap.sseEmitterMap.put(clientId, new SseResult(clientId, System.currentTimeMillis(), sseEmitter));
        return sseEmitter;
    }


    /**
     * 向SseEmitter对象发送数据
     *
     * @param clientId
     * @return
     */
    @RequestMapping("/send2")
    public String setSseEmitter(String clientId) {
        try {
            SseResult result =  SseMap.sseEmitterMap.get(clientId);
            if (result != null && result.sseEmitter != null) {
                long timeInMillis = Calendar.getInstance().getTimeInMillis();
                String re = "{\"success\":true,\"message\":\"操作成功！\",\"code\":200,\"result\":{\"id\":1018},\"timestamp\":"+timeInMillis+"}";
                Map<String,Object> map= JSON.parseObject(re);
                  result.sseEmitter.send(map);
            }
        } catch (IOException e) {
            LoggerUtils.error(getClass(),"IOException");
            return "error";
        }
        return "Succeed!";
    }


    /**
     * 将SseEmitter对象设置成完成
     *
     * @param clientId
     * @return
     */
    @RequestMapping("/end")
    public String completeSseEmitter(String clientId) {
        SseResult result =  SseMap.sseEmitterMap.get(clientId);
        if (result != null) {
            SseMap.sseEmitterMap.remove(clientId);
            result.sseEmitter.complete();
        }
        return "Succeed!";
    }



}
