package model

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

	"active/constant"
	"active/internal/model/scratchcard"

	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/rds"
	"github.com/go-redis/redis"
)

// GetAllActiceByType 活动数据
func GetAllActiceByType(activeType string) ActiveSwitchAll {
	// 先读取缓存
	if data, ok := ActiveCache.Load("AllActive"); ok {
		if v, ok := data.(map[string]ActiveSwitchAll)[activeType]; ok {
			logs.Info("get AllActive by cahce!")
			return v
		}
	}

	var activeSwitchModel ActiveSwitchAll
	am, _ := activeSwitchModel.Get(activeType)
	if am.ID == "" {
		return am
	}

	c := map[string]ActiveSwitchAll{}
	c[activeType] = am
	ActiveCache.Store("AllActive", c)

	return am
}

// GetAllActice  数据缓存
func GetAllActice() []ActiveSwitchAll {
	// 先读取缓存
	if data, ok := ActiveCacheArr.Load("AllActiveArr"); ok {
		return data.([]ActiveSwitchAll)
	}

	od, err := GetActiveSwitch()
	if err != nil {
		return od
	}

	logs.Info("Set AllActiveArr cahce success!")
	ActiveCacheArr.Store("AllActiveArr", od)
	return od
}

// SubRedisConfig 运行时配置订阅
func SubRedisConfig() {
	r := rds.Register("redis8")
	_, err := r.Ping().Result()
	if err != nil {
		fmt.Println("配置订阅错误", err)
	}
	// 监听test频道
	pubSub := r.Subscribe(constant.SUBACTOPIC)
	// 订阅
	go func() {
		fmt.Println("配置订阅启动4")
		var receipt interface{}
		var err error
		for {
			receipt, err = pubSub.Receive()
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println("配置订阅消息来了2")
			switch v := receipt.(type) {
			case *redis.Message: // 单个订阅subscribe
				fmt.Printf("%s: message: %s\n", v.Channel, v.Payload)
				switch v.Payload {
				case "AllActive":
					// 清除内容
					ActiveCache.Delete("AllActive")
					ActiveCacheArr.Delete("AllActiveArr")
					atomic.CompareAndSwapInt32(&rebateExpireAt, 1, 0)
					atomic.CompareAndSwapInt32(&invitebeanExpireAt, 1, 0)
					atomic.CompareAndSwapInt32(&scratchcard.ScratchCard, 1, 0)
					// 添加上传更新piggybank函数
					if constant.PiggyBank {
						sleep := rand.Int() % 1000
						time.Sleep(time.Duration(sleep) * time.Millisecond)
						val := rds.Redis.Get("piggybanksend_lock").Val()
						if val == "" {
							rds.Redis.Set("piggybanksend_lock", time.Now().Unix(), 30*time.Second)
							PubPiggyBankConf()
						}
					}
					fmt.Println("AllActive,内容订阅完毕")
					break
				default:
				}
			case error:
				fmt.Println("你好")
				return
			default:
				fmt.Println("pong....")

			}
		}
	}()
}
