package kami_gateway

import (
	"crypto/md5"
	"encoding/hex"
	"sort"

	"github.com/duke-git/lancet/v2/convertor"
)

func GetMD5SignMF(params map[string]any, paySecret string) string {
	strArr := SortMap(params)
	signStr := ""
	for i := range strArr {
		k := strArr[i]
		if len(convertor.ToString(params[k])) == 0 {
			signStr += k
		} else {
			signStr += k + convertor.ToString(params[k])
		}
	}
	signStr += paySecret
	return GetMd5Lower(signStr)
}

// SortMap 对map的key值进行排序
func SortMap(m map[string]any) []string {
	var arr []string
	for k := range m {
		arr = append(arr, k)
	}
	sort.Strings(arr)
	return arr
}

// SortMapByKeys 按照key的ascii值从小到大给map排序
func SortMapByKeys(m map[string]any) map[string]any {
	keys := SortMap(m)
	tmp := make(map[string]any)
	for _, key := range keys {
		tmp[key] = convertor.ToString(m[key])
	}
	return tmp
}

// GetMd5Lower 获取小写的MD5
func GetMd5Lower(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}
