package gmdata

import (
	"encoding/json"
	"fmt"
	model2 "leafstalk/covenant/model"
	"leafstalk/log"
	"os"
)

type Chapter struct {
	ID                  int64       `json:"ID"`
	Type                int         `json:"type"`
	Difficulty          int64       `json:"difficulty"`
	Name                string      `json:"name"`
	RoomCount           int32       `json:"chapter"`
	CombatEffe          int         `json:"combatEffe"`
	CombatEffeLimit     [][]float64 `json:"combatEffeLimit"`
	DailyNumber         int         `json:"dailyNumber"`
	AdRefreshSkillTimes int         `json:"adRefreshSkillTimes"`
	GoldRatio           int         `json:"goldRatio"`
	EndText             string      `json:"endText"`
	OP                  int         `json:"OP"`
	SoundID             int         `json:"SoundID"`
	UnlockSkills        []int       `json:"unlockSkills"`
	EquipNumLimit       int         `json:"EquipNumLimit"`
	ReentryLimit        int         `json:"ReentryLimit"`
}

type ChapterOptionItem struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

var (
	Chapters      []*model2.LevelListItem
	ChapterOption []*ChapterOptionItem
)

// LoadChapter 加载配置信息
func LoadChapter() {
	loadChapterFile(CurrentPath+"/"+"LevelList.json", &Chapters)

	// 根据 ID 和 Difficulty 排序，最小越靠前
	//sort.Slice(Chapters, func(i, j int) bool {
	//	if Chapters[i].ID == Chapters[j].ID {
	//		return Chapters[i].Difficulty < Chapters[j].Difficulty
	//	}
	//	return Chapters[i].ID < Chapters[j].ID
	//})

	for _, v := range Chapters {
		ChapterOption = append(ChapterOption, &ChapterOptionItem{
			Label: v.Name,
			Value: fmt.Sprintf("%v", v.Uid),
		})
	}
}

func loadChapterFile(filePath string, val interface{}) {
	ptrFile, err := os.Open(filePath)
	if err != nil {
		log.Fatalln("读取json文件失败", err)
	}
	defer ptrFile.Close()

	decoder := json.NewDecoder(ptrFile)
	if err = decoder.Decode(&val); err != nil {
		log.Fatalln("loadTreasureFile Decoder failed ", filePath, err.Error())
	}
}

func GetChaptersMap() map[string]*model2.LevelListItem {
	var data = make(map[string]*model2.LevelListItem, len(Chapters))
	for _, v := range Chapters {
		data[fmt.Sprintf("%d", v.Uid)] = v
	}
	return data
}

func GetMaxChapterForType() map[int64]int64 {
	maxChapters := make(map[int64]int64)
	for _, chapter := range Chapters {
		if _, ok := maxChapters[chapter.Type]; !ok || chapter.Uid > maxChapters[chapter.Type] {
			maxChapters[chapter.Type] = chapter.Uid
		}
	}
	return maxChapters
}

func GetChapterById(id int32) *model2.LevelListItem {
	for _, v := range Chapters {
		if v.Uid == int64(id) {
			return v
		}
	}
	return nil
}

func GetDifficultName(diff int64) string {
	if diff == 1 {
		return "困难"
	}
	if diff == 2 {
		return "噩梦"
	}
	return "普通"
}
