package com.hai.config;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 百度AI开放平台，语音合成
 * @author hurui
 */
@Component
public class BaiduVoiceService {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取token
     * @return
     * @throws Exception
     */
    public String getToken() {
        Object token = redisUtil.get("baidu_voice_token");
        if (token != null) {
            return token.toString();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credentials");
        map.put("client_id", "21NEfkbyDiXVZ3kf3vI8rwOG");
        map.put("client_secret", "EyN2X1oBDERL7dwMX2WIqoZnsdtvadCC");

        // 获取token
        JSONObject tokenObject = HttpsUtils.doGet("https://aip.baidubce.com/oauth/2.0/token", map);
        if (StringUtils.isNotBlank(tokenObject.getString("access_token"))) {
            redisUtil.set("baidu_voice_token", tokenObject.getString("access_token"), tokenObject.getLong("expires_in"));
            return tokenObject.getString("access_token");
        }
        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取token失败");
    }

    /**
     * 文本转换语音
     * @param text  文本
     * @return
     * @throws Exception
     */
    public String text2audio(String text) {
        Map<String, Object> param = new HashMap<>();
        param.put("tok", this.getToken());
        param.put("tex", text);
        param.put("cuid", System.currentTimeMillis()+"");
        param.put("ctp", 1);
        param.put("lan", "zh");
        param.put("spd", 5);
        param.put("pit", 5);
        param.put("vol", 8);
        param.put("per", 5118);
        param.put("aue", 3);

        String apiUrl = "http://tsn.baidu.com/text2audio";
        StringBuffer paramStr = new StringBuffer();
        int i = 0;
        for (String key : param.keySet()) {
            if (i == 0) {
                paramStr.append("?");
            } else {
                paramStr.append("&");
                paramStr.append(key).append("=").append(param.get(key));
            }
            i++;
        }
        return apiUrl + paramStr;
    }
}
