package endless

import (
	"fmt"
	"math"
	endlessCfg "server/conf/endless"
	"server/game/mod/item"
	"server/msg"
	"sort"
)

type EndlessMod struct {
	Auto      int              // 自增id
	Id        int              // 当前领取的id
	List      map[int]*Endless // 礼包列表
	LastMoney float64          // 最后一次生成的金额
}

const (
	ENDLESS_TYPE_AD     = 1 // 广告礼包
	ENDLESS_TYPE_CHARGE = 2 // 充值礼包
	ENDLESS_TYPE_FREE   = 3 // 免费礼包
)

type Endless struct {
	ChargeId int // 充值id
	Type     int // 类型
	Items    []*item.Item
}

func (e *EndlessMod) InitData() {
	if e.List == nil {
		e.List = make(map[int]*Endless)
	}
}

// 零点更新 重置礼包
func (e *EndlessMod) ZeroUpdate(MaxMoney float64, Lv int) {
	e.List = make(map[int]*Endless)
	e.Auto = 1
	FirstMoney := 0.0
	if MaxMoney > 0 {
		m := MaxMoney / 10
		GradeList := []float64{1.99, 3.99, 5.99, 7.99, 9.99}
		type duch struct {
			Grade float64
			Num   float64
		}
		duchList := make([]duch, 0, len(GradeList))
		for _, v := range GradeList {
			duchList = append(duchList, duch{
				Grade: v,
				Num:   math.Abs(v - m),
			})
		}
		// 按照Num升序排序
		sort.Slice(duchList, func(i, j int) bool {
			return duchList[i].Num < duchList[j].Num
		})
		FirstMoney = duchList[0].Grade
		if FirstMoney == 0 {
			FirstMoney = 9.99
		}
	}

	money := FirstMoney
	for range 3 {
		e.appendGrade(money, Lv)
		money = endlessCfg.NextMoney(money)
	}
	e.Id = 1
}

// appendGrade 初始化一档礼包并合并到列表
func (e *EndlessMod) appendGrade(money float64, Lv int) {
	r, autoNext := initGrade(money, e.Auto, Lv)
	e.Auto = autoNext
	for k, v := range r {
		e.List[k] = v
	}
	e.LastMoney = money
}

// 领取免费礼包
func (e *EndlessMod) GetReward(Lv int) ([]*item.Item, error) {
	v, ok := e.List[e.Id]
	if !ok {
		return nil, fmt.Errorf("EndlessMod Reward Id:%d not found", e.Id)
	}
	if v.Type == ENDLESS_TYPE_CHARGE {
		return nil, fmt.Errorf("EndlessMod Reward Id:%d is charge", e.Id)
	}
	delete(e.List, e.Id)
	e.Id++
	if v1 := e.List[e.Id]; v1 != nil && v1.Type == ENDLESS_TYPE_CHARGE { //领完一阶段 随机新的一阶段
		e.appendGrade(endlessCfg.NextMoney(e.LastMoney), Lv)
	}
	return v.Items, nil
}

func (e *EndlessMod) BackData() *msg.ResEndless {
	r := make(map[int32]*msg.ResEndlessInfo)
	for k, v := range e.List {
		r[int32(k)] = &msg.ResEndlessInfo{
			ChargeId: int32(v.ChargeId),
			Type:     int32(v.Type),
			Items:    item.ItemToMsg(v.Items),
		}
	}
	return &msg.ResEndless{
		Id:          int32(e.Id),
		EndlessList: r,
	}
}

// 处理充值礼包
func (e *EndlessMod) Fire(ChargeId int) []*item.Item {
	v, ok := e.List[e.Id]
	if !ok {
		return nil
	}
	if v.ChargeId != ChargeId {
		return nil
	}
	delete(e.List, e.Id)
	e.Id++
	return v.Items
}
