package helper

import (
	"fmt"
	"reflect"
	"sort"
)

type KeyValue struct {
	Key   string
	Value string
}

func SortStruct(data any) []KeyValue {
	v := reflect.ValueOf(data).Elem()
	t := v.Type()
	var kv []KeyValue
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		key := LowercaseFirstLetter(t.Field(i).Name)
		value := fmt.Sprintf("%v", field.Interface())
		kv = append(kv, KeyValue{Key: key, Value: value})
	}
	sort.SliceStable(kv, func(i, j int) bool {
		return kv[i].Key < kv[j].Key
	})
	return kv
}

func SortStructJsonTag(data any) []KeyValue {
	// 获取 data 结构体的类型和值
	dataType := reflect.TypeOf(data).Elem()
	dataValue := reflect.ValueOf(data).Elem()

	var kv []KeyValue
	for i := 0; i < dataType.NumField(); i++ {
		field := dataType.Field(i)
		// 获取字段的值
		fieldValue := dataValue.FieldByName(field.Name).Interface()
		// 获取 JSON 字段名
		jsonTagName := field.Tag.Get("json")
		if jsonTagName != "" {
			kv = append(kv, KeyValue{Key: jsonTagName, Value: fmt.Sprintf("%v", fieldValue)})
		}
	}

	// 排序
	sort.SliceStable(kv, func(i, j int) bool {
		return kv[i].Key < kv[j].Key
	})

	return kv
}
