package com.guwan.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.guwan.config.GlobalValue;
import io.minio.MinioClient;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;


/**
 * 语音转文本1
 */
@Component

public class ToTextExample {
    private static MinioClient minioClient;
    private static RestTemplate restTemplate;
    private static GlobalValue globalValue;

    public ToTextExample(MinioClient minioClient, RestTemplate restTemplate, GlobalValue globalValue) {
        ToTextExample.minioClient = minioClient;
        ToTextExample.restTemplate = restTemplate;
        ToTextExample.globalValue = globalValue;
    }

    public static String voiceToText(String fileUrl) {
            try {
                // 从 MinIO 获取文件
                InputStream inputStream = minioClient.getObject(globalValue.getMinioBucketName(),
                        fileUrl);
                ByteArrayResource fileResource = FileUtil
                        .createByteArrayResource(IOUtils.toByteArray(inputStream),
                        fileUrl);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("file", fileResource);
                body.add("model", globalValue.getModel());
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                ResponseEntity<String> response = restTemplate
                        .postForEntity(globalValue.getTransitionApi(),
                                requestEntity, String.class);

                JSONObject result = JSONUtil.parseObj(response.getBody());
                if (result.containsKey("text")) {
                    String text = result.get("text").toString();
                    System.out.println(text);
                    return text;
                } else {
                    System.out.println("识别发生错误");
                }
            } catch (Exception e) {
                System.out.println("识别发生错误");
            }
        return "识别发生错误！";
    }

}