package utils

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"strings"
	"testing"

	"github.com/apcera/termtables"
	"github.com/gogf/gf/v2/os/glog"
)

func TestInit(t *testing.T) {
	table := termtables.CreateTable()

	table.AddHeaders("Name", "Age")
	table.AddRow("John", "30")
	table.AddRow("Sam", 18)
	table.AddRow("Julie", 20.14)
	fmt.Println(glog.GetStack())
	fmt.Println(table.Render())
}

// SuperMaps 表示XML根节点
type SuperMaps struct {
	XMLName xml.Name `xml:"superMaps" json:"-"`
	Maps    []Map    `xml:"maps" json:"maps"`
}

// Map 表示XML中的每个地图节点
type Map struct {
	ID     string `xml:"id,attr" json:"id"`
	Name   string `xml:"name,attr" json:"name"`
	X      string `xml:"x,attr" json:"x"`
	Y      string `xml:"y,attr" json:"y"`
	Galaxy string `xml:"galaxy,attr" json:"galaxy,omitempty"`
}

func TestXml(t *testing.T) {
	// 示例XML数据
	xmlData := `<?xml version="1.0" encoding="UTF-8"?>
<superMaps>
	<maps id="1" name="传送舱" x="" y=""/>
	<maps id="4" name="船长室" x="" y=""/>
	<maps id="10 11 12 13" name="克洛斯星" galaxy="1" x="358" y="46"/>
</superMaps>`

	// 示例JSON数据
	jsonData := `{
		"maps": [
			{
				"id": "1",
				"name": "传送舱",
				"x": "",
				"y": ""
			},
			{
				"id": "4",
				"name": "船长室",
				"x": "",
				"y": ""
			},
			{
				"id": "10 11 12 13",
				"name": "克洛斯星",
				"galaxy": "1",
				"x": "358",
				"y": "46"
			}
		]
	}`

	// 1. 解析XML并转换为JSON
	fmt.Println("=== XML 到 JSON ===")
	superMaps := &SuperMaps{}
	err := xml.Unmarshal([]byte(xmlData), superMaps)
	if err != nil {
		fmt.Printf("解析XML失败: %v\n", err)
		return
	}

	jsonOutput, err := json.MarshalIndent(superMaps, "", "  ")
	if err != nil {
		fmt.Printf("转换为JSON失败: %v\n", err)
		return
	}
	fmt.Println(string(jsonOutput))

	// 2. 解析JSON并转换为XML
	fmt.Println("\n=== JSON 到 XML ===")
	newSuperMaps := &SuperMaps{}
	err = json.Unmarshal([]byte(jsonData), newSuperMaps)
	if err != nil {
		fmt.Printf("解析JSON失败: %v\n", err)
		return
	}

	xmlOutput, err := xml.MarshalIndent(newSuperMaps, "", "  ")
	if err != nil {
		fmt.Printf("转换为XML失败: %v\n", err)
		return
	}
	// 添加XML声明
	xmlWithHeader := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlOutput)
	fmt.Println(string(xmlWithHeader))

	// 3. 解析复杂ID的XML并处理
	fmt.Println("\n=== 解析复杂ID的XML ===")
	parseComplexID(xmlData)
}

// 解析复杂ID的XML并处理
func parseComplexID(xmlData string) {
	superMaps := &SuperMaps{}
	err := xml.Unmarshal([]byte(xmlData), superMaps)
	if err != nil {
		fmt.Printf("解析XML失败: %v\n", err)
		return
	}

	// 处理每个地图项
	for _, m := range superMaps.Maps {
		// 处理包含多个ID的情况
		if strings.Contains(m.ID, " ") {
			ids := strings.Fields(m.ID)
			fmt.Printf("地图名称: %s, 拆分后的ID: %v\n", m.Name, ids)
		} else {
			fmt.Printf("地图名称: %s, ID: %s\n", m.Name, m.ID)
		}
	}
}
