package com.ruoyi.cms.controller.app;

import com.ruoyi.common.annotation.BussinessLog;
import com.ruoyi.common.config.AudioTextRequestClient;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;

import static com.ruoyi.common.enums.BusinessType.OTHER;

/**
 * app语音Controller
 * 
 * @author lishundong
 * @date 2024-09-03
 */
@RestController
@RequestMapping("/app/speech")
@Api(tags = "移动端:用户相关")
public class AppSpeechController extends BaseController
{
    /*private String appKey = "4lFYn2yPsQymwGu8";
    private String id = "LTAI5t9hhSqdDHqwH3RjgyYj";
    private String secret = "ni5aW3vxrWouMwcGqJPfh9Uu56PBuv";
    private String url = System.getenv().getOrDefault("NLS_GATEWAY_URL", AliyunNlsUtils.getNlsUrl()+"/ws/v1/");*/

    @Autowired
    AudioTextRequestClient audioTextRequestClient;

    @BussinessLog(title = "语音转文字",businessType = OTHER)
    @ApiOperation("语音转文字")
    @PostMapping(value = "/asr")
    public AjaxResult asr(@RequestParam("file") MultipartFile file){
        try {
            return AjaxResult.success("请求成功",audioTextRequestClient.getTextFromAudioFile(file));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @BussinessLog(title = "文字转语音",businessType = OTHER)
    @ApiOperation("文字转语音")
    @GetMapping(value = "/tts")
    public ResponseEntity<byte[]> tts(@RequestParam("text") String text) throws UnsupportedEncodingException {
        byte[] wavData = audioTextRequestClient.getAudioInputStreamFromText(text);
        HttpHeaders headers = new HttpHeaders();
        // WAV音频的标准MIME类型
        headers.setContentType(MediaType.parseMediaType("audio/wav"));
        // inline：让浏览器在线播放（而非下载）
        headers.setContentDispositionFormData("inline", System.currentTimeMillis() + ".wav");
        // 设置内容长度
        headers.setContentLength(wavData.length);
        // 4. 返回音频数据
        return new ResponseEntity<>(wavData, headers, HttpStatus.OK);
    }

    /*@ApiOperation("统计")
    @GetMapping("/getToken")
    public AjaxResult getToken()
    {
        SpeechRecognizerAI recognizerDemo = new SpeechRecognizerAI(appKey, id, secret, url);
        AccessToken accessToken = recognizerDemo.getAccessToken();
        String token = AliyunNlsUtils.getNlsUrl()+"/ws/v1/?appkey="+appKey+"&token="+accessToken.getToken();
        return AjaxResult.success(token);
    }*/
}
