package tool

import (
	"applet/app/utils"
	"applet/cloud_issuance/md"
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"time"
)

const (
	RequestUrl = "http://router.itaokecms.com/api?app_key=%s&v=1.0&format=json&sign_method=md5&method=%s&timestamp=%s&domain=%s&client=%s&partner_id=%s&sign=%s"
	AppKey     = "1091808433"
	AppSecret  = "bed35c10-ecf1-2d06-477b-f821c227198b"
	Domain     = "hairuyi.com"
	PartnerId  = "top-sdk-php-20190618"
)

func SendPost(url string, args interface{}) (data md.CurlResponse, err error) {
	utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{
		"time": time.Now().Format("2006-01-02 15:04:05.000"),
		"args": args,
		"url":  url,
	}))
	post, err := utils.CurlPost(url, utils.Serialize(args), map[string]string{})
	err = json.Unmarshal(post, &data)
	utils.FilePutContents("cloud_issuance_send", utils.SerializeStr(map[string]interface{}{
		"time": time.Now().Format("2006-01-02 15:04:05.000"),
		"resp": post,
	}))
	if err != nil {
		return
	}
	if data.Status != "0000" {
		err = errors.New(data.Msg)
		return
	}
	return data, err
}

func HttpBuild(methodName, clientIP string, params map[string]string) (httpUrl string) {
	timestamp := utils.AnyToString(time.Now().Unix())
	params["app_key"] = AppKey
	params["v"] = "1.0"
	params["format"] = "json"
	params["sign_method"] = "md5"
	params["method"] = methodName
	params["timestamp"] = timestamp
	params["domain"] = Domain
	params["client"] = clientIP
	params["partner_id"] = PartnerId
	sign := httpBuildQuery(params, true)
	sign = AppSecret + httpBuildQuery(params, true) + AppSecret
	sign = utils.MD5ToUpper32(sign)
	httpUrl = fmt.Sprintf(RequestUrl, AppKey, methodName, timestamp, Domain, clientIP, PartnerId, sign)
	return
}

func httpBuildQuery(args map[string]string, sortAsc ...bool) string {
	str := ""
	if len(args) == 0 {
		return str
	}
	if len(sortAsc) > 0 {
		keys := make([]string, 0, len(args))
		for k := range args {
			keys = append(keys, k)
		}
		if sortAsc[0] {
			sort.Strings(keys)
		} else {
			sort.Sort(sort.Reverse(sort.StringSlice(keys)))
		}
		for _, k := range keys {
			str += k + args[k]
		}
	} else {
		for k, v := range args {
			str += k + v
		}
	}
	return str
}