package Account

import (
	"Cold_Data/conf"
	"Cold_Data/logs"
	"fmt"
	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
	uuid "github.com/satori/go.uuid"
	"time"
)

var redisCache_Tokey cache.Cache

func init() {
	//注册模型
	//orm.RegisterModel(new(Tokey))

	config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
		"redis_User_Tokey", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
	var err error
	redisCache_Tokey, err = cache.NewCache("redis", config)
	if err != nil || redisCache_Tokey == nil {
		errMsg := "failed to init redis"
		logs.PrintlnError(errMsg, err)
	}
}

// ---------------- Redis -------------------
// Redis_Set(m.T_sn,m) // Redis 更新缓存
func Add_Tokey_Set(Uuid string) string {
	var Tokey string
	for true {
		Tokey = uuid.NewV4().String()
		if !redisCache_Tokey.IsExist(Tokey) {
			break
		}
		fmt.Print("申请 TOKEY 重复！重新生成。", Tokey)
	}
	redisCache_Tokey.Put(Tokey, Uuid, 2*time.Hour)

	return Tokey
}

// if r,is :=Redis_Get(T_sn);is{
// return r,nil
// }
func Redis_Tokey_Get(Tokey string) (string, bool) {
	if len(Tokey) < 10 {
		return "", false
	}
	if redisCache_Tokey.IsExist(Tokey) {
		//println("找到key:",key)
		v := redisCache_Tokey.Get(Tokey)
		value := string(v.([]byte)) //这里的转换很重要，Get返回的是interface

		redisCache_Tokey.Put(Tokey, value, 2*time.Hour) //  重新计次
		return value, true
	}
	//println("没有 找到key:",key)
	return "", false
}
