package utils

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/medivhzhan/weapp/token"
	"go.uber.org/zap"
	"math/rand"
)

func GetToken() string {
	tok, err := global.GVA_REDIS.Get(context.Background(), "wxtoken").Result()
	if err != nil || tok == "" {
		tok, exp, err := token.AccessToken(global.GVA_CONFIG.Wxxcx.Appid, global.GVA_CONFIG.Wxxcx.Secret)
		if err != nil || tok == "" {
			global.GVA_LOG.Error("获取微信token失败!", zap.Any("err", err))
			return ""
		} else {
			global.GVA_REDIS.SetEX(context.Background(), "wxtoken", tok, exp-1000)
			return tok
		}
	}
	return tok
}

var defaultLetters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

// RandomString returns a random string with a fixed length
func RandomString(n int, allowedChars ...[]rune) string {
	var letters []rune

	if len(allowedChars) == 0 {
		letters = defaultLetters
	} else {
		letters = allowedChars[0]
	}

	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}

	return string(b)
}
