package utils

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/qit-team/snow-core/redis"
	"net"
	"qteam/config"
	"runtime"
	"strconv"
	"strings"
	"time"
)

const (
	CODE62  = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	codeLen = 20
)

func GetHostIp() string {
	conn, err := net.Dial("udp", "8.8.8.8:53")
	if err != nil {
		fmt.Println("get current host ip err: ", err)
		return ""
	}
	addr := conn.LocalAddr().(*net.UDPAddr)
	ip := strings.Split(addr.String(), ":")[0]
	return ip
}
func Log(c *gin.Context, name string, msg ...interface{}) {
	_, file, line, _ := runtime.Caller(1)
	timeLayout := "2006-01-01 03:04:05" //转化所需模板
	var datetime = time.Unix(time.Now().Unix(), 0).Format(timeLayout)
	fmt.Println(name, msg, file, line, datetime)
}

func GetRealKey(key string) string {
	return config.GetConf().ServiceName + ":" + key
}

// MD5加密
func SToMd5(data string) string {
	r := md5.Sum([]byte(data))
	return hex.EncodeToString(r[:])

}

/**
 * 编码 整数 为 base62 字符串
 */
func Encode(number int64) string {
	if number == 0 {
		return "0"
	}
	result := make([]byte, 0)
	for number > 0 {
		round := number / codeLen
		remain := number % codeLen
		result = append(result, CODE62[remain])
		number = round
	}
	return string(result)
}

// 生成用户touken
func GeneratorToken(playerName string, playerId string) string {
	//去生成一个token返回给客户端
	m5 := SToMd5(playerName + time.Now().String())
	var pid, _ = strconv.ParseInt(playerId, 10, 64)
	bsCode := Encode(pid)
	tk := m5 + bsCode
	//将token放入redis
	_, err := redis.GetRedis(redis.SingletonMain).SetEX(context.Background(), GetRealKey(tk), playerId, 3600).Result()
	if err != nil {
		Log(nil, "token", err)
	}
	return tk
}
