package model

import (
	"active/constant"
	"fmt"
	"strconv"
	"strings"

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

// SubGoodsConfig 定义计费点订阅
func SubGoodsConfig() {
	r := rds.Register("redis8")
	_, err := r.Ping().Result()
	if err != nil {
		fmt.Println("配置订阅错误", err)
	}
	// 监听test频道
	pubSub := r.Subscribe(constant.SUBGOODTOPIC)
	// 订阅
	go func() {
		fmt.Println("配置订阅启动1")
		var receipt interface{}
		var err error
		for {
			receipt, err = pubSub.Receive()
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println("配置订阅消息来了1")
			switch v := receipt.(type) {
			case *redis.Message: // 单个订阅subscribe
				fmt.Printf("%s: message: %s\n", v.Channel, v.Payload)
				switch v.Payload {
				case constant.GOODSKEY:
					// 清除内容
					GoodsCache.Delete(constant.GOODSKEY)
					fmt.Println(constant.GOODSKEY, ",内容订阅完毕")

				case fmt.Sprintf("jiaxiang_%s", constant.GOODSKEY):
					// 清除内容
					GoodsCache.Delete(fmt.Sprintf("jiaxiang_%s", constant.GOODSKEY))
					fmt.Println(fmt.Sprintf("jiaxiang_%s", constant.GOODSKEY), ",内容订阅完毕")

				case fmt.Sprintf("sichuan_%s", constant.GOODSKEY):
					// 清除内容
					GoodsCache.Delete(fmt.Sprintf("sichuan_%s", constant.GOODSKEY))
					fmt.Println(fmt.Sprintf("sichuan_%s", constant.GOODSKEY), ",内容订阅完毕")

				case fmt.Sprintf("ddz_%s", constant.GOODSKEY):
					// 清除内容
					GoodsCache.Delete(fmt.Sprintf("ddz_%s", constant.GOODSKEY))
					fmt.Println(fmt.Sprintf("ddz_%s", constant.GOODSKEY), ",内容订阅完毕")

				case constant.PAYBLACKLIST:
					// 清除内容
					PayBlackCache.Delete(constant.PAYBLACKLIST)
					fmt.Println(constant.PAYBLACKLIST, ",支付黑名单内容订阅完毕")
				default:
					data := strings.Split(v.Payload, ",")
					if len(data) == 2 {
						userid, _ := strconv.Atoi(data[0])
						level, _ := strconv.Atoi(data[1])
						PayBlackCacheNew.Set(userid, level)
					}
					xlog.Infof("%s 支付新黑名单内容订阅完毕 新增：%+v, 数据:%+v", constant.PAYBLACKLISTNEW, data, PayBlackCacheNew)
					break
				}
			case error:
				fmt.Println("你好")
				return
			default:
				fmt.Println("pong....")

			}
		}
	}()
}
