class_name UserData

## 用户数据类
## 用于存储用户的基本信息

var id: String = ""
var username: String = ""
var nickname: String = ""
var email: String = ""
var phone: String = ""
var avatarUrl: String = ""
var role: int = 1
var createdAt: String = ""

# 兼容旧字段
var level: int = 1
var exp: int = 0
var createTime: int = 0

## 从字典创建 UserData 对象
static func fromDict(data: Dictionary) -> UserData:
	var userData = UserData.new()

	# 新字段（处理可能为 null 的值）
	userData.id = str(data.get("id", ""))
	userData.username = _getStringOrEmpty(data, "username")
	userData.nickname = _getStringOrEmpty(data, "nickname")
	userData.email = _getStringOrEmpty(data, "email")
	userData.phone = _getStringOrEmpty(data, "phone")
	userData.avatarUrl = _getStringOrEmpty(data, "avatar_url", _getStringOrEmpty(data, "avatarUrl"))
	userData.role = int(data.get("role", 1))
	userData.createdAt = _getStringOrEmpty(data, "created_at", _getStringOrEmpty(data, "createdAt"))

	# 兼容旧字段
	userData.level = data.get("level", 1)
	userData.exp = data.get("exp", 0)
	userData.createTime = data.get("create_time", data.get("createTime", 0))

	return userData

## 辅助方法：从字典中获取字符串，如果为 null 则返回空字符串
static func _getStringOrEmpty(data: Dictionary, key: String, defaultValue: String = "") -> String:
	var value = data.get(key, defaultValue)
	if value == null:
		return ""
	return str(value)

## 转换为字典
func toDict() -> Dictionary:
	return {
		"id": id,
		"username": username,
		"nickname": nickname,
		"email": email,
		"phone": phone,
		"avatar_url": avatarUrl,
		"role": role,
		"created_at": createdAt,
		"level": level,
		"exp": exp,
		"create_time": createTime
	}

## 打印用户信息（用于调试）
func toString() -> String:
	return "UserData(id=%s, username=%s, nickname=%s, role=%d)" % [id, username, nickname, role]
