package org.xyzh.workcase.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.xyzh.api.ai.dto.ChatPrepareData;
import org.xyzh.api.ai.dto.TbChat;
import org.xyzh.api.ai.dto.TbChatMessage;
import org.xyzh.api.workcase.dto.TbWordCloudDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseDTO;
import org.xyzh.api.workcase.service.WorkcaseChatService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.utils.validation.ValidationResult;
import org.xyzh.common.utils.validation.ValidationUtils;

import io.swagger.v3.oas.annotations.Operation;

import java.util.Arrays;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @description    工单对话控制器
 *                 - AI对话管理
 *                 - 微信客服消息接收
 *                 - 词云管理
 * @filename    WorkcaseChatController.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Tag(name = "工单对话")
@RestController
@RequestMapping("/workcase/chat")
public class WorkcaseChatContorller {

    @Autowired
    private WorkcaseChatService workcaseChatService;

    // ========================= AI对话管理 =========================

    @Operation(summary = "创建对话")
    @PostMapping
    public ResultDomain<TbChat> createChat(@RequestBody TbChat chat) {
        ValidationResult vr = ValidationUtils.validate(chat, Arrays.asList(
            ValidationUtils.requiredString("userId", "用户ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.createChat(chat);
    }

    @Operation(summary = "更新对话")
    @PutMapping
    public ResultDomain<TbChat> updateChat(@RequestBody TbChat chat) {
        ValidationResult vr = ValidationUtils.validate(chat, Arrays.asList(
            ValidationUtils.requiredString("chatId", "对话ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.updateChat(chat);
    }

    @Operation(summary = "查询对话列表")
    @PostMapping("/list")
    public ResultDomain<TbChat> getChatList(@RequestBody TbChat filter) {
        return workcaseChatService.getChatList(filter);
    }

    @Operation(summary = "获取对话消息列表")
    @PostMapping("/message/list")
    public ResultDomain<TbChatMessage> getChatMessageList(@RequestBody TbChat filter) {
        ValidationResult vr = ValidationUtils.validate(filter, Arrays.asList(
            ValidationUtils.requiredString("chatId", "对话ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.getChatMessageList(filter);
    }

    @Operation(summary = "准备对话会话")
    @PostMapping("/prepare")
    public ResultDomain<String> prepareChatMessageSession(@RequestBody ChatPrepareData prepareData) {
        ValidationResult vr = ValidationUtils.validate(prepareData, Arrays.asList(
            ValidationUtils.requiredString("chatId", "对话ID"),
            ValidationUtils.requiredString("query", "用户问题")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.prepareChatMessageSession(prepareData);
    }

    @Operation(summary = "流式对话（SSE）")
    @GetMapping(value = "/stream/{sessionId}", produces = "text/event-stream")
    public SseEmitter streamChatMessage(@PathVariable String sessionId) {
        return workcaseChatService.streamChatMessageWithSse(sessionId);
    }

    @Operation(summary = "停止对话")
    @PostMapping("/stop/{taskId}")
    public ResultDomain<Boolean> stopChat(@RequestBody TbChat filter, @PathVariable String taskId) {
        return workcaseChatService.stopChatMessageByTaskId(filter, taskId);
    }

    @Operation(summary = "评论对话消息")
    @PostMapping("/comment")
    public ResultDomain<Boolean> commentChatMessage(@RequestBody TbChat filter, 
            @RequestParam String messageId, @RequestParam String comment) {
        return workcaseChatService.commentChatMessage(filter, messageId, comment);
    }

    // ========================= 对话分析 =========================

    @Operation(summary = "分析对话（AI预填工单信息）")
    @GetMapping("/analyze/{chatId}")
    public ResultDomain<TbWorkcaseDTO> analyzeChat(@PathVariable String chatId) {
        return workcaseChatService.analyzeChat(chatId);
    }

    @Operation(summary = "总结对话")
    @PostMapping("/summary/{chatId}")
    public ResultDomain<TbWorkcaseDTO> summaryChat(@PathVariable String chatId) {
        return workcaseChatService.summaryChat(chatId);
    }

    // ========================= 微信客服消息回调 =========================

    @Operation(summary = "微信客服消息回调验证（GET）")
    @GetMapping("/kefu/callback")
    public String kefuCallbackVerify(
            @RequestParam("msg_signature") String msgSignature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) {
        // TODO: 验证签名并返回 echostr
        // 实际应使用微信提供的加解密工具验证
        return echostr;
    }

    @Operation(summary = "微信客服消息回调（POST）")
    @PostMapping("/kefu/callback")
    public String kefuCallback(
            @RequestParam("msg_signature") String msgSignature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestBody String xmlBody) {
        // TODO: 解密消息，调用同步接口拉取消息
        // 收到回调后，应调用 kefuMessageService.syncMessages() 拉取新消息
        // 然后通过 processMessages() 处理消息
        return "success";
    }

    // ========================= 词云管理 =========================

    @Operation(summary = "添加词云")
    @PostMapping("/wordcloud")
    public ResultDomain<TbWordCloudDTO> addWordCloud(@RequestBody TbWordCloudDTO wordCloud) {
        ValidationResult vr = ValidationUtils.validate(wordCloud, Arrays.asList(
            ValidationUtils.requiredString("word", "词语"),
            ValidationUtils.requiredString("category", "分类")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.addWordCloud(wordCloud);
    }

    @Operation(summary = "更新词云")
    @PutMapping("/wordcloud")
    public ResultDomain<TbWordCloudDTO> updateWordCloud(@RequestBody TbWordCloudDTO wordCloud) {
        ValidationResult vr = ValidationUtils.validate(wordCloud, Arrays.asList(
            ValidationUtils.requiredString("wordCloudId", "词云ID")
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.updateWordCloud(wordCloud);
    }

    @Operation(summary = "查询词云列表")
    @PostMapping("/wordcloud/list")
    public ResultDomain<TbWordCloudDTO> getWordCloudList(@RequestBody TbWordCloudDTO filter) {
        return workcaseChatService.getWordCloudList(filter);
    }

    @Operation(summary = "分页查询词云")
    @PostMapping("/wordcloud/page")
    public ResultDomain<TbWordCloudDTO> getWordCloudPage(@RequestBody PageRequest<TbWordCloudDTO> pageRequest) {
        ValidationResult vr = ValidationUtils.validate(pageRequest, Arrays.asList(
            ValidationUtils.requiredNumber("pageParam.page", "页码", 1, null),
            ValidationUtils.requiredNumber("pageParam.pageSize", "每页数量", 1, 100)
        ));
        if (!vr.isValid()) {
            return ResultDomain.failure(vr.getAllErrors());
        }
        return workcaseChatService.getWordCloudPage(pageRequest);
    }

}
