package wxbroadcastv2

import (
	"encoding/json"
	"fmt"
	"git.jiaxianghudong.com/webs/pkg/rds"
)

var Total = 5 //限制位置

var tagMap = map[int64]string{
	0: "官方直播",
	1: "美女主播",
	2: "人气主播",
	3: "优质主播",
	4: "官方认证",
}

type Watch struct {
	Index      int    `json:"index"`
	TagUrl     string `json:"tag_url" form:"tag_url"`
	Img        string `json:"img" form:"img"`
	Nickname   string `json:"nickname" form:"nickname"`
	Uid        string `json:"uid" form:"uid"`
	IsOfficial bool   `json:"is_official" form:"is_official"`
}

type WatchConfig struct {
	WatchList []*Watch `json:"watch_list"`
}

func (w *WatchConfig) Store() error {
	marshal, _ := json.Marshal(w)
	err := rds.Redis.Set(WXBROADCASTWATCH, string(marshal), -1).Err()
	return err
}

func (w *WatchConfig) Load() {
	val := rds.Redis.Get(WXBROADCASTWATCH).Val()
	if val == "" {
		w.WatchList = make([]*Watch, Total)
		for i := range w.WatchList {
			w.WatchList[i] = &Watch{}
		}
		w.Store()
	} else {
		json.Unmarshal([]byte(val), w)
	}
	//for i := range w.WatchList {
	//	w.WatchList[i].TagUrl = tagMap[w.WatchList[i].TagId]
	//}
}

func (w *WatchConfig) StoreV2(channel, appid int32) (err error) {
	marshal, _ := json.Marshal(w)
	if channel > 0 && appid > 0 {
		err = rds.Redis.HSet(WXBROADCASTWATCHSPE, fmt.Sprintf("%v_%v", channel, appid), string(marshal)).Err()
	} else {
		err = rds.Redis.Set(WXBROADCASTWATCH, string(marshal), -1).Err()
	}
	return err
}

func (w *WatchConfig) LoadV2(channel, appid int32, reload bool) error {

	var val string
	if channel > 0 && appid > 0 {
		val = rds.Redis.HGet(WXBROADCASTWATCHSPE, fmt.Sprintf("%v_%v", channel, appid)).Val()
	}
	if (reload && val == "") || (channel == 0 && appid == 0) { //如果是旧的或者是配置通用的
		val = rds.Redis.Get(WXBROADCASTWATCH).Val()
	}

	if val != "" {
		json.Unmarshal([]byte(val), w)
	}
	if len(w.WatchList) == 0 {
		val = rds.Redis.Get(WXBROADCASTWATCH).Val()
	}

	return nil
}
