package services

import (
	"encoding/base64"
	"encoding/json"
	"eta/eta_api/models"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/crypt"
	"net/url"
	"strings"
	"time"

	"eta/eta_api/utils"
	"github.com/gorilla/websocket"
)

type XfParams struct {
	XfAPPID     string
	XfAPIKey    string
	XfAPISecret string
}

// 科大讯飞，语音合成
func GetXfVideo(body []byte, savePath string, req XfParams) (err error) {
	path, err := assembleAuthUrl(req)
	if err != nil {
		return
	}
	conn, _, err := websocket.DefaultDialer.Dial(path, nil)
	if err != nil {
		return
	}
	defer conn.Close()

	err = conn.WriteMessage(websocket.TextMessage, body)
	if err != nil {
		return
	}

	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("ReadMessage Err:" + err.Error())
			return err
		}
		item := new(models.XfReciveResult)
		err = json.Unmarshal(message, &item)
		if err != nil {
			fmt.Println("json.Unmarshal Err:" + err.Error())
			return err
		}
		if item.Code != 0 {
			goto readWebSocketFail
		}
		if item.Code == 0 && item.Data != nil {
			if item.Data.Status == 1 {
				audio := item.Data.Audio
				err = utils.SaveBase64ToFileBySeek(audio, savePath)
				if err != nil {
					fmt.Println("文件保存失败", err.Error())
					goto readWebSocketFail
				}
			} else {
				audio := item.Data.Audio
				err = utils.SaveBase64ToFileBySeek(audio, savePath)
				if err != nil {
					fmt.Println("文件保存失败", err.Error())
					goto webSocketClose
					//return
				}
				fmt.Println("goto close")
				goto webSocketClose
			}
		}
	}
readWebSocketFail:
	conn.Close()
	fmt.Println("goto readWebSocketFail")
webSocketClose:
	conn.Close()
	fmt.Println("goto webSocketClose")
	return nil
}

// @hosturl :  like  wss://iat-api.xfyun.cn/v2/iat
// @apikey : apiKey
// @apiSecret : apiSecret
func assembleAuthUrl(req XfParams) (callUrl string, err error) {
	ul, err := url.Parse(utils.XfHostUrl)
	if err != nil {
		return
	}
	//签名时间
	date := time.Now().UTC().Format(time.RFC1123)
	//参与签名的字段 host ,date, request-line
	signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"}
	//拼接签名字符串
	sign := strings.Join(signString, "\n")
	fmt.Println("sign:", sign)
	//签名结果
	sha := crypt.HmacSha256EncryptToBase64([]byte(sign), []byte(req.XfAPISecret))
	//构建请求参数 此时不需要urlencoding
	authUrl := fmt.Sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", req.XfAPIKey,
		"hmac-sha256", "host date request-line", sha)
	//将请求参数使用base64编码
	authorization := base64.StdEncoding.EncodeToString([]byte(authUrl))
	v := url.Values{}
	v.Add("host", ul.Host)
	v.Add("date", date)
	v.Add("authorization", authorization)
	//将编码后的字符串url encode后添加到url后面
	callUrl = utils.XfHostUrl + "?" + v.Encode()
	return
}
