package com.emoon.openplatform.controller;

import cn.hutool.http.server.HttpServerRequest;
import com.emoon.common.core.domain.R;
import com.emoon.common.httpclient.AdminClient;
import com.emoon.common.httpclient.domain.AdminLoginResp;
import com.emoon.common.httpclient.util.AdminLoginRequestFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author destiny
 * @description:
 * @date 2025/10/26 15:30
 */
@Slf4j
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
public class ChatController {

    private final AdminClient adminClient;

    @PostMapping(value = "/handleChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseEntity<StreamingResponseBody> handleChat(@RequestBody(required = false) String requestBody,
                                                            HttpServerRequest request) {
        log.info("handleChat: {}", requestBody);
        return ResponseEntity.ok()
            .header("Cache-Control", "no-cache")
            .header("X-Accel-Buffering", "no")
            .body(outputStream -> {
                try {
                    // 构造固定的对话历史
                    List<Map<String, String>> input = Arrays.asList(
                        Map.of("content", "你好", "role", "user"),
                        Map.of("content", "你好！我是EMOON AI助手，有什么可以帮助你的吗？", "role", "assistant"),
                        Map.of("content", "查询2025年6月1日到2025年6月2的医院数据 并计算这三天外科的平均住院人数是多少?", "role", "user")
                    );
                    R<AdminLoginResp> resp = adminClient.login(AdminLoginRequestFactory.createSuperAdmin());
                    if (R.isError(resp)) {
                        outputStream.write("登录失败".getBytes());
                        return;
                    }
                } catch (Exception e) {
                    outputStream.write("登录失败".getBytes());
                }
            });
    }

}
