package game

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"sync"

	"git.jiaxianghudong.com/go/logs"

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

var RdsXueLiu = "activegamexueliu"

var ChannelXueLIU = "channel_activegamexueliu"

var syncMap sync.Map

var (
	Conf      Data // 血流6红中
	ConfMs    Data // 血流免输(也叫血流8红中)
	ConfHzvs  Data // 血流2v2
	ConfXl4hz Data // 血流4红中
	ConfGb    Data // 国标免洗麻将
	ConfGbxz  Data // 国标血战麻将
)

type Data struct {
	List     []*GameXueLiu `json:"list"`
	TextList []string      `json:"text_list"`
	mu       sync.RWMutex
}

type GameXueLiu struct {
	HuType       string     `json:"hu_type"`
	BeiShu       int        `json:"bei_shu"`
	FuziData     [][]string `json:"fuzi_data"`
	Msg          string     `json:"msg"`
	FuziShowType []string   `json:"fuzi_show_type"`
}

func (d *Data) Store(version string) (err error) {

	if len(d.List) != 0 {
		marshal, _ := json.Marshal(d)
		err = rds.Redis.Set(RdsXueLiu+version, marshal, -1).Err()
		PubMessage(ChannelXueLIU, "refresh")
		logs.Infof("更新规则配置,TextList=%+v", d.TextList)
		for k, v := range d.List {
			logs.Infof("%d--list=%+v", k, *v)
		}
	} else {
		return errors.New("没有正确格式")
	}
	return err
}

func (d *Data) ReLoad(version string) error {
	Conf.mu.Lock()
	defer Conf.mu.Unlock()
	val := rds.Redis.Get(RdsXueLiu + version).Val()
	if val != "" {
		json.Unmarshal([]byte(val), d)
	}
	syncMap.Store(version, d)
	return nil
}

func (d *Data) LoadConf(version string) error {
	Conf.mu.RLock()
	defer Conf.mu.RUnlock()
	if version == "" {
		d.List = Conf.List
		d.TextList = Conf.TextList
	} else {
		load, ok := syncMap.Load(version)
		if ok {
			t := load.(*Data)
			d.List = t.List
			d.TextList = t.TextList
		}
	}
	return nil
}

func PubMessage(channel, msg string) {
	rds.Redis.Publish(channel, msg)
}

func SubMessage() {

	rds.Redis = rds.Register("redis")

	Conf.ReLoad("")
	ConfMs.ReLoad("xueliums")
	ConfHzvs.ReLoad("hzvs")
	ConfXl4hz.ReLoad("xl4hz")
	ConfGb.ReLoad("xueliugb")
	ConfGbxz.ReLoad("xueliugbxz")
	pubsub := rds.Redis.Subscribe(ChannelXueLIU)
	go func() {
		fmt.Println("配置订阅启动3")
		var receipt interface{}
		var err error
		for {
			receipt, err = pubsub.Receive()
			if err != nil {
				if strings.Contains(err.Error(), "close") {
					fmt.Println("closedd", err)
					return
				}
			}
			switch v := receipt.(type) {
			case *redis.Message: // 单个订阅subscribe
				fmt.Printf("%s: message: %s\n", v.Channel, v.Payload)
				switch v.Payload {
				case "refresh":
					Conf.ReLoad("")
					ConfMs.ReLoad("xueliums")
					ConfHzvs.ReLoad("hzvs")
					ConfXl4hz.ReLoad("xl4hz")
					ConfGb.ReLoad("xueliugb")
					ConfGbxz.ReLoad("xueliugbxz")
					break
				default:
				}
			case error:
				fmt.Println("你好")
				return
			default:
				fmt.Println("pong....")

			}
		}
	}()
}
