package broadcast

import (
	"encoding/json"
	"sort"
	"sync"

	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/rds"
	"git.jiaxianghudong.com/webs/pkg/xgorm"
)

var BroadcastConf = &Config{}
var SnipeAnchorConf = &SnipeAnchorConfig{}
var KSGDMJYJYConf = &ksgdmjyjy{}

type ksgdmjyjy struct {
	Award []awardConf
	Codes map[string]string
}

type awardConf struct {
	RangeMin int `json:"range_min" yaml:"range_min"` // 区间下限
	RangeMax int `json:"range_max" yaml:"range_max"` // 区间上限
	Weight   int `json:"weight" yaml:"weight"`       // 权重
}
type Config struct {
	Award          [][]int64 `json:"award" yaml:"award"`
	MahjongEndGame struct {
		Interval    int         `json:"interval" yaml:"interval"`       // 生成间隔
		PreGenerate int         `json:"pregenerate" yaml:"pregenerate"` // 预生成数量
		Token       string      `json:"token" yaml:"token"`             // 接口鉴权 token
		Rewards     []awardConf `json:"rewards" yaml:"rewards"`         // 奖励配置
	} `json:"mahjong_endgame" yaml:"mahjong_endgame"` // 麻将残局配置
	BattleAwards     []awardConf `json:"battle_awards" yaml:"battle_awards"`         // 挑战赛兑换码奖励配置
	GuangDongMahjong []awardConf `json:"guangdong_mahjong" yaml:"guangdong_mahjong"` // 广东麻将兑换码奖励配置
	GuiZhouMahjong   []awardConf `json:"guizhou_mahjong" yaml:"guizhou_mahjong"`     // 贵州麻将兑换码奖励配置

	WL5555 struct {
		ActiveName string    `json:"active_name"  yaml:"active_name"`
		ExpireTime string    `json:"expire_time"  yaml:"expire_time"`
		Award      [][]int64 `json:"award" yaml:"award"`
	} `json:"wl5555" yaml:"wl5555"`
}

// 狙击主播配置
type SnipeAnchorConfig struct {
	FailBeans  int32                  `yaml:"fail_beans"` //狙击失败后赠送的豆豆数
	MaxCount   int32                  `yaml:"max_count"`  //狙击最大次数
	Anchorlist SnipeAnchorList        `yaml:"anchorlist"` //主播列表
	Anchors    map[int32]*SnipeAnchor // 按key归类的主播
}

type SnipeAnchor struct {
	UserID      int32  `yaml:"userid"`    //主播游戏ID
	Sort        int32  `yaml:"sort"`      //排序，值越小越靠前
	Starttime   int32  `yaml:"starttime"` //每天开播时间，小时*3600 秒
	Endtime     int32  `yaml:"endtime"`   //每天下播时间, 小时*3600 秒
	EndLiveTime int32  // 下播时间戳
	Game        int32  `yaml:"game"`      //默认播的游戏，实际根据主播进入的游戏动态更新
	PlayMode    string `yaml:"play_mode"` //默认播的游戏玩法，实际根据主播进入的玩法动态更新
	Bewin       int64  `yaml:"bewin"`     //默认可以被褥的豆豆数，实际会根据主播身上的豆豆数更新
	Isused      int32  `yaml:"isused"`    //是否启用，0-不启用，1-启用
	IsOnline    int32  //是否在线，0-离线，1-在线
}

var (
	//BroadcastIdMaps = make(map[int64]bool)
	//RecommendMaps   = make(map[string][]*BroadcastShower)
	syncs sync.Mutex
)

// 手动排序，按sort排序
type SnipeAnchorList []*SnipeAnchor

func (s SnipeAnchorList) Len() int      { return len(s) }
func (s SnipeAnchorList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SnipeAnchorList) Less(i, j int) bool {
	return s[i].Sort < s[j].Sort
}

func Init() {
	sort.Sort(SnipeAnchorConf.Anchorlist)
	SnipeAnchorConf.Anchors = make(map[int32]*SnipeAnchor)
	for _, v := range SnipeAnchorConf.Anchorlist {
		SnipeAnchorConf.Anchors[v.UserID] = v
		logs.Infof("狙击主播配置：%+v", *v)
	}
}

func LoadBroadcastId() map[string][]*BroadcastShower {

	recommendMaps := make(map[string][]*BroadcastShower)
	valBraodcastIdMap := rds.Redis.Get("broadcast_BroadcastIdMaps").Val()
	valRecommendMaps := rds.Redis.Get("broadcast_RecommendMaps").Val()
	if valBraodcastIdMap == "" || valRecommendMaps == "" {
		syncs.Lock()
		xdb := xgorm.NewConn(BroadcastGorm)
		var list = make([]*BroadcastShower, 0)
		xdb.Table("broadcast_shower").Find(&list)
		for i := range list {
			_, result := recommendMaps[list[i].GameShortName]
			if !result {
				recommendMaps[list[i].GameShortName] = make([]*BroadcastShower, 0)
			}
			recommendMaps[list[i].GameShortName] = append(recommendMaps[list[i].GameShortName], list[i])
		}

		byte2, _ := json.Marshal(recommendMaps)

		rds.Redis.Set("broadcast_RecommendMaps", byte2, -1)
		syncs.Unlock()
	} else {

		json.Unmarshal([]byte(valRecommendMaps), &recommendMaps)
	}
	return recommendMaps
}
