package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"log"
	"math"
	"net/url"
	"sort"
	"strings"
)

func MapToSortUrlEncode(paramsMap map[string]string) string {
	v := url.Values{}

	var mapKeys []string
	for k := range paramsMap {
		mapKeys = append(mapKeys, k)
	}
	sort.Strings(mapKeys)

	for k := range mapKeys {
		v.Add(mapKeys[k], paramsMap[mapKeys[k]])
	}
	body := v.Encode()
	return body
}

func Signature(appKey string, req map[string]string, secretKey string, time string) string {
	signParams := MapToSortUrlEncode(req)
	signParams = appKey + signParams + secretKey + time
	h := md5.New()
	_, err := h.Write([]byte(signParams))
	if err != nil {
		log.Printf("Write signParams %s %s", "err", err)
	}
	cipgerStr := h.Sum(nil)
	sign := strings.ToUpper(hex.EncodeToString(cipgerStr))

	return sign
}

func Decimal(value float64, num int) float64 {
	n10 := math.Pow10(num)
	value = math.Trunc((value+0.5/n10)*n10) / n10
	return value
}

func UniqueId (id int64) string {
	return fmt.Sprintf("addr-%d",id)
}