package face_check

import (
	zhios_third_party_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/utils"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"sort"
	"time"
)

func Send(url string, appKey, appSecret string, arg, HeaderArr map[string]string) (string, error) {

	sign := Sign(url, arg, "POST", appKey, appSecret, HeaderArr)
	HeaderArr["X-Ca-Signature"] = sign
	domain := "https://zfah.market.alicloudapi.com"
	post, err := zhios_third_party_utils.CurlPost(domain+url, arg, HeaderArr)
	if err != nil {
		return "", err
	}
	if post == nil {
		return "", errors.New("获取数据失败")
	}
	fmt.Println(post)
	fmt.Println(err)
	return string(post), nil

}
func Sign(url string, arg map[string]string, HTTPMethod, appKey, appSecret string, header map[string]string) string {
	headerStr := make([]string, 0)
	for k := range header {
		headerStr = append(headerStr, k)
	}
	sort.Strings(headerStr)
	str := HTTPMethod + "\n"
	str += header["Accept"] + "\n"
	str += header["Content-MD5"] + "\n"
	str += header["Content-Type"] + "\n"
	str += header["Date"] + "\n"
	var filter = []string{"X-Ca-Signature", "X-Ca-Signature-Headers", "Accept", "Content-MD5", "Content-Type", "Date"}
	for _, v := range headerStr {
		if zhios_third_party_utils.InArr(v, filter) {
			continue
		}
		str += v + ":" + header[v] + "\n"
	}
	pathStr := ""
	argStr := make([]string, 0)
	for k := range arg {
		argStr = append(argStr, k)
	}
	sort.Strings(argStr)
	for _, v := range argStr {
		if pathStr == "" {
			pathStr += "?" + v + "=" + arg[v]
		} else {
			pathStr += "&" + v + "=" + arg[v]
		}
	}
	str += url + pathStr
	fmt.Println(str)
	hmacSHA256 := GenHmacSha256(str, appSecret)
	fmt.Println(hmacSHA256)
	return hmacSHA256
}

func GenHmacSha256(message string, secret string) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(message))
	//sha := hex.EncodeToString(h.Sum(nil))
	//fmt.Printf("sha:%s\n", sha)
	return Base64UrlSafeEncode(h.Sum(nil))
}

func Base64UrlSafeEncode(source []byte) string {
	byteArr := base64.StdEncoding.EncodeToString(source)
	return byteArr
}
func Header(appKey string) map[string]string {
	headers := map[string]string{
		"Accept":                 "application/json; charset=utf-8",
		"X-Ca-Key":               appKey,
		"X-Ca-Nonce":             zhios_third_party_utils.RandNum(),
		"X-Ca-Signature-Method":  "HmacSHA256",
		"X-Ca-Timestamp":         zhios_third_party_utils.Int64ToStr(time.Now().Unix() * 1000),
		"X-Ca-Signature-Headers": "X-Ca-Key,X-Ca-Nonce,X-Ca-Signature-Method,X-Ca-Timestamp",
	}
	return headers
}