package com.storlead.knowledge.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.storlead.framework.common.result.Result;
import com.storlead.knowledge.config.DifyProperties;
import com.storlead.knowledge.pojo.dto.ChatDTO;
import com.storlead.knowledge.pojo.dto.TagDTO;
import com.storlead.knowledge.utils.HttpService;
import com.storlead.knowledge.utils.JacksonHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.IOException;


@RestController
@RequestMapping("/chat/")
@Api(tags = "对话及流程")
public class ChatController {
    @Resource
    private HttpService httpService;

    @Resource
    private DifyProperties difyProperties;

    /**
     * 创建聊天 blocking模式
     * @param chatDTO
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("chat")
    @ApiOperation("创建聊天")
    public Result<Object> chat(@RequestBody ChatDTO chatDTO) throws JsonProcessingException {
        String url = difyProperties.getBaseUrl() + "chat-messages";
        String body = JacksonHolder.OBJECT_MAPPER.writeValueAsString(chatDTO);
        return httpService.post(url, null, "Bearer "+difyProperties.getAppKeys().get(chatDTO.getAppId()), body, new TypeReference<>() {});
    }


    /**
     * 创建聊天 流式模式
     * @param chatDTO
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/chatStreaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatStreaming(@RequestBody ChatDTO chatDTO) throws IOException {

        SseEmitter emitter = new SseEmitter(0L); // 0 = 不超时

        String url = difyProperties.getBaseUrl() + "chat-messages";

        // 强制开启流式
        //chatDTO.setStream(true);

        String body = JacksonHolder.OBJECT_MAPPER.writeValueAsString(chatDTO);

        httpService.postStream(
                url,
                "Bearer " + difyProperties.getAppKeys().get(chatDTO.getAppId()),
                body,
                emitter
        );

        return emitter;
    }

}
