package cache

import (
	"dsbqj-admin/pkg/logger"
	"dsbqj-admin/pkg/util"
	"github.com/go-redis/redis"
	"os"
	"strconv"
	"sync/atomic"
	"time"
)

// RedisClient Redis缓存客户端单例
var RedisReport *redis.Client
var num int32 = 0

// Redis 在中间件中初始化redis链接
func Redis() {
	RedisReportInit()

	startListen()
}

func startListen() {
	ListenRedis("redis_report", RedisReport, RedisReportInit)
}

func RedisReportInit() {
	db, _ := strconv.ParseUint(os.Getenv("REDIS_DB"), 10, 64)
	client := redis.NewClient(&redis.Options{
		Addr:     os.Getenv("REDIS_ADDR"),
		Password: os.Getenv("REDIS_PW"),
		DB:       int(db),
	})

	_, err := client.Ping().Result()
	if err != nil {
		if num == 0 {
			panic("redis connect err")
		}
		return
	}
	logger.Info("redis 数据库连接成功 第%d次连接", num)
	RedisReport = client
}

func ListenRedis(mark string, rd *redis.Client, connect func()) {
	util.StartMinorGO("redis connect", func() {
		for {
			time.Sleep(5 * time.Second)
			_, err := rd.Ping().Result()
			if err != nil {
				num = atomic.AddInt32(&num, 1)
				logger.Info("%s---> redis client reconnect num: %d", mark, num)
				connect()
			}
		}
	}, func(isdebug bool) {})
}
