package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.TtsRequestLog;
import com.rj.mapper.TtsRequestLogMapper;
import com.rj.service.ITtsRequestLogService;
import com.rj.dto.AsrRequest;
import com.rj.dto.AsrResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * TTS请求日志控制器
 * 
 * @author rj
 * @date 2025-01-02
 */
@Slf4j
@RestController
@RequestMapping("/api/tts/log")
@Tag(name = "TTS请求日志", description = "音频合成，TTS请求日志管理接口")
public class TtsRequestLogController {
    
    @Autowired
    private ITtsRequestLogService ttsRequestLogService;
    
    @Autowired
    private TtsRequestLogMapper ttsRequestLogMapper;
    
    @GetMapping("/list")
    @Operation(summary = "查询TTS请求日志列表", description = "分页查询TTS请求日志")
    public ResponseEntity<Map<String, Object>> getTtsRequestLogs(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "音乐名称") @RequestParam(required = false) String audioName,
            @Parameter(description = "状态") @RequestParam(required = false) String status,
            @Parameter(description = "模型") @RequestParam(required = false) String model,
            @Parameter(description = "创建人姓名") @RequestParam(required = false) String creatorName,
            @Parameter(description = "创建人电话") @RequestParam(required = false) String creatorPhone,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
        
        Map<String, Object> result = new HashMap<>();

        try {
            Page<TtsRequestLog> page = new Page<>(pageNum, pageSize);
            QueryWrapper<TtsRequestLog> queryWrapper = new QueryWrapper<>();
            
            // 添加查询条件
            if (audioName != null && !audioName.trim().isEmpty()) {
                queryWrapper.like("audio_name", audioName);
            }
            if (status != null && !status.trim().isEmpty()) {
                queryWrapper.eq("status", status);
            }
            if (model != null && !model.trim().isEmpty()) {
                queryWrapper.like("model", model);
            }
            if (creatorName != null && !creatorName.trim().isEmpty()) {
                queryWrapper.like("creator_name", creatorName);
            }
            if (creatorPhone != null && !creatorPhone.trim().isEmpty()) {
                queryWrapper.like("creator_phone", creatorPhone);
            }
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryWrapper.ge("request_time", startTime);
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                queryWrapper.le("request_time", endTime);
            }
            
            // 按请求时间倒序排列
            queryWrapper.orderByDesc("update_time");
            
            // 执行查询
            Page<TtsRequestLog> pageResult = ttsRequestLogMapper.selectPage(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pageNum", pageResult.getCurrent());
            result.put("pageSize", pageResult.getSize());
            result.put("pages", pageResult.getPages());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("查询TTS请求日志失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询TTS请求日志", description = "根据ID查询TTS请求日志详情")
    public ResponseEntity<Map<String, Object>> getTtsRequestLogById(
            @Parameter(description = "日志ID") @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            TtsRequestLog requestLog = ttsRequestLogService.getTtsRequestLogById(id);
            
            if (requestLog != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", requestLog);
            } else {
                result.put("success", false);
                result.put("message", "日志不存在");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("查询TTS请求日志失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @GetMapping("/statistics")
    @Operation(summary = "TTS请求统计", description = "获取TTS请求统计信息")
    public ResponseEntity<Map<String, Object>> getTtsStatistics() {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里可以添加统计查询逻辑
            // 例如：总请求数、成功数、失败数、平均处理时间等
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", new HashMap<>());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取TTS统计信息失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @PostMapping("/speech-to-text")
    @Operation(summary = "语音转文本", description = "将语音文件转换为文本")
    public ResponseEntity<AsrResponse> speechToText(
            @Parameter(description = "语音转文本请求参数") @RequestBody AsrRequest request) {
        
        try {
            if (!ttsRequestLogService.isAsrServiceAvailable()) {
                return ResponseEntity.status(500).body(AsrResponse.error("ASR服务不可用，请检查配置"));
            }
            
            AsrResponse response = ttsRequestLogService.speechToText(request);
            
            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(500).body(response);
            }
            
        } catch (Exception e) {
            log.error("语音转文本失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(AsrResponse.error("语音转文本失败: " + e.getMessage()));
        }
    }
}
