/*
 * @Descripttion:
 * @version:
 * @Author: Neo,Huang
 * @Date: 2020-11-07 16:16:27
 * @LastEditors: Neo,Huang
 * @LastEditTime: 2020-11-11 14:24:49
 */
//提交验证码管理
package models

import (
	"fmt"
	"math/rand"
	"sync"
	"time"

	"box-gm/utils"
)

var tokenRond *rand.Rand
var tokens map[string]int64
var tokenMutex sync.Mutex

func init() {
	tokenRond = rand.New(rand.NewSource(time.Now().UnixNano()))
	tokens = make(map[string]int64)
}

func GetToken() string {
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	now := time.Now().Unix()
	for {
		token := utils.Strtomd5(fmt.Sprintf("%v%v", now, tokenRond.Intn(999999)))
		_, ok := tokens[token]
		if ok {
			continue
		}
		tokens[token] = now
		return token
	}
}

func CheckToken(token string) bool {
	if token == "" {
		return false
	}
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	_, ok := tokens[token]
	return ok
}

func DelToken(token string) {
	if token == "" {
		return
	}
	tokenMutex.Lock()
	defer tokenMutex.Unlock()

	_, ok := tokens[token]
	if ok {
		delete(tokens, token)
	}

	//超过10分钟就删除
	now := time.Now().Unix()
	for k, v := range tokens {
		if now-v >= 600 {
			delete(tokens, k)
		}
	}

	return
}
