package friendTreasure

import (
	"fmt"
	friendTreasureCfg "server/conf/friend_treasure"
	"server/game/mod/item"
	GoUtil "server/game_util"
	"server/msg"
	"server/pkg/github.com/name5566/leaf/log"
)

type FriendTreasureMod struct {
	Star     int // 星级
	Shift    int // 挡位
	Pos      []int
	List     map[int]*msg.TreasureInfo
	List2    []int32 // 选择的好友
	Uids     []int64
	Status   int
	BoxItems []*item.Item
}

const (
	FRIEND_TYPE_ALIVE     = 1
	FRIEND_TYPE_NOT_ALIVE = 2

	GAME_STATUS_IDLE  = 0 // 未开始
	GAME_STATUS_START = 1 // 开始
	GAME_STATUS_END   = 2 // 结束
)

// 初始化数据
func (f *FriendTreasureMod) InitData() {
	if f.List == nil {
		f.List = make(map[int]*msg.TreasureInfo)
	}
}

// 零点重置
func (f *FriendTreasureMod) ZeroUpdate() {
	f.Shift = 0
	f.Pos = nil
	f.List = make(map[int]*msg.TreasureInfo)
	f.List2 = nil
	f.Uids = nil
	f.Status = GAME_STATUS_IDLE
}

// 初始化游戏数据
func (f *FriendTreasureMod) InitGame(List []*msg.TreasureInfo, List2 []int32) {
	for _, v := range List {
		f.List[int(v.Pos)] = v
	}
	f.List2 = List2
	f.Status = GAME_STATUS_START
}

// 增加星级
func (f *FriendTreasureMod) AddStar(Star int) {
	f.Star = min(200, f.Star+Star)
}

// 翻牌
func (f *FriendTreasureMod) Flip(Pos int) ([]*item.Item, int64, error) {
	if f.Status == GAME_STATUS_IDLE {
		return nil, 0, fmt.Errorf("game not start")
	}
	f.Shift++
	Info := f.List[Pos]
	Info.Status = GAME_STATUS_START
	if Info.Uid != 0 {
		log.Debug("uid:%v", Info.Uid)
		f.Uids = append(f.Uids, Info.Uid)
	}
	if Info.Type == FRIEND_TYPE_ALIVE {
		ProbMap := friendTreasureCfg.GetChestProb()
		Prob := GoUtil.RandMap(ProbMap)
		Items := friendTreasureCfg.GetChestItems(Prob)
		if Items != nil {
			f.BoxItems = append(f.BoxItems, Items...)
		}
		return Items, Info.Uid, nil
	}
	return nil, 0, nil
}

// 结束游戏
func (f *FriendTreasureMod) EndGame() ([]*item.Item, int, error) {
	if f.Status == GAME_STATUS_IDLE {
		return nil, 0, fmt.Errorf("game is over")
	}
	// f.Shift++
	ProbAdd := friendTreasureCfg.GetProbAdd(f.Shift)
	ItemNum := int(float64(f.Star) * (100.0 + float64(ProbAdd)) / 100.0)
	FriendItemNum := ItemNum / 10
	Reward := []*item.Item{
		{Id: item.ITEM_STAR_ID, Num: ItemNum},
	}
	if f.Shift == 9 {
		BigReward := friendTreasureCfg.GetBigReward()
		Reward = append(Reward, BigReward...)
	}

	return Reward, FriendItemNum, nil
}

// 重置游戏数据
func (f *FriendTreasureMod) ResetGame() {
	f.Star = 0
	f.Shift = 0
	f.Status = GAME_STATUS_END
	f.BoxItems = nil
}

func (f *FriendTreasureMod) NotifyStar() *msg.ResFriendTreasureStar {
	return &msg.ResFriendTreasureStar{
		Star: int32(f.Star),
	}
}

func (f *FriendTreasureMod) BackData() *msg.ResFriendTreasure {
	TreasureInfoList := make([]*msg.TreasureInfo, 0, len(f.List))

	for _, v := range f.List {
		TreasureInfoList = append(TreasureInfoList, v)
	}

	return &msg.ResFriendTreasure{
		Status: int32(f.Status),
		List:   TreasureInfoList,
		List2:  f.List2,
		Star:   int32(f.Star),
		Shift:  int32(f.Shift),
		Uids:   f.Uids,
	}
}
