package util

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"math/big"
	"strings"
	"time"
)

func GenerateSM4Key() []byte {
	str := "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
	buffer := make([]byte, 16)
	for i := 0; i < 16; i++ {
		nextInt, _ := rand.Int(rand.Reader, big.NewInt(int64(len(str))))
		buffer[i] = str[nextInt.Int64()]
	}
	return buffer
}

func GenAccessToken(token string) string {
	if token != "" {
		return token
	}
	now := time.Now()
	return strings.ToUpper(Md5Hash(now.Format("2006A01B02CD15E04F05"), ""))
}

func Md5Hash(password, salt string) string {
	m := md5.New()
	m.Write([]byte(salt + password))
	return hex.EncodeToString(m.Sum(nil))
}

// GetSM4IV 获取SM4的IV
func GetSM4IV() []byte {
	return []byte("UISwD9fW6cFh9SNS")
}

func Padding(input []byte, mode int) []byte {
	if input == nil {
		return nil
	} else {
		var ret []byte
		if mode == 1 {
			p := 16 - len(input)%16
			ret = make([]byte, len(input)+p)
			copy(ret, input)

			for i := 0; i < p; i++ {
				ret[len(input)+i] = byte(p)
			}
		} else {
			p := input[len(input)-1]
			ret = make([]byte, len(input)-int(p))
			copy(ret, input[:len(input)-int(p)])
		}

		return ret
	}
}
