package decorate

import (
	"fmt"
	"server/GoUtil"
	decorateCfg "server/conf/decorate"
	"server/game/mod/item"
	"server/msg"
	"sort"
)

type Decorate struct {
	AreaId      int
	FinishList  map[int]struct{}
	Progress    int
	DecorateNum int
}

func (d *Decorate) InitData() {
	if d.AreaId == 0 {
		d.AreaId = 1
		d.FinishList = make(map[int]struct{})
	}
}

// 装饰
func (d *Decorate) Decorate(areaId int, decorateId int) ([]*item.Item, error) {
	if d.AreaId != areaId {
		return nil, fmt.Errorf("areaId not match")
	}
	if _, ok := d.FinishList[decorateId]; ok {
		return nil, fmt.Errorf("decorateId already finished")
	}
	SortList := decorateCfg.GetAllSortIdByAreaId(areaId)
	if !GoUtil.InArray(decorateId, SortList) {
		return nil, fmt.Errorf("decorateId not in areaId")
	}
	d.FinishList[decorateId] = struct{}{}
	d.Progress += 1
	Item := decorateCfg.GetProgressReward(areaId, d.Progress)
	if d.Progress >= len(SortList) {
		d.AreaId++
		d.Progress = 0
		d.FinishList = make(map[int]struct{})
	}
	d.DecorateNum++
	return Item, nil
}

// 获取装饰消耗
func (d *Decorate) GetDecorateCostItem(AreaId, DecorateId int) []*item.Item {
	Item := decorateCfg.GetStarCost(AreaId, DecorateId)
	return []*item.Item{item.NewItem(item.ITEM_STAR_ID, -Item)}
}

func (d *Decorate) DecorateAll(Star int) ([]*item.Item, []*item.Item, int, []int, []interface{}) {
	DecorateAll := decorateCfg.GetAllSortIdByAreaId(d.AreaId)
	SubAlice := GoUtil.SubSlices(DecorateAll, GoUtil.MapIntToIntSlice(d.FinishList))
	sort.Ints(SubAlice)
	SubItem := 0
	AddItem := make([]*item.Item, 0)
	DecorateList := make([]int, 0)
	Log := make([]interface{}, 0)
	Num := 0
	for _, v := range SubAlice {

		NeedStar := decorateCfg.GetStarCost(d.AreaId, v)
		if Star < NeedStar {
			break
		}
		Star -= NeedStar
		SubItem += NeedStar
		d.FinishList[v] = struct{}{}
		d.Progress++
		d.DecorateNum++
		Num++
		Item := decorateCfg.GetProgressReward(d.AreaId, d.Progress)
		if len(Item) > 0 {
			if d.Progress >= len(DecorateAll) {
				Log = append(Log, map[string]interface{}{
					"deco_step_id": fmt.Sprintf("%d_%d", d.AreaId+1, 0),
					"item_list":    Item,
				})
			} else {
				Log = append(Log, map[string]interface{}{
					"deco_step_id": fmt.Sprintf("%d_%d", d.AreaId, d.Progress),
					"item_list":    Item,
				})
			}

		}
		AddItem = append(AddItem, Item...)
		DecorateList = append(DecorateList, v)
	}

	if d.Progress >= len(DecorateAll) {
		d.AreaId++
		d.Progress = 0
		d.FinishList = make(map[int]struct{})
	}

	return []*item.Item{item.NewItem(item.ITEM_STAR_ID, -SubItem)}, AddItem, Num, DecorateList, Log
}

// 获取装饰信息
func (d *Decorate) BackData() *msg.ResDecorateInfo {
	return &msg.ResDecorateInfo{
		AreaId:      int32(d.AreaId),
		MFinishList: GoUtil.MapIntToSlice(d.FinishList),
	}
}

func (d *Decorate) GetAreaId() int {
	return d.AreaId
}

func (d *Decorate) GetProgress() int {
	return d.Progress
}

func (d *Decorate) GetDecorateNum() int {
	return d.DecorateNum
}
