package zhimeng

import (
	"fmt"
	"sort"
	"strconv"
	"time"

	"applet/app/utils"
)

var StatusSuc int = 1

type ZM struct {
	AK     string
	SK     string
	SMS_AK string
	SMS_SK string
}

// 智盟接口, 可以调取京东, 拼多多等
const ZM_HOST = "http://www.izhim.com/"

var (
	ZM_BASE_URL    = ZM_HOST + "?mod=api&act=%s&ctrl=%s"
	APP_KEY        = "300000001"
	SECRET_KEY     = "95c347002b2750dbd4b6a03bd4196c18"
	SMS_APP_KEY    = "300000175"
	SMS_SECRET_KEY = "6cf1dcd1820a576ff2cbecbe00d31df2"
)

func Send(act, op string, args map[string]interface{}) ([]byte, error) {
	router := fmt.Sprintf(ZM_BASE_URL, act, op)
	// args["appkey"] = APP_KEY
	args["time"] = strconv.Itoa(int(time.Now().Unix()))
	args["sign"] = sign(args, args["secret_key"].(string))
	// b, _ := json.Marshal(args)
	// fmt.Println(string(b))
	return utils.CurlPost(router, args, nil)
}

// SMSend is 发送短信用的key 和签名
func SMSend(act, op, key, secret string, args map[string]interface{}) ([]byte, error) {
	router := fmt.Sprintf(ZM_BASE_URL, act, op)
	args["appkey"] = key
	args["time"] = strconv.Itoa(int(time.Now().Unix()))
	args["sign"] = sign(args, secret)
	fmt.Println("====短信==", router, args)
	return utils.CurlPost(router, args, nil)
}

func sign(m map[string]interface{}, SK string) string {
	// key sort
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	str := ""
	for _, k := range keys {
		str += k + utils.AnyToString(m[k])
	}
	// merge string
	str = SK + str + SK + "方诺科技"
	return utils.Md5(str)
}
