package gome_live_show

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
	"net/http"
	"sort"
	"strings"
	"sync"
	"time"
)

var api *API

func init() {
	appKey := "N0R033L2QQFR53"
	secretKey := "686ffc3e31c24594838baed045563790"
	api = New(appKey, secretKey, "")
	//api.GetAccessToken()
	//	api.GetAccessToken()
}

func (a *API) SetToken(token string) {
	a.locker.Lock()
	defer a.locker.Unlock()
	a.sessionToken = token
}

func (a *API) GetAppKey() string {
	a.locker.Lock()
	defer a.locker.Unlock()
	return a.appKey
}

func New(appKey, appSecret, code string, config ...*platformapi.APIConfig) *API {
	curConfig := platformapi.DefAPIConfig
	if len(config) > 0 {
		curConfig = *config[0]
	}
	return &API{
		code:         code,
		appKey:       appKey,
		sign:         "",
		appSecret:    appSecret,
		refreshToken: "",
		sessionToken: "",
		expiration:   "",
		version:      "2",
		locker:       sync.RWMutex{},
		client:       &http.Client{Timeout: curConfig.ClientTimeout},
		config:       &curConfig,
	}
}

// 签名
func (a *API) signParam(params map[string]interface{}) (sig string) {
	var valueList []string
	for k, v := range params {
		if k != "sign" {
			if str := fmt.Sprint(v); str != "" {
				valueList = append(valueList, fmt.Sprintf("%s%s", k, str))
			}
		}
	}
	sort.Sort(sort.StringSlice(valueList))
	sig = strings.Join(valueList, "")
	sig = sig + "_" + a.appSecret
	data := []byte(sig)
	return strings.ToUpper(fmt.Sprintf("%x", md5.Sum(data)))
}

// 获取access_token
func (a *API) GetAccessToken() (tokenInfo *gomeToken, err error) {
	parameter := make(map[string]interface{}, 3)
	parameter["appKey"] = a.appKey
	parameter["timestamp"] = utils.Int64ToStr(time.Now().Unix())
	parameter["sign"] = a.signParam(parameter)

	// 获取token
	result, err := a.AccessAPI(gomeUrl, GetTokenApi, http.MethodPost, parameter)
	if err != nil {
		return nil, err
	}

	if err := utils.Map2StructByJson(result, &tokenInfo, false); err != nil {
		return nil, err
	}

	a.refreshToken = tokenInfo.Data.RefreshToken
	a.expiration = tokenInfo.Data.Expiration
	a.sessionToken = tokenInfo.Data.SessionToken
	return tokenInfo, err
}

func (a *API) AccessAPI(baseUrl, actionApi, method string, bizParams map[string]interface{}) (retVal map[string]interface{}, err error) {
	// 序列化
	data, err := json.Marshal(bizParams)
	if err != nil {
		return nil, err
	}

	// 全路径请求参数
	fullURL := utils.GenerateGetURL(baseUrl, actionApi, nil)

	// 发送请求
	sendUrl := func() *http.Request {
		var request *http.Request
		if http.MethodPost == method {
			request, _ = http.NewRequest(http.MethodPost, fullURL, strings.NewReader(string(data)))
		} else {
			request, _ = http.NewRequest(http.MethodGet, utils.GenerateGetURL(baseUrl, actionApi, bizParams), nil)
		}
		request.Header.Set("Content-Type", "application/json")
		return request
	}

	// 数据解析
	dataMarshal := func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
		if jsonResult1 == nil {
			return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
		}
		if err != nil {
			return "", err
		}
		if utils.MustInterface2Int64(jsonResult1["code"]) != 200 {
			errLevel = platformapi.ErrLevelGeneralFail
			err = utils.NewErrorCode(jsonResult1["message"].(string), utils.Int64ToStr(utils.MustInterface2Int64(jsonResult1["code"])))
		}
		retVal = jsonResult1
		return errLevel, err
	}

	err = platformapi.AccessPlatformAPIWithRetry(a.client, sendUrl, a.config, dataMarshal)
	return retVal, err
}

// 组装访问参数
func (a *API) MakeRequestParam(storeByte []byte) *SystemParameterReq {
	param := &SystemParameterReq{
		AuthToken: a.sessionToken,
		Timestamp: time.Now().Unix(),
		Version:   a.version,
		Sign:      "",
	}
	param.Biz = "{}"
	if storeByte != nil || len(storeByte) > 0 {
		param.Biz = string(storeByte)
	}
	mapParametersReq := utils.Struct2FlatMap(param)
	param.Sign = a.signParam(mapParametersReq)

	return param
}
