package com.gxwebsoft.common.core.controller;

import com.gxwebsoft.common.core.utils.AliyunTranslateUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 翻译控制器
 * 提供文本翻译和批量翻译功能
 */
@Slf4j
@Tag(name = "翻译管理")
@RestController
@RequestMapping("/api/translate")
public class TranslateController extends BaseController {

    @Resource
    private AliyunTranslateUtil translateUtil;

    @Operation(summary = "单文本翻译")
    @PostMapping("/text")
    public ApiResult<TranslateResponse> translateText(@RequestBody TranslateRequest request) {
        try {
            String translated = translateUtil.translate(
                    request.getText(),
                    request.getTargetLang(),
                    request.getSourceLang() != null ? request.getSourceLang() : "auto"
            );

            TranslateResponse response = new TranslateResponse();
            response.setSourceText(request.getText());
            response.setTranslatedText(translated);
            response.setSourceLang(request.getSourceLang());
            response.setTargetLang(request.getTargetLang());

            return success("翻译成功", response);
        } catch (Exception e) {
            log.error("翻译失败", e);
            return new ApiResult<>(1, "翻译失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量翻译")
    @PostMapping("/batch")
    public ApiResult<BatchTranslateResponse> batchTranslate(@RequestBody BatchTranslateRequest request) {
        try {
            log.info("收到批量翻译请求: {}", request);

            // 参数校验
            if (request.getTexts() == null || request.getTexts().isEmpty()) {
                return new ApiResult<>(1, "待翻译文本列表不能为空");
            }

            if (request.getTargetLang() == null || request.getTargetLang().isEmpty()) {
                return new ApiResult<>(1, "目标语言不能为空");
            }

            List<TranslateResponse> results = new ArrayList<>();

            for (String text : request.getTexts()) {
                if (text == null || text.trim().isEmpty()) {
                    continue; // 跳过空文本
                }

                String translated = translateUtil.translate(
                        text,
                        request.getTargetLang(),
                        request.getSourceLang() != null ? request.getSourceLang() : "auto"
                );

                TranslateResponse response = new TranslateResponse();
                response.setSourceText(text);
                response.setTranslatedText(translated);
                response.setSourceLang(request.getSourceLang());
                response.setTargetLang(request.getTargetLang());

                results.add(response);
            }

            BatchTranslateResponse batchResponse = new BatchTranslateResponse();
            batchResponse.setResults(results);
            batchResponse.setTotal(results.size());

            return success("批量翻译成功", batchResponse);
        } catch (Exception e) {
            log.error("批量翻译失败，请求参数: {}", request, e);
            return new ApiResult<>(1, "批量翻译失败: " + e.getMessage());
        }
    }

    /**
     * 单文本翻译请求
     */
    @Data
    public static class TranslateRequest {
        @Parameter(description = "待翻译文本")
        private String text;

        @Parameter(description = "目标语言（如：en, zh, ja, ko）")
        private String targetLang;

        @Parameter(description = "源语言（如：zh, en, auto）默认auto自动检测")
        private String sourceLang;
    }

    /**
     * 批量翻译请求
     */
    @Data
    public static class BatchTranslateRequest {
        @Parameter(description = "待翻译文本列表")
        private List<String> texts;

        @Parameter(description = "目标语言（如：en, zh, ja, ko）")
        private String targetLang;

        @Parameter(description = "源语言（如：zh, en, auto）默认auto自动检测")
        private String sourceLang;
    }

    /**
     * 翻译响应
     */
    @Data
    public static class TranslateResponse {
        @Parameter(description = "原文")
        private String sourceText;

        @Parameter(description = "译文")
        private String translatedText;

        @Parameter(description = "源语言")
        private String sourceLang;

        @Parameter(description = "目标语言")
        private String targetLang;
    }

    /**
     * 批量翻译响应
     */
    @Data
    public static class BatchTranslateResponse {
        @Parameter(description = "翻译结果列表")
        private List<TranslateResponse> results;

        @Parameter(description = "总数")
        private Integer total;
    }
}
