package redisdata

import (
	"encoding/json"
	"fmt"
	"oppmg/common/log"
	"oppmg/common/redis"
	"oppmg/protocol"
	"strings"
	"time"
)

func SetLoginToken(param protocol.LoginAuthToken, userid int64, companyid int64) error {
	client := redis.GetRedis()
	var (
		key     string
		value   []byte
		err     error
		exp     int64
		nowTime = time.Now().Unix()
	)
	data := RedisLoginToken{
		AccessToken:    param.AccessToken,
		RefreshToken:   param.RefreshToken,
		CurrentCompany: companyid,
	}
	value, _ = json.Marshal(data)
	exp = param.RefreshExpires - nowTime
	key = fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
	err = client.Set(key, string(value), time.Duration(exp)*time.Second).Err()
	return err
}

func GetLoginToken(userid int64) (RedisLoginToken, error) {
	client := redis.GetRedis()
	var (
		key    string
		value  string
		err    error
		result RedisLoginToken
	)
	key = fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
	value, err = client.Get(key).Result()
	if err != nil {
		return result, err
	}
	value = strings.TrimSpace(value)
	err = json.Unmarshal([]byte(value), &result)
	if err != nil {
		log.Error("Unmarshal redis value:%s err:%s", value, err)
		return result, err
	}
	return result, nil
}

func ExistLoginToken(userid int64) bool {
	client := redis.GetRedis()
	key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
	value := client.Exists(key).Val()
	if value > 0 {
		return true
	}
	return false
}

func DeleteLoginToken(userid int64) error {
	client := redis.GetRedis()
	key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
	err := client.Del(key).Err()
	return err
}

//   刷新token 的有效期
func RefreshLoginTokenExpires(userid int64) error {
	client := redis.GetRedis()
	key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
	result, err := client.Exists(key).Result()
	if err != nil {
		return err
	}
	if result == 0 {
		return nil
	}
	_, err = client.Expire(key, 30*time.Minute).Result()
	if err != nil {
		return err
	}
	return nil
}

//消息发布订阅