package collect

import (
	"fmt"
	collectCfg "server/conf/collect"
	"server/game/mod/item"
	GoUtil "server/game_util"
	"server/msg"
)

type Collect struct {
	Reward  []int // 已领取记录
	Jackpot []int // 奖池
}

type CollectInfo struct {
	List map[int]int
}

const (
	COLLECT_TYPE_EMOJI  = 1
	COLLECT_TYPE_FACE   = 2
	COLLECT_TYPE_AVATAR = 3

	jackpotPreviewSize = 18 // 展示的奖池预览数量，同时作为补充阈値
)

func (c *Collect) InitData() {
	if c.Reward == nil {
		c.Reward = make([]int, 0)
	}
	if len(c.Jackpot) == 0 {
		c.Jackpot = initJackpot()
	}
	c.ensureJackpot()
}

// ensureJackpot 当奖池剩余少于预览数量时自动补充
func (c *Collect) ensureJackpot() {
	if len(c.Jackpot) <= jackpotPreviewSize {
		c.Jackpot = initJackpot2(c.Jackpot)
	}
}

// 获取收集奖励
func (c *Collect) GetReward(Id, Num int) ([]*item.Item, error) {
	// 判断是否已领取
	for _, v := range c.Reward {
		if v == Id {
			return nil, fmt.Errorf("id : %d;已领取", Id)
		}
	}
	Need := collectCfg.GetRewardNeed(Id)
	if Num < Need {
		return nil, fmt.Errorf("id : %d;收集数量不足 %d", Id, Need)
	}
	// 领取奖励
	c.Reward = append(c.Reward, Id)
	JackpotId := 0
	JackpotId, c.Jackpot = GoUtil.PopSlice(c.Jackpot)
	c.ensureJackpot()
	return collectCfg.GetJackpotItems(JackpotId), nil
}

func (c *Collect) BackData() *msg.ResCollectInfo {
	ItemsMsg := make([]*msg.CollectItem, 0, jackpotPreviewSize)
	for i := 0; i < jackpotPreviewSize; i++ {
		Items := collectCfg.GetJackpotItems(c.Jackpot[i])
		ItemsMsg = append(ItemsMsg, &msg.CollectItem{
			Id:    int32(i + 1),
			Items: item.ItemToMsg(Items),
		})
	}
	return &msg.ResCollectInfo{
		Id:    GoUtil.IntToInt32(c.Reward),
		Items: ItemsMsg,
	}
}

func initJackpot2(r1 []int) []int {
	Ids := collectCfg.GetJackpotId()
	r2 := GoUtil.ShuffleArray(Ids)
	return append(r1, r2...)
}

func initJackpot() []int {
	return initJackpot2(initJackpot2(initJackpot2(nil)))
}
