package shop.alien.store.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
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.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.store.util.ai.AiFeedbackAssignUtils;

@Slf4j
@Api(tags = {"ai语音识别"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/aiUp")
@RequiredArgsConstructor
public class AiUploadController {
    private final AiFeedbackAssignUtils aiFeedbackAssignUtils;
    @ApiOperation("AI语音识别")
    @ApiOperationSupport(order = 1)
    @PostMapping("/GetAIUpload")
    public R<JSONObject> getAiUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "language", required = false) String language,
            @RequestParam(value = "use_itn", required = false) String use_itn,
            @RequestParam(value = "merge_vad", required = false) String merge_vad) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return R.fail("音频文件不能为空");
        }
        
        try {
            String speechRecognitionResult = aiFeedbackAssignUtils.getSpeechRecognition1(file, null, language, use_itn, merge_vad);
            if (speechRecognitionResult == null) {
                return R.fail("语音识别失败");
            }
            // 将返回的JSON字符串解析为JSONObject
            JSONObject result = JSONObject.parseObject(speechRecognitionResult);
            return R.data(result);
        } catch (RuntimeException e) {
            log.error("语音识别失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("语音识别异常", e);
            return R.fail("语音识别失败: " + e.getMessage());
        }
    }
}
