package org.dromara.talk.controller.api;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.dto.DictDataDTO;
import org.dromara.common.core.service.DictService;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.talk.domain.bo.TalkAgentBo;
import org.dromara.talk.domain.dto.MessageStreamRequest;
import org.dromara.talk.domain.vo.TalkAgentVo;
import org.dromara.talk.service.IChatService;
import org.dromara.talk.service.ITalkAgentService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

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

/**
 * 对话接口（对话前端）
 *
 * @author Lion Li
 *  2026-01-27
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/talk")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ChatController {

    private final IChatService chatService;
    private final DictService dictService;
    private final ITalkAgentService talkAgentService;

    /**
     * 获取TTS发言人字典
     * 返回系统支持的TTS发言人列表，用于AI动态选择合适的发言人
     *
     * @return TTS发言人字典列表
     */
    @GetMapping("/dict/ttsVcn")
    public List<DictDataDTO> getTtsVcnDict() {
        return dictService.getDictData("tts_vcn");
    }

    /**
     * 根据当前登录用户ID获取对应的客服
     * 用于对话前端自动匹配客服
     *
     * @return 客服配置，如果没有找到则返回null
     */
    @GetMapping("/agent/my")
    public Map<String, Object> getMyAgent() {
        try {
            Long userId = LoginHelper.getUserId();
            TalkAgentVo agent = talkAgentService.queryByUserId(userId);
            if (agent != null) {
                return Map.of("code", 200, "data", agent);
            } else {
                return Map.of("code", 404, "msg", "未找到对应的客服");
            }
        } catch (Exception e) {
            log.error("获取当前用户客服失败", e);
            return Map.of("code", 500, "msg", "获取客服失败: " + e.getMessage());
        }
    }

    /**
     * 更新客服配置
     * 用于对话前端在开始对话时更新客服的TTS配置和状态
     *
     * @param id 客服ID
     * @param bo 客服配置参数，包含：
     *           - ttsSpeed: TTS语速
     *           - ttsPitch: TTS音调
     *           - ttsVolume: TTS音量
     *           - ttsBgs: TTS背景音开关
     *           - status: 客服状态（2=对话中）
     * @return 更新结果
     */
    @PutMapping("/agent/{id}")
    public Map<String, Object> updateAgentConfig(@PathVariable Long id, @RequestBody TalkAgentBo bo) {
        bo.setId(id);
        boolean success = talkAgentService.updateByBo(bo);
        return Map.of("success", success);
    }

    /**
     * 开始对话（通用接口）
     * 支持普通对话和RPA对话场景
     *
     * @param id 客服ID
     * @param request 可选参数，包含customerPhone（RPA场景使用）
     * @return 开始对话结果，包含sessionId
     */
    @PostMapping("/agent/{id}/start")
    public Map<String, Object> startChat(@PathVariable Long id, @RequestBody(required = false) Map<String, String> request) {
        Long userId = 0L;
        try {
            userId = LoginHelper.getUserId();
        } catch (Exception e) {
            log.warn("获取登录用户ID失败，使用默认值", e);
        }

        String customerPhone = request != null ? request.get("customerPhone") : null;
        return chatService.startChatSession(id, userId, customerPhone);
    }

    /**
     * 挂断电话
     * 用户挂断电话后，更新会话结束时间并将客服状态改回0（正常）
     *
     * @param id      客服ID
     * @param request 包含sessionId与chatHistory数组的请求体
     * @return 更新结果
     */
    @PostMapping("/agent/{id}/hangup")
    public Map<String, Object> hangupCall(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        String sessionId = (String) request.get("sessionId");
        List<Map<String, Object>> chatHistory = (List<Map<String, Object>>) request.get("chatHistory");

        boolean success = chatService.hangupCall(id, sessionId, chatHistory);
        return Map.of("success", success);
    }

    /**
     * 流式处理用户消息
     * 使用SSE实时推送文本和音频数据
     *
     * @param request 请求参数
     */
    @PostMapping("/message/stream")
    public SseEmitter handleMessageStream(@RequestBody MessageStreamRequest request) {
        log.info("收到流式消息请求: {}, 客服ID: {}, 对话ID: {}, 请求ID: {}, 客户电话: {}, 类型: {}",
            request.getMessage(), request.getAgentId(), request.getConversationId(),
            request.getRequestId(), request.getCustomerPhone(), request.getType());

        SseEmitter emitter = new SseEmitter(60000L);
        chatService.processMessageStream(
            request,
            emitter
        );
        return emitter;
    }

}
