package com.sqx.modules.utils;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.service.CommonInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@Component
public class BaiduUtils {

    @Autowired
    private CommonInfoService commonInfoService;


    public String exportMusic(String content,String per) {
        String appId = commonInfoService.findOne(809).getValue();
        String apiKey = commonInfoService.findOne(810).getValue();
        String secretKey = commonInfoService.findOne(811).getValue();

        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(appId, apiKey, secretKey);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        HashMap<String, Object> options=new HashMap<>();
        //语速，取值0-15，默认为5中语速
        options.put("spd","5");
        //音调，取值0-15，默认为5中语调
        options.put("pit","5");
        //音量，基础音库取值0-9，精品音库取值0-15，默认为5中音量（取值为0时为音量最小值，并非为无声）
//        options.put("vol","5");
        //音库
        options.put("per",per);
        // 调用接口
        byte[] data=null;
        if(content.length()>60){
            int num=content.length()/60;
            if(content.length()%60!=0){
                num++;
            }
            for(int i=0;i<num;i++){
                String contents;
                if(i==0){
                    contents=content.substring(0,60);
                }else{
                    int length=60*(i+1);
                    if(content.length()<length){
                        length=content.length();
                    }
                    contents=content.substring(i*60,length);
                }

                TtsResponse res = client.synthesis(contents, "zh", 1, options);
                org.json.JSONObject result = res.getResult();
                if(result!=null){
                    log.error("语音异常："+result.toString());
                    return null;
                }
                byte[] datas = res.getData();
                if(data==null){
                    data=datas;
                }else{
                    data=byteMerger(data,datas);
                }
            }

        }else{
            TtsResponse res = client.synthesis(content, "zh", 1, options);
            org.json.JSONObject result = res.getResult();
            if(result!=null){
                log.error("语音异常："+result.toString());
                return null;
            }
            data = res.getData();
        }
        String http = commonInfoService.findOne(19).getValue();
        String[] split = http.split("://");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName=sdf.format(new Date())+String.valueOf((int) ((Math.random() * 9 + 1) * 100000))+".mp3";
        // 上传文件路径
        String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath/ordersMusic/"+fileName;
        File file = new File(filePath);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (data != null) {
            try {
                Util.writeBytesToFileSystem(data, filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return http + "/file/uploadPath/ordersMusic/"+fileName;
    }

    public static byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length+bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }

}
