package gm_services

import (
	"encoding/json"
	"errors"
	"gadmin/internal/admin/forms"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"os"
	"sort"
)

// 等级信息
type CharacterInfo struct {
	ID      int    `json:"ID"`
	Name    string `json:"Name"`
	Role    int    `json:"Role"`
	Star    int    `json:"Star"`
	MaxStar int    `json:"MaxStar"`
	Level   int    `json:"Level"`
}

type LevelInfo struct {
	Level int `json:"level"`
	ID    int `json:"id"`
}

type StarInfo struct {
	Star   int         `json:"star"`
	Levels []LevelInfo `json:"levels"`
}

// UpgradeRole 升级角色
func UpgradeRole(ctx *gin.Context, params forms.UpgradeRoleReq) (err error) {
	/*if params.UserId == 0 {
		return errNoUser
	}
	DB, err := player.GetDBByUserId(params.UserId)
	if err != nil {
		return
	}
	//newRoleId, err := replaceDigits(params.RoleId, params.NewRoleId)

	if err != nil {
		return err
	}
	if params.RoleId >= params.NewRoleId {
		return errors.New("升级角色匹配有误，请输入角色ID")
	}

	msg := msg2.GmUpdateRole{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		RoleID:     params.RoleId,
		NewRoleID:  params.NewRoleId,
		OperatorId: token.GetUID(ctx),
	}
	//err = gate.SendToWorld(0, &msg)
	//if err == nil {
	//
	//}
	rpc_share.MsgMap[msg.MsgId] = fmt.Sprintf("%s,GM给玩家[%d]的角色[%d]升级至[%d]",
		utility.FormatSecond(time.Now()),
		params.UserId,
		params.RoleId, params.NewRoleId)

	var resp *msg2.ResponseGmUpdateRole
	res, err := config.GmNats.GmRequest(DB, "GmUpdateRole", msg)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msg.MsgId,
		Data:  resp,
	}*/

	return

}

func GetRoleLevel(ctx *gin.Context, params forms.GetRoleLevelReq) (starInfoList []StarInfo, err error) {
	filePath := os.Getenv("ROLE_JSON")

	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		err = errors.New("无法读取JSON文件")
		return
	}

	var characters map[string]CharacterInfo
	err = json.Unmarshal(data, &characters)
	if err != nil {
		err = errors.New("Json转换失败")
		return
	}

	// 定义一个 map，用于按 Star 分组 Level 和 ID
	groupedCharacters := make(map[int]map[int][]int)
	keys := make([]string, 0, len(characters))
	for key := range characters {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	// 定义一个切片，用于存储 StarInfo
	//var starInfoList []StarInfo

	// 遍历 characters
	for _, key := range keys {
		info := characters[key]
		if info.Name == params.RoleName {
			star := info.Star
			level := info.Level
			id := info.ID

			// 初始化 map
			if _, ok := groupedCharacters[star]; !ok {
				groupedCharacters[star] = make(map[int][]int)
			}

			// 添加 Level 和 ID 到 map
			if _, ok := groupedCharacters[star][level]; !ok {
				groupedCharacters[star][level] = []int{}
			}
			groupedCharacters[star][level] = append(groupedCharacters[star][level], id)
		}
	}

	// 遍历 groupedCharacters 构建 StarInfo
	for star, levels := range groupedCharacters {
		var levelInfoList []LevelInfo

		// 获取 levels 的 key（即 level）并排序
		var levelKeys []int
		for level := range levels {
			levelKeys = append(levelKeys, level)
		}

		sort.Ints(levelKeys)

		// 遍历排序后的 level
		for _, level := range levelKeys {
			ids := levels[level]

			// 对 ids 切片进行排序
			sort.Ints(ids)

			// 构建 LevelInfo
			levelInfo := LevelInfo{
				Level: level,
				ID:    ids[0],
			}

			levelInfoList = append(levelInfoList, levelInfo)
		}

		// 构建 StarInfo
		starInfo := StarInfo{
			Star:   star,
			Levels: levelInfoList,
		}

		starInfoList = append(starInfoList, starInfo)
	}
	// 对 starInfoList 进行排序
	sort.Slice(starInfoList, func(i, j int) bool {
		return starInfoList[i].Star < starInfoList[j].Star
	})

	// 转换为 JSON 格式并打印
	//jsonData, err := json.Marshal(starInfoList)
	//if err != nil {
	//	log.Fatal("Error encoding JSON:", err)
	//	return
	//}

	return
}
