package model

import (
	"active/constant"
	"fmt"
	"sync"

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

// AppBannersCache 广告轮播缓存
var AppBannersCache sync.Map

// GetBanner 轮播数据
func GetBanner() []AppsBanner {
	// 先读取缓存
	if data, ok := AppBannersCache.Load("AppBanners"); ok {
		return data.([]AppsBanner)
	}

	bannerdata, err := GetBannerData()
	if err != nil {
		return bannerdata
	}

	logs.Info("Set AppBanners cahce success!")
	AppBannersCache.Store("AppBanners", bannerdata)
	return bannerdata
}

// SubAdsRedisConfig 运行时轮播广告订阅
func SubAdsRedisConfig() {
	r := rds.Register("redis8")
	_, err := r.Ping().Result()
	if err != nil {
		fmt.Println("配置订阅错误", err)
	}
	// 监听test频道
	pubSub := r.Subscribe(constant.SUBADTOPIC)
	// 订阅
	go func() {
		fmt.Println("配置订阅启动2")
		var receipt interface{}
		var err error
		for {
			receipt, err = pubSub.Receive()
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println("配置订阅消息来了3")
			switch v := receipt.(type) {
			case *redis.Message: // 单个订阅subscribe
				fmt.Printf("%s: message: %s\n", v.Channel, v.Payload)
				switch v.Payload {
				case "AppBanners":
					AppBannersCache.Delete("AppBanners")
					fmt.Println("AppBanners,内容订阅完毕")
					break
				default:
				}
			case error:
				fmt.Println("你好")
				return
			default:
				fmt.Println("pong....")

			}
		}
	}()
}
