package tiktok

import (
	"crypto/md5"
	"errors"
	"fmt"
	"git.rosy.net.cn/baseapi/utils"
	"sort"
	"strings"
	"time"
)

// 获取支付签名
func (a *API) Sign(paramsMap map[string]interface{}) string {
	var paramsArr []string
	for k, v := range paramsMap {
		if k == "other_settle_params" || k == "app_id" || k == "sign" || k == "thirdparty_id " {
			continue
		}
		value := strings.TrimSpace(fmt.Sprintf("%v", v))
		if strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") && len(value) > 1 {
			value = value[1 : len(value)-1]
		}
		value = strings.TrimSpace(value)
		if value == "" || value == "nil" {
			continue
		}
		switch k {
		case "app_id", "thirdparty_id", "sign":
		default:
			paramsArr = append(paramsArr, value)
		}
	}
	if a.clientKey == TiktokJXDJAppID {
		paramsArr = append(paramsArr, salt2)
	} else {
		paramsArr = append(paramsArr, salt)
	}
	sort.Strings(paramsArr)
	return fmt.Sprintf("%x", md5.Sum([]byte(strings.Join(paramsArr, "&"))))
}

// 抖音预发单
func (a *API) CreateOrderByTicktock(param *TickTokCreateOrder) (string, string, error) {
	param.Sign = a.Sign(utils.Struct2FlatMap(param))
	data, err := a.AccessAPI2(PayUrl, utils.Struct2FlatMap(param))
	if err != nil {
		return "", "", err
	}

	result := &PreOrderResult{}
	if err := utils.Map2StructByJson(data, result, false); err != nil {
		return "", "", err
	}
	if result.ErrNo != 0 {
		return "", "", errors.New(result.ErrTips)
	}
	return result.Data.OrderId, result.Data.OrderToken, nil
}

// 获取抖音token
func (a *API) GetTiktokToken() error {
	tokenReq := make(map[string]interface{}, 3)
	tokenReq["appid"] = a.clientKey
	tokenReq["secret"] = a.clientSecret
	//tokenReq["appid"] = TiktokAppId
	//tokenReq["secret"] = TiktokSecret
	tokenReq["grant_type"] = "client_credential"
	result, err := a.AccessAPI2(GetTiktokToken, tokenReq)
	if err != nil {
		return err
	}

	accessToken := &AccessToken{}
	if err := utils.Map2StructByJson(result, accessToken, false); err != nil {
		return err
	}
	if accessToken.ErrNo != 0 {
		return errors.New(accessToken.ErrTips)
	}
	a.msgToken = accessToken.Data.AccessToken
	a.expiresIn = accessToken.Data.ExpiresIn
	return nil
}

// 检查token是否过期
func (a *API) CheckTokenIsExist() error {
	if a.msgToken == "" || time.Now().Unix() > a.expiresIn {
		return a.GetTiktokToken()
	}
	return nil
}
