import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import '../network/api_client.dart';
import '../storage/secure_storage.dart';
import '../storage/storage_keys.dart';
import '../errors/exceptions.dart';
import '../telemetry/telemetry_service.dart';
import '../sentry/sentry_service.dart';
import 'multi_account_service.dart';

/// 设备硬件信息 (存储在 deviceName 字段中)
class DeviceHardwareInfo {
  final String? brand; // 品牌 (如 "Xiaomi")
  final String? manufacturer; // 厂商 (如 "Xiaomi")
  final String? model; // 型号 (如 "Mi 11")
  final String? device; // 设备名 (如 "venus")
  final String? product; // 产品名 (如 "venus_eea")
  final String? hardware; // 硬件名 (如 "qcom")
  final String? osVersion; // 系统版本 (如 "13")
  final String? platform; // 平台 (如 "android", "ios")
  final int? sdkInt; // SDK 版本 (如 33)
  final bool? isPhysicalDevice; // 是否真机

  DeviceHardwareInfo({
    this.brand,
    this.manufacturer,
    this.model,
    this.device,
    this.product,
    this.hardware,
    this.osVersion,
    this.platform,
    this.sdkInt,
    this.isPhysicalDevice,
  });

  Map<String, dynamic> toJson() => {
        if (brand != null) 'brand': brand,
        if (manufacturer != null) 'manufacturer': manufacturer,
        if (model != null) 'model': model,
        if (device != null) 'device': device,
        if (product != null) 'product': product,
        if (hardware != null) 'hardware': hardware,
        if (osVersion != null) 'osVersion': osVersion,
        if (platform != null) 'platform': platform,
        if (sdkInt != null) 'sdkInt': sdkInt,
        if (isPhysicalDevice != null) 'isPhysicalDevice': isPhysicalDevice,
      };

  @override
  String toString() =>
      'DeviceHardwareInfo(brand: $brand, model: $model, platform: $platform, osVersion: $osVersion)';
}

/// 创建账号请求
class CreateAccountRequest {
  final String deviceId; // 必填: Android ID 或 iOS identifierForVendor
  final DeviceHardwareInfo? deviceName; // 可选: 设备硬件信息 (JSON)
  final String? inviterReferralCode; // 可选: 邀请人推荐码

  CreateAccountRequest({
    required this.deviceId,
    this.deviceName,
    this.inviterReferralCode,
  });

  Map<String, dynamic> toJson() => {
        'deviceId': deviceId,
        if (deviceName != null) 'deviceName': deviceName!.toJson(),
        if (inviterReferralCode != null)
          'inviterReferralCode': inviterReferralCode,
      };

  @override
  String toString() =>
      'CreateAccountRequest(deviceId: $deviceId, inviterReferralCode: $inviterReferralCode)';
}

/// 创建账号响应 (新版 - 不含钱包信息)
class CreateAccountResponse {
  final String userSerialNum; // 用户序列号（新格式: D + YYMMDD + 5位序号）
  final String referralCode; // 推荐码
  final String username; // 随机用户名
  final String avatarSvg; // 随机 SVG 头像
  final String accessToken;
  final String refreshToken;

  CreateAccountResponse({
    required this.userSerialNum,
    required this.referralCode,
    required this.username,
    required this.avatarSvg,
    required this.accessToken,
    required this.refreshToken,
  });

  factory CreateAccountResponse.fromJson(Map<String, dynamic> json) {
    debugPrint('[AccountService] 解析 CreateAccountResponse: ${json.keys.toList()}');
    return CreateAccountResponse(
      userSerialNum: json['userSerialNum']?.toString() ?? '',
      referralCode: json['referralCode'] as String,
      username: json['username'] as String,
      avatarSvg: json['avatarSvg'] as String,
      accessToken: json['accessToken'] as String,
      refreshToken: json['refreshToken'] as String,
    );
  }

  @override
  String toString() =>
      'CreateAccountResponse(userSerialNum: $userSerialNum, username: $username, referralCode: $referralCode)';
}

/// 钱包信息响应
class WalletInfoResponse {
  final String status; // "generating" | "ready" | "failed"
  final WalletAddresses? walletAddresses;
  final String? mnemonic; // 12 词助记词

  WalletInfoResponse({
    required this.status,
    this.walletAddresses,
    this.mnemonic,
  });

  factory WalletInfoResponse.fromJson(Map<String, dynamic> json) {
    debugPrint('[AccountService] 解析 WalletInfoResponse: status=${json['status']}');
    return WalletInfoResponse(
      status: json['status'] as String,
      walletAddresses: json['walletAddresses'] != null
          ? WalletAddresses.fromJson(
              json['walletAddresses'] as Map<String, dynamic>)
          : null,
      mnemonic: json['mnemonic'] as String?,
    );
  }

  bool get isReady => status == 'ready';
  bool get isGenerating => status == 'generating';
  bool get isFailed => status == 'failed';

  @override
  String toString() =>
      'WalletInfoResponse(status: $status, hasAddresses: ${walletAddresses != null}, hasMnemonic: ${mnemonic != null})';
}

/// 钱包地址
class WalletAddresses {
  final String kava;
  final String dst;
  final String bsc;

  WalletAddresses({
    required this.kava,
    required this.dst,
    required this.bsc,
  });

  factory WalletAddresses.fromJson(Map<String, dynamic> json) {
    debugPrint('[AccountService] 解析 WalletAddresses: kava=${_maskAddress(json['kava'])}, dst=${_maskAddress(json['dst'])}, bsc=${_maskAddress(json['bsc'])}');
    return WalletAddresses(
      kava: json['kava'] as String,
      dst: json['dst'] as String,
      bsc: json['bsc'] as String,
    );
  }

  @override
  String toString() =>
      'WalletAddresses(kava: ${_maskAddress(kava)}, dst: ${_maskAddress(dst)}, bsc: ${_maskAddress(bsc)})';
}

/// 遮蔽地址中间部分，用于日志输出
String _maskAddress(String? address) {
  if (address == null || address.length <= 10) return address ?? 'null';
  return '${address.substring(0, 6)}...${address.substring(address.length - 4)}';
}

/// 短信验证码类型
enum SmsCodeType {
  register, // 注册
  login, // 登录
  bind, // 绑定手机号
  recover, // 恢复账号
}

/// 手机号注册响应 (与登录响应相同)
class PhoneAuthResponse {
  final String userId;
  final String accountSequence; // 用户序列号
  final String accessToken;
  final String refreshToken;

  PhoneAuthResponse({
    required this.userId,
    required this.accountSequence,
    required this.accessToken,
    required this.refreshToken,
  });

  factory PhoneAuthResponse.fromJson(Map<String, dynamic> json) {
    debugPrint('[AccountService] 解析 PhoneAuthResponse: ${json.keys.toList()}');
    return PhoneAuthResponse(
      userId: json['userId'] as String,
      accountSequence: json['accountSequence']?.toString() ?? '',
      accessToken: json['accessToken'] as String,
      refreshToken: json['refreshToken'] as String,
    );
  }

  @override
  String toString() =>
      'PhoneAuthResponse(userId: $userId, accountSequence: $accountSequence)';
}

/// 恢复账户响应
class RecoverAccountResponse {
  final String userId;
  final String userSerialNum; // accountSequence（新格式: D + YYMMDD + 5位序号）
  final String username; // nickname
  final String? avatarSvg; // avatarUrl
  final String referralCode;
  final String accessToken;
  final String refreshToken;

  RecoverAccountResponse({
    required this.userId,
    required this.userSerialNum,
    required this.username,
    this.avatarSvg,
    required this.referralCode,
    required this.accessToken,
    required this.refreshToken,
  });

  factory RecoverAccountResponse.fromJson(Map<String, dynamic> json) {
    debugPrint('[AccountService] 解析 RecoverAccountResponse: ${json.keys.toList()}');
    final avatarUrl = json['avatarUrl'] as String?;
    debugPrint('[AccountService] RecoverAccountResponse.avatarUrl: ${avatarUrl != null ? "长度=${avatarUrl.length}" : "null"}');
    if (avatarUrl != null && avatarUrl.isNotEmpty) {
      debugPrint('[AccountService] RecoverAccountResponse.avatarUrl前50字符: ${avatarUrl.substring(0, avatarUrl.length > 50 ? 50 : avatarUrl.length)}');
    }
    return RecoverAccountResponse(
      userId: json['userId'] as String,
      userSerialNum: json['accountSequence']?.toString() ?? '',
      username: json['nickname'] as String,
      avatarSvg: avatarUrl,
      referralCode: json['referralCode'] as String,
      accessToken: json['accessToken'] as String,
      refreshToken: json['refreshToken'] as String,
    );
  }

  @override
  String toString() =>
      'RecoverAccountResponse(userSerialNum: $userSerialNum, username: $username, referralCode: $referralCode)';
}

/// 当前用户信息响应 (GET /me)
class MeResponse {
  final String userId;
  final String accountSequence; // 账户序列号（新格式: D + YYMMDD + 5位序号）
  final String? phoneNumber;
  final String nickname;
  final String? avatarUrl;
  final String referralCode;
  final String referralLink;
  final String? inviterSequence; // 推荐人序列号（新格式: D + YYMMDD + 5位序号）
  final List<WalletAddressInfo> walletAddresses;
  final String kycStatus;
  final String status;
  final DateTime registeredAt;

  MeResponse({
    required this.userId,
    required this.accountSequence,
    this.phoneNumber,
    required this.nickname,
    this.avatarUrl,
    required this.referralCode,
    required this.referralLink,
    this.inviterSequence,
    required this.walletAddresses,
    required this.kycStatus,
    required this.status,
    required this.registeredAt,
  });

  factory MeResponse.fromJson(Map<String, dynamic> json) {
    return MeResponse(
      userId: json['userId'] as String,
      accountSequence: json['accountSequence']?.toString() ?? '',
      phoneNumber: json['phoneNumber'] as String?,
      nickname: json['nickname'] as String,
      avatarUrl: json['avatarUrl'] as String?,
      referralCode: json['referralCode'] as String,
      referralLink: json['referralLink'] as String,
      inviterSequence: json['inviterSequence']?.toString(),
      walletAddresses: (json['walletAddresses'] as List<dynamic>?)
              ?.map((e) => WalletAddressInfo.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      kycStatus: json['kycStatus'] as String,
      status: json['status'] as String,
      registeredAt: DateTime.parse(json['registeredAt'] as String),
    );
  }

  @override
  String toString() =>
      'MeResponse(accountSequence: $accountSequence, nickname: $nickname, inviterSequence: $inviterSequence)';
}

/// 钱包地址信息
class WalletAddressInfo {
  final String chainType;
  final String address;

  WalletAddressInfo({required this.chainType, required this.address});

  factory WalletAddressInfo.fromJson(Map<String, dynamic> json) {
    return WalletAddressInfo(
      chainType: json['chainType'] as String,
      address: json['address'] as String,
    );
  }
}

/// 账号服务
///
/// 处理账号创建、钱包获取等功能
class AccountService {
  final ApiClient _apiClient;
  final SecureStorage _secureStorage;
  final MultiAccountService? _multiAccountService;

  static const String _tag = '[AccountService]';

  AccountService({
    required ApiClient apiClient,
    required SecureStorage secureStorage,
    MultiAccountService? multiAccountService,
  })  : _apiClient = apiClient,
        _secureStorage = secureStorage,
        _multiAccountService = multiAccountService {
    debugPrint('$_tag 初始化完成');
  }

  /// 获取设备唯一标识符
  ///
  /// Android: 使用 Android ID (64位十六进制字符串)
  /// iOS: 使用 identifierForVendor
  Future<String> getDeviceId() async {
    debugPrint('$_tag getDeviceId() - 开始获取设备ID');
    final deviceInfoPlugin = DeviceInfoPlugin();

    if (Platform.isAndroid) {
      final info = await deviceInfoPlugin.androidInfo;
      final deviceId = info.id;
      debugPrint('$_tag getDeviceId() - Android ID: ${_maskAddress(deviceId)}');
      return deviceId;
    } else if (Platform.isIOS) {
      final info = await deviceInfoPlugin.iosInfo;
      final deviceId = info.identifierForVendor ?? const Uuid().v4();
      debugPrint('$_tag getDeviceId() - iOS identifierForVendor: ${_maskAddress(deviceId)}');
      return deviceId;
    }

    // 其他平台回退到 UUID
    final uuid = const Uuid().v4();
    debugPrint('$_tag getDeviceId() - 其他平台，使用 UUID: ${_maskAddress(uuid)}');
    return uuid;
  }

  /// 获取设备硬件信息
  ///
  /// Android: 完整硬件信息
  /// iOS: 基本信息
  Future<DeviceHardwareInfo> getDeviceHardwareInfo() async {
    debugPrint('$_tag getDeviceHardwareInfo() - 开始获取设备硬件信息');
    final deviceInfoPlugin = DeviceInfoPlugin();

    if (Platform.isAndroid) {
      final info = await deviceInfoPlugin.androidInfo;
      final hardwareInfo = DeviceHardwareInfo(
        brand: info.brand,
        manufacturer: info.manufacturer,
        model: info.model,
        device: info.device,
        product: info.product,
        hardware: info.hardware,
        osVersion: info.version.release,
        platform: 'android',
        sdkInt: info.version.sdkInt,
        isPhysicalDevice: info.isPhysicalDevice,
      );
      debugPrint('$_tag getDeviceHardwareInfo() - Android: $hardwareInfo');
      return hardwareInfo;
    } else if (Platform.isIOS) {
      final info = await deviceInfoPlugin.iosInfo;
      final hardwareInfo = DeviceHardwareInfo(
        brand: 'Apple',
        manufacturer: 'Apple',
        model: info.model,
        device: info.name,
        osVersion: info.systemVersion,
        platform: 'ios',
        isPhysicalDevice: info.isPhysicalDevice,
      );
      debugPrint('$_tag getDeviceHardwareInfo() - iOS: $hardwareInfo');
      return hardwareInfo;
    }

    // 其他平台返回空信息
    debugPrint('$_tag getDeviceHardwareInfo() - 其他平台，返回空信息');
    return DeviceHardwareInfo();
  }

  /// 创建账号 (快速返回，不含钱包信息)
  ///
  /// 钱包在后台异步生成，需要单独调用 getWalletInfo 获取
  Future<CreateAccountResponse> createAccount({
    String? inviterReferralCode,
  }) async {
    debugPrint('$_tag createAccount() - 开始创建账号');
    debugPrint('$_tag createAccount() - 邀请码: ${inviterReferralCode ?? "无"}');

    try {
      // 获取设备ID (必填)
      final deviceId = await getDeviceId();
      debugPrint('$_tag createAccount() - 获取设备ID成功');

      // 获取设备硬件信息 (可选)
      final deviceName = await getDeviceHardwareInfo();
      debugPrint('$_tag createAccount() - 获取设备硬件信息成功');

      final request = CreateAccountRequest(
        deviceId: deviceId,
        deviceName: deviceName,
        inviterReferralCode: inviterReferralCode,
      );
      debugPrint('$_tag createAccount() - 请求参数: $request');

      // 调用 API
      debugPrint('$_tag createAccount() - 调用 POST /user/auto-create');
      final response = await _apiClient.post(
        '/user/auto-create',
        data: request.toJson(),
      );
      debugPrint('$_tag createAccount() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag createAccount() - 错误: API 返回空响应');
        throw const ApiException('创建账号失败: 空响应');
      }

      debugPrint('$_tag createAccount() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = CreateAccountResponse.fromJson(data);
      debugPrint('$_tag createAccount() - 解析成功: $result');

      // 保存账号数据到安全存储
      debugPrint('$_tag createAccount() - 保存账号数据到安全存储');
      await _saveAccountData(result, deviceId);
      debugPrint('$_tag createAccount() - 账号数据保存成功');

      debugPrint('$_tag createAccount() - 账号创建完成');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag createAccount() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag createAccount() - 未知异常: $e');
      debugPrint('$_tag createAccount() - 堆栈: $stackTrace');
      throw ApiException('创建账号失败: $e');
    }
  }

  /// 获取钱包信息 (包含助记词)
  ///
  /// 通过 JWT token 获取当前用户的钱包状态
  Future<WalletInfoResponse> getWalletInfo(String userSerialNum) async {
    debugPrint('$_tag getWalletInfo() - 开始获取钱包信息');
    debugPrint('$_tag getWalletInfo() - userSerialNum: $userSerialNum');

    try {
      debugPrint('$_tag getWalletInfo() - 调用 GET /user/wallet');
      final response = await _apiClient.get('/user/wallet');
      debugPrint('$_tag getWalletInfo() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag getWalletInfo() - 错误: API 返回空响应');
        throw const ApiException('获取钱包信息失败: 空响应');
      }

      debugPrint('$_tag getWalletInfo() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = WalletInfoResponse.fromJson(data);
      debugPrint('$_tag getWalletInfo() - 解析成功: $result');

      // 如果钱包已就绪，保存钱包地址和助记词
      if (result.isReady) {
        debugPrint('$_tag getWalletInfo() - 钱包已就绪，保存钱包数据');
        await _saveWalletData(result);
        debugPrint('$_tag getWalletInfo() - 钱包数据保存成功');
      } else if (result.isGenerating) {
        debugPrint('$_tag getWalletInfo() - 钱包生成中，需要继续轮询');
      } else if (result.isFailed) {
        debugPrint('$_tag getWalletInfo() - 钱包生成失败');
      }

      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag getWalletInfo() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag getWalletInfo() - 未知异常: $e');
      debugPrint('$_tag getWalletInfo() - 堆栈: $stackTrace');
      throw ApiException('获取钱包信息失败: $e');
    }
  }

  /// 手机号+密码登录 (POST /user/login-with-password)
  ///
  /// 用于账号恢复功能
  Future<PhoneAuthResponse> loginWithPassword({
    required String phoneNumber,
    required String password,
    required String deviceId,
  }) async {
    debugPrint('$_tag loginWithPassword() - 开始登录');
    debugPrint('$_tag loginWithPassword() - 手机号: $phoneNumber');

    try {
      debugPrint('$_tag loginWithPassword() - 调用 POST /user/login-with-password');
      final response = await _apiClient.post(
        '/user/login-with-password',
        data: {
          'phoneNumber': phoneNumber,
          'password': password,
          'deviceId': deviceId,
        },
      );

      debugPrint('$_tag loginWithPassword() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag loginWithPassword() - 错误: API 返回空响应');
        throw const ApiException('登录失败: 空响应');
      }

      debugPrint('$_tag loginWithPassword() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>? ?? responseData;
      final result = PhoneAuthResponse.fromJson(data);
      debugPrint('$_tag loginWithPassword() - 登录成功: ${result.accountSequence}');

      // 保存登录信息
      await _savePhoneAuthData(result, deviceId, phoneNumber);

      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag loginWithPassword() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag loginWithPassword() - 未知异常: $e');
      debugPrint('$_tag loginWithPassword() - 堆栈: $stackTrace');
      throw ApiException('登录失败: $e');
    }
  }

  /// 发送重置密码短信验证码 (POST /user/send-reset-password-sms)
  ///
  /// 用于找回密码功能
  Future<void> sendResetPasswordSmsCode(String phoneNumber) async {
    debugPrint('$_tag sendResetPasswordSmsCode() - 发送重置密码验证码');
    debugPrint('$_tag sendResetPasswordSmsCode() - 手机号: $phoneNumber');

    try {
      final response = await _apiClient.post(
        '/user/send-reset-password-sms',
        data: {'phoneNumber': phoneNumber},
      );

      debugPrint('$_tag sendResetPasswordSmsCode() - API 响应状态码: ${response.statusCode}');

      if (response.statusCode != 200 && response.statusCode != 201) {
        throw ApiException('发送验证码失败: ${response.statusCode}');
      }

      debugPrint('$_tag sendResetPasswordSmsCode() - 验证码发送成功');
    } on ApiException catch (e) {
      debugPrint('$_tag sendResetPasswordSmsCode() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag sendResetPasswordSmsCode() - 未知异常: $e');
      debugPrint('$_tag sendResetPasswordSmsCode() - 堆栈: $stackTrace');
      throw ApiException('发送验证码失败: $e');
    }
  }

  /// 重置密码 (POST /user/reset-password)
  ///
  /// 用于找回密码功能，通过手机号+验证码重置密码
  Future<void> resetPassword({
    required String phoneNumber,
    required String smsCode,
    required String newPassword,
  }) async {
    debugPrint('$_tag resetPassword() - 开始重置密码');
    debugPrint('$_tag resetPassword() - 手机号: $phoneNumber');

    try {
      final response = await _apiClient.post(
        '/user/reset-password',
        data: {
          'phoneNumber': phoneNumber,
          'smsCode': smsCode,
          'newPassword': newPassword,
        },
      );

      debugPrint('$_tag resetPassword() - API 响应状态码: ${response.statusCode}');

      if (response.statusCode != 200 && response.statusCode != 201) {
        throw ApiException('重置密码失败: ${response.statusCode}');
      }

      debugPrint('$_tag resetPassword() - 密码重置成功');
    } on ApiException catch (e) {
      debugPrint('$_tag resetPassword() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag resetPassword() - 未知异常: $e');
      debugPrint('$_tag resetPassword() - 堆栈: $stackTrace');
      throw ApiException('重置密码失败: $e');
    }
  }

  /// 手动重试钱包生成 (POST /user/wallet/retry)
  ///
  /// 当钱包生成失败或超时时，用户可手动触发重试
  Future<void> retryWalletGeneration() async {
    debugPrint('$_tag retryWalletGeneration() - 开始手动重试钱包生成');

    try {
      debugPrint('$_tag retryWalletGeneration() - 调用 POST /user/wallet/retry');
      final response = await _apiClient.post('/user/wallet/retry');
      debugPrint('$_tag retryWalletGeneration() - API 响应状态码: ${response.statusCode}');

      if (response.statusCode == 200) {
        debugPrint('$_tag retryWalletGeneration() - 重试请求已提交');
      } else {
        debugPrint('$_tag retryWalletGeneration() - 请求失败，状态码: ${response.statusCode}');
        throw ApiException('重试钱包生成失败: ${response.statusCode}');
      }
    } on ApiException catch (e) {
      debugPrint('$_tag retryWalletGeneration() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag retryWalletGeneration() - 未知异常: $e');
      debugPrint('$_tag retryWalletGeneration() - 堆栈: $stackTrace');
      throw ApiException('重试钱包生成失败: $e');
    }
  }

  /// 获取当前用户完整信息 (GET /me)
  ///
  /// 返回用户的所有信息，包括推荐人序列号
  Future<MeResponse> getMe() async {
    debugPrint('$_tag getMe() - 开始获取用户信息');

    try {
      debugPrint('$_tag getMe() - 调用 GET /me');
      final response = await _apiClient.get('/me');
      debugPrint('$_tag getMe() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag getMe() - 错误: API 返回空响应');
        throw const ApiException('获取用户信息失败: 空响应');
      }

      debugPrint('$_tag getMe() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = MeResponse.fromJson(data);
      debugPrint('$_tag getMe() - 解析成功: $result');

      // 保存推荐人序列号到本地存储
      if (result.inviterSequence != null) {
        await _secureStorage.write(
          key: StorageKeys.inviterSequence,
          value: result.inviterSequence!,
        );
        debugPrint('$_tag getMe() - 保存 inviterSequence: ${result.inviterSequence}');
      }

      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag getMe() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag getMe() - 未知异常: $e');
      debugPrint('$_tag getMe() - 堆栈: $stackTrace');
      throw ApiException('获取用户信息失败: $e');
    }
  }

  /// 获取推荐人序列号 (从本地存储)
  Future<String?> getInviterSequence() async {
    final value = await _secureStorage.read(key: StorageKeys.inviterSequence);
    return value;
  }

  /// 保存账号数据
  Future<void> _saveAccountData(
    CreateAccountResponse response,
    String deviceId,
  ) async {
    debugPrint('$_tag _saveAccountData() - 开始保存账号数据');

    // 保存用户序列号
    debugPrint('$_tag _saveAccountData() - 保存 userSerialNum: ${response.userSerialNum}');
    await _secureStorage.write(
      key: StorageKeys.userSerialNum,
      value: response.userSerialNum,
    );

    debugPrint('$_tag _saveAccountData() - 保存 referralCode: ${response.referralCode}');
    await _secureStorage.write(
      key: StorageKeys.referralCode,
      value: response.referralCode,
    );

    // 保存用户信息
    debugPrint('$_tag _saveAccountData() - 保存 username: ${response.username}');
    await _secureStorage.write(
      key: StorageKeys.username,
      value: response.username,
    );

    debugPrint('$_tag _saveAccountData() - 保存 avatarSvg (长度: ${response.avatarSvg.length})');
    await _secureStorage.write(
      key: StorageKeys.avatarSvg,
      value: response.avatarSvg,
    );

    // 保存 Token
    debugPrint('$_tag _saveAccountData() - 保存 accessToken (长度: ${response.accessToken.length})');
    await _secureStorage.write(
      key: StorageKeys.accessToken,
      value: response.accessToken,
    );

    debugPrint('$_tag _saveAccountData() - 保存 refreshToken (长度: ${response.refreshToken.length})');
    await _secureStorage.write(
      key: StorageKeys.refreshToken,
      value: response.refreshToken,
    );

    // 保存设备 ID
    debugPrint('$_tag _saveAccountData() - 保存 deviceId: ${_maskAddress(deviceId)}');
    await _secureStorage.write(
      key: StorageKeys.deviceId,
      value: deviceId,
    );

    // 标记账号已创建
    debugPrint('$_tag _saveAccountData() - 标记账号已创建');
    await _secureStorage.write(
      key: StorageKeys.isAccountCreated,
      value: 'true',
    );

    // 设置遥测服务的用户ID和访问令牌（用于心跳认证）
    if (TelemetryService().isInitialized) {
      TelemetryService().setUserId(response.userSerialNum);
      TelemetryService().setAccessToken(response.accessToken);
      debugPrint('$_tag _saveAccountData() - 设置TelemetryService userId: ${response.userSerialNum}');
    }

    // 设置 Sentry 用户信息
    if (SentryService().isInitialized) {
      SentryService().setUser(userId: response.userSerialNum);
      debugPrint('$_tag _saveAccountData() - 设置SentryService userId: ${response.userSerialNum}');
    }

    debugPrint('$_tag _saveAccountData() - 账号数据保存完成');
  }

  /// 保存钱包数据
  Future<void> _saveWalletData(WalletInfoResponse response) async {
    debugPrint('$_tag _saveWalletData() - 开始保存钱包数据');

    if (response.walletAddresses != null) {
      debugPrint('$_tag _saveWalletData() - 保存 BSC 地址: ${_maskAddress(response.walletAddresses!.bsc)}');
      await _secureStorage.write(
        key: StorageKeys.walletAddressBsc,
        value: response.walletAddresses!.bsc,
      );

      debugPrint('$_tag _saveWalletData() - 保存 KAVA 地址: ${_maskAddress(response.walletAddresses!.kava)}');
      await _secureStorage.write(
        key: StorageKeys.walletAddressKava,
        value: response.walletAddresses!.kava,
      );

      debugPrint('$_tag _saveWalletData() - 保存 DST 地址: ${_maskAddress(response.walletAddresses!.dst)}');
      await _secureStorage.write(
        key: StorageKeys.walletAddressDst,
        value: response.walletAddresses!.dst,
      );
    } else {
      debugPrint('$_tag _saveWalletData() - 警告: walletAddresses 为空');
    }

    if (response.mnemonic != null && response.mnemonic!.isNotEmpty) {
      final wordCount = response.mnemonic!.split(' ').length;
      debugPrint('$_tag _saveWalletData() - 保存助记词 ($wordCount 个单词)');
      await _secureStorage.write(
        key: StorageKeys.mnemonic,
        value: response.mnemonic!,
      );
    } else {
      debugPrint('$_tag _saveWalletData() - 警告: mnemonic 为空');
    }

    // 标记钱包已就绪
    debugPrint('$_tag _saveWalletData() - 标记钱包已就绪');
    await _secureStorage.write(
      key: StorageKeys.isWalletReady,
      value: 'true',
    );

    debugPrint('$_tag _saveWalletData() - 钱包数据保存完成');
  }

  /// 检查是否已创建账号
  Future<bool> hasAccount() async {
    debugPrint('$_tag hasAccount() - 检查账号是否已创建');
    final isCreated =
        await _secureStorage.read(key: StorageKeys.isAccountCreated);
    final result = isCreated == 'true';
    debugPrint('$_tag hasAccount() - 结果: $result');
    return result;
  }

  /// 检查钱包是否已就绪
  Future<bool> isWalletReady() async {
    debugPrint('$_tag isWalletReady() - 检查钱包是否已就绪');
    final isReady = await _secureStorage.read(key: StorageKeys.isWalletReady);
    final result = isReady == 'true';
    debugPrint('$_tag isWalletReady() - 结果: $result');
    return result;
  }

  /// 获取用户序列号
  Future<String?> getUserSerialNum() async {
    debugPrint('$_tag getUserSerialNum() - 获取用户序列号');
    final result = await _secureStorage.read(key: StorageKeys.userSerialNum);
    debugPrint('$_tag getUserSerialNum() - 结果: $result');
    return result;
  }

  /// 获取用户名
  Future<String?> getUsername() async {
    debugPrint('$_tag getUsername() - 获取用户名');
    final result = await _secureStorage.read(key: StorageKeys.username);
    debugPrint('$_tag getUsername() - 结果: $result');
    return result;
  }

  /// 获取头像 SVG（初始生成的头像）
  Future<String?> getAvatarSvg() async {
    debugPrint('$_tag getAvatarSvg() - 获取头像 SVG');
    final result = await _secureStorage.read(key: StorageKeys.avatarSvg);
    debugPrint('$_tag getAvatarSvg() - 结果长度: ${result?.length ?? 0}');
    return result;
  }

  /// 获取头像 URL（用户上传的头像）
  Future<String?> getAvatarUrl() async {
    debugPrint('$_tag getAvatarUrl() - 获取头像 URL');
    final result = await _secureStorage.read(key: StorageKeys.avatarUrl);
    debugPrint('$_tag getAvatarUrl() - 结果: $result');
    return result;
  }

  /// 更新本地存储的头像 SVG
  /// 当从 API 获取到头像后，同步保存到本地存储
  /// 同时更新账号列表中的头像信息
  Future<void> updateLocalAvatarSvg(String avatarSvg) async {
    debugPrint('$_tag updateLocalAvatarSvg() - 更新本地头像 SVG (长度: ${avatarSvg.length})');
    await _secureStorage.write(key: StorageKeys.avatarSvg, value: avatarSvg);
    debugPrint('$_tag updateLocalAvatarSvg() - 保存成功');

    // 同步到账号列表
    await _syncAvatarToAccountList(avatarSvg: avatarSvg);
  }

  /// 同步头像信息到账号列表
  Future<void> _syncAvatarToAccountList({String? avatarSvg, String? avatarUrl}) async {
    await _syncProfileToAccountList(avatarSvg: avatarSvg, avatarUrl: avatarUrl);
  }

  /// 同步用户资料到账号列表
  Future<void> _syncProfileToAccountList({
    String? username,
    String? avatarSvg,
    String? avatarUrl,
  }) async {
    if (_multiAccountService == null) {
      debugPrint('$_tag _syncProfileToAccountList() - MultiAccountService 未注入，跳过同步');
      return;
    }

    final userSerialNum = await _secureStorage.read(key: StorageKeys.userSerialNum);
    if (userSerialNum == null) {
      debugPrint('$_tag _syncProfileToAccountList() - 未找到用户序列号，跳过同步');
      return;
    }

    await _multiAccountService.updateAccountInList(
      userSerialNum: userSerialNum,
      username: username,
      avatarSvg: avatarSvg,
      avatarUrl: avatarUrl,
    );
    debugPrint('$_tag _syncProfileToAccountList() - 已同步资料到账号列表');
  }

  /// 获取推荐码
  Future<String?> getReferralCode() async {
    debugPrint('$_tag getReferralCode() - 获取推荐码');
    final result = await _secureStorage.read(key: StorageKeys.referralCode);
    debugPrint('$_tag getReferralCode() - 结果: $result');
    return result;
  }

  /// 获取钱包地址 (从本地存储)
  Future<WalletAddresses?> getWalletAddresses() async {
    debugPrint('$_tag getWalletAddresses() - 获取钱包地址');
    final bsc = await _secureStorage.read(key: StorageKeys.walletAddressBsc);
    final kava = await _secureStorage.read(key: StorageKeys.walletAddressKava);
    final dst = await _secureStorage.read(key: StorageKeys.walletAddressDst);

    if (bsc == null || kava == null || dst == null) {
      debugPrint('$_tag getWalletAddresses() - 钱包地址不完整');
      return null;
    }

    final result = WalletAddresses(kava: kava, dst: dst, bsc: bsc);
    debugPrint('$_tag getWalletAddresses() - 结果: $result');
    return result;
  }

  /// 获取助记词 (从本地存储)
  Future<String?> getMnemonic() async {
    debugPrint('$_tag getMnemonic() - 获取助记词');
    final result = await _secureStorage.read(key: StorageKeys.mnemonic);
    if (result != null) {
      final wordCount = result.split(' ').length;
      debugPrint('$_tag getMnemonic() - 获取到 $wordCount 个单词');
    } else {
      debugPrint('$_tag getMnemonic() - 未找到助记词');
    }
    return result;
  }

  /// 标记助记词已备份
  ///
  /// 1. 调用后端 API 标记已备份
  /// 2. 保存本地状态
  Future<void> markMnemonicBackedUp() async {
    debugPrint('$_tag markMnemonicBackedUp() - 标记助记词已备份');

    try {
      // 1. 调用后端 API
      debugPrint('$_tag markMnemonicBackedUp() - 调用 PUT /user/mnemonic/backup');
      await _apiClient.put('/user/mnemonic/backup');
      debugPrint('$_tag markMnemonicBackedUp() - 后端标记成功');
    } catch (e) {
      // 后端调用失败时仅记录日志，不影响本地标记
      debugPrint('$_tag markMnemonicBackedUp() - 后端调用失败: $e');
    }

    // 2. 保存本地状态
    await _secureStorage.write(
      key: StorageKeys.isMnemonicBackedUp,
      value: 'true',
    );
    debugPrint('$_tag markMnemonicBackedUp() - 本地标记完成');
  }

  /// 检查助记词是否已备份
  Future<bool> isMnemonicBackedUp() async {
    debugPrint('$_tag isMnemonicBackedUp() - 检查助记词是否已备份');
    final isBackedUp =
        await _secureStorage.read(key: StorageKeys.isMnemonicBackedUp);
    final result = isBackedUp == 'true';
    debugPrint('$_tag isMnemonicBackedUp() - 结果: $result');
    return result;
  }

  /// 通过助记词恢复账户
  ///
  /// 使用序列号和 12 个助记词恢复已有账户
  /// [accountSequence] - 用户序列号（新格式: D + YYMMDD + 5位序号）
  /// [mnemonic] - 12 个助记词，用空格分隔
  Future<RecoverAccountResponse> recoverByMnemonic(String accountSequence, String mnemonic) async {
    debugPrint('$_tag recoverByMnemonic() - 开始恢复账户');
    debugPrint('$_tag recoverByMnemonic() - 序列号: $accountSequence');

    try {
      // 获取设备ID
      final deviceId = await getDeviceId();
      debugPrint('$_tag recoverByMnemonic() - 获取设备ID成功');

      // 获取设备硬件信息
      final deviceInfo = await getDeviceHardwareInfo();
      debugPrint('$_tag recoverByMnemonic() - 获取设备硬件信息成功');

      // 调用 API
      debugPrint('$_tag recoverByMnemonic() - 调用 POST /user/recover-by-mnemonic');
      final response = await _apiClient.post(
        '/user/recover-by-mnemonic',
        data: {
          'accountSequence': accountSequence,
          'mnemonic': mnemonic,
          'newDeviceId': deviceId,
          'deviceName': '${deviceInfo.brand ?? ''} ${deviceInfo.model ?? ''}'.trim(),
        },
      );
      debugPrint('$_tag recoverByMnemonic() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag recoverByMnemonic() - 错误: API 返回空响应');
        throw const ApiException('恢复账户失败: 空响应');
      }

      debugPrint('$_tag recoverByMnemonic() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = RecoverAccountResponse.fromJson(data);
      debugPrint('$_tag recoverByMnemonic() - 解析成功: $result');

      // 保存账号数据 (使用恢复账户专用的保存方法)
      debugPrint('$_tag recoverByMnemonic() - 保存账号数据');
      await _saveRecoverAccountData(result, deviceId);

      // 保存助记词
      debugPrint('$_tag recoverByMnemonic() - 保存助记词');
      await _secureStorage.write(
        key: StorageKeys.mnemonic,
        value: mnemonic,
      );

      // 标记助记词已备份 (恢复的用户肯定已经备份过了)
      await _secureStorage.write(
        key: StorageKeys.isMnemonicBackedUp,
        value: 'true',
      );

      // 获取并保存钱包地址
      debugPrint('$_tag recoverByMnemonic() - 获取钱包地址');
      try {
        final walletInfo = await getWalletInfo(result.userSerialNum);
        if (walletInfo.isReady && walletInfo.walletAddresses != null) {
          debugPrint('$_tag recoverByMnemonic() - 钱包地址获取成功');
          // _saveWalletData 会保存地址并设置 isWalletReady
          await _saveWalletData(walletInfo);
        } else {
          debugPrint('$_tag recoverByMnemonic() - 钱包地址未就绪: ${walletInfo.status}');
        }
      } catch (e) {
        // 钱包地址获取失败不影响恢复流程，可以稍后重试
        debugPrint('$_tag recoverByMnemonic() - 获取钱包地址失败 (不影响恢复): $e');
      }

      debugPrint('$_tag recoverByMnemonic() - 账户恢复完成');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag recoverByMnemonic() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag recoverByMnemonic() - 未知异常: $e');
      debugPrint('$_tag recoverByMnemonic() - 堆栈: $stackTrace');
      throw ApiException('恢复账户失败: $e');
    }
  }

  /// 保存恢复账户数据
  Future<void> _saveRecoverAccountData(
    RecoverAccountResponse response,
    String deviceId,
  ) async {
    debugPrint('$_tag _saveRecoverAccountData() - 开始保存恢复账号数据');

    // 保存用户序列号
    debugPrint('$_tag _saveRecoverAccountData() - 保存 userSerialNum: ${response.userSerialNum}');
    await _secureStorage.write(
      key: StorageKeys.userSerialNum,
      value: response.userSerialNum,
    );

    debugPrint('$_tag _saveRecoverAccountData() - 保存 referralCode: ${response.referralCode}');
    await _secureStorage.write(
      key: StorageKeys.referralCode,
      value: response.referralCode,
    );

    // 保存用户信息
    debugPrint('$_tag _saveRecoverAccountData() - 保存 username: ${response.username}');
    await _secureStorage.write(
      key: StorageKeys.username,
      value: response.username,
    );

    if (response.avatarSvg != null && response.avatarSvg!.isNotEmpty) {
      debugPrint('$_tag _saveRecoverAccountData() - 保存 avatarSvg (长度: ${response.avatarSvg!.length})');
      debugPrint('$_tag _saveRecoverAccountData() - avatarSvg前50字符: ${response.avatarSvg!.substring(0, response.avatarSvg!.length > 50 ? 50 : response.avatarSvg!.length)}');
      await _secureStorage.write(
        key: StorageKeys.avatarSvg,
        value: response.avatarSvg!,
      );
    } else {
      debugPrint('$_tag _saveRecoverAccountData() - ⚠️ avatarSvg 为空! response.avatarSvg=${response.avatarSvg}');
    }

    // 保存 Token
    debugPrint('$_tag _saveRecoverAccountData() - 保存 accessToken (长度: ${response.accessToken.length})');
    await _secureStorage.write(
      key: StorageKeys.accessToken,
      value: response.accessToken,
    );

    debugPrint('$_tag _saveRecoverAccountData() - 保存 refreshToken (长度: ${response.refreshToken.length})');
    await _secureStorage.write(
      key: StorageKeys.refreshToken,
      value: response.refreshToken,
    );

    // 保存设备 ID
    debugPrint('$_tag _saveRecoverAccountData() - 保存 deviceId: ${_maskAddress(deviceId)}');
    await _secureStorage.write(
      key: StorageKeys.deviceId,
      value: deviceId,
    );

    // 标记账号已创建
    debugPrint('$_tag _saveRecoverAccountData() - 标记账号已创建');
    await _secureStorage.write(
      key: StorageKeys.isAccountCreated,
      value: 'true',
    );

    // 恢复的账户钱包已就绪（助记词恢复意味着钱包已存在）
    debugPrint('$_tag _saveRecoverAccountData() - 标记钱包已就绪');
    await _secureStorage.write(
      key: StorageKeys.isWalletReady,
      value: 'true',
    );

    // 设置遥测服务的用户ID和访问令牌（用于心跳认证）
    if (TelemetryService().isInitialized) {
      TelemetryService().setUserId(response.userSerialNum);
      TelemetryService().setAccessToken(response.accessToken);
      debugPrint('$_tag _saveRecoverAccountData() - 设置TelemetryService userId: ${response.userSerialNum}');
    }

    // 设置 Sentry 用户信息
    if (SentryService().isInitialized) {
      SentryService().setUser(userId: response.userSerialNum);
      debugPrint('$_tag _saveRecoverAccountData() - 设置SentryService userId: ${response.userSerialNum}');
    }

    debugPrint('$_tag _saveRecoverAccountData() - 恢复账号数据保存完成');
  }

  /// 更新用户资料
  ///
  /// [nickname] - 新昵称（可选）
  /// [avatarUrl] - 新头像URL/SVG（可选）
  Future<void> updateProfile({String? nickname, String? avatarUrl}) async {
    debugPrint('$_tag updateProfile() - 开始更新用户资料');
    debugPrint('$_tag updateProfile() - nickname: $nickname, avatarUrl长度: ${avatarUrl?.length ?? 0}');

    if (nickname == null && avatarUrl == null) {
      debugPrint('$_tag updateProfile() - 无需更新，参数为空');
      return;
    }

    try {
      // 构建请求数据
      final Map<String, dynamic> data = {};
      if (nickname != null) {
        data['nickname'] = nickname;
      }
      if (avatarUrl != null) {
        data['avatarUrl'] = avatarUrl;
      }

      // 调用 API
      debugPrint('$_tag updateProfile() - 调用 PUT /user/update-profile');
      final response = await _apiClient.put('/user/update-profile', data: data);
      debugPrint('$_tag updateProfile() - API 响应状态码: ${response.statusCode}');

      // 更新本地存储
      if (nickname != null) {
        debugPrint('$_tag updateProfile() - 更新本地 username: $nickname');
        await _secureStorage.write(key: StorageKeys.username, value: nickname);
      }
      if (avatarUrl != null) {
        debugPrint('$_tag updateProfile() - 更新本地 avatarSvg');
        await _secureStorage.write(key: StorageKeys.avatarSvg, value: avatarUrl);
      }

      // 同步到账号列表
      if (nickname != null || avatarUrl != null) {
        await _syncProfileToAccountList(username: nickname, avatarSvg: avatarUrl);
      }

      debugPrint('$_tag updateProfile() - 用户资料更新完成');
    } on ApiException catch (e) {
      debugPrint('$_tag updateProfile() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag updateProfile() - 未知异常: $e');
      debugPrint('$_tag updateProfile() - 堆栈: $stackTrace');
      throw ApiException('更新用户资料失败: $e');
    }
  }

  /// 上传头像
  ///
  /// [imageFile] - 图片文件
  /// 返回新的头像URL
  Future<String> uploadAvatar(File imageFile) async {
    debugPrint('$_tag uploadAvatar() - 开始上传头像');
    debugPrint('$_tag uploadAvatar() - 文件路径: ${imageFile.path}');

    try {
      // 获取文件名和MIME类型
      final fileName = imageFile.path.split('/').last;
      final extension = fileName.split('.').last.toLowerCase();
      String mimeType;
      switch (extension) {
        case 'jpg':
        case 'jpeg':
          mimeType = 'image/jpeg';
          break;
        case 'png':
          mimeType = 'image/png';
          break;
        case 'gif':
          mimeType = 'image/gif';
          break;
        case 'webp':
          mimeType = 'image/webp';
          break;
        default:
          mimeType = 'image/jpeg';
      }

      debugPrint('$_tag uploadAvatar() - 文件名: $fileName, MIME: $mimeType');

      // 创建 FormData
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imageFile.path,
          filename: fileName,
          contentType: DioMediaType.parse(mimeType),
        ),
      });

      // 调用 API
      debugPrint('$_tag uploadAvatar() - 调用 POST /user/upload-avatar');
      final response = await _apiClient.post(
        '/user/upload-avatar',
        data: formData,
      );
      debugPrint('$_tag uploadAvatar() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        throw const ApiException('上传头像失败: 空响应');
      }

      final responseData = response.data as Map<String, dynamic>;
      debugPrint('$_tag uploadAvatar() - responseData: $responseData');
      // API 返回格式: { success: true, data: { message, avatarUrl } }
      final data = responseData['data'] as Map<String, dynamic>?;
      debugPrint('$_tag uploadAvatar() - data: $data');
      if (data == null) {
        throw const ApiException('上传头像失败: 响应数据格式错误');
      }
      final newAvatarUrl = data['avatarUrl'] as String?;
      debugPrint('$_tag uploadAvatar() - 新头像URL: $newAvatarUrl');
      if (newAvatarUrl == null || newAvatarUrl.isEmpty) {
        throw const ApiException('上传头像失败: 未返回头像URL');
      }

      // 更新本地存储（使用 avatarUrl 而不是 avatarSvg）
      await _secureStorage.write(key: StorageKeys.avatarUrl, value: newAvatarUrl);
      debugPrint('$_tag uploadAvatar() - 本地存储已更新');

      // 同步到账号列表
      await _syncProfileToAccountList(avatarUrl: newAvatarUrl);

      // 将图片复制到本地缓存目录
      try {
        final localPath = await _saveAvatarToLocal(imageFile);
        debugPrint('$_tag uploadAvatar() - 头像已保存到本地: $localPath');
      } catch (e) {
        debugPrint('$_tag uploadAvatar() - 保存本地头像失败 (不影响上传): $e');
      }

      return newAvatarUrl;
    } on ApiException catch (e) {
      debugPrint('$_tag uploadAvatar() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag uploadAvatar() - 未知异常: $e');
      debugPrint('$_tag uploadAvatar() - 堆栈: $stackTrace');
      throw ApiException('上传头像失败: $e');
    }
  }

  /// 上传通用图片
  ///
  /// [imageFile] - 图片文件
  /// [category] - 图片分类 (如 'office-photos')
  /// 返回图片URL
  Future<String> uploadImage(File imageFile, String category) async {
    debugPrint('$_tag uploadImage() - 开始上传图片');
    debugPrint('$_tag uploadImage() - 文件路径: ${imageFile.path}, 分类: $category');

    try {
      // 获取文件名和MIME类型
      final fileName = imageFile.path.split('/').last;
      final extension = fileName.split('.').last.toLowerCase();

      String mimeType;
      switch (extension) {
        case 'jpg':
        case 'jpeg':
          mimeType = 'image/jpeg';
          break;
        case 'png':
          mimeType = 'image/png';
          break;
        case 'gif':
          mimeType = 'image/gif';
          break;
        case 'webp':
          mimeType = 'image/webp';
          break;
        default:
          mimeType = 'image/jpeg';
      }

      debugPrint('$_tag uploadImage() - 文件名: $fileName, MIME: $mimeType');

      // 创建 FormData
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imageFile.path,
          filename: fileName,
          contentType: DioMediaType.parse(mimeType),
        ),
      });

      // 调用 API
      debugPrint('$_tag uploadImage() - 调用 POST /user/upload-image?category=$category');
      final response = await _apiClient.post(
        '/user/upload-image',
        data: formData,
        queryParameters: {'category': category},
      );
      debugPrint('$_tag uploadImage() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        throw const ApiException('上传图片失败: 空响应');
      }

      final responseData = response.data as Map<String, dynamic>;
      debugPrint('$_tag uploadImage() - responseData: $responseData');

      final data = responseData['data'] as Map<String, dynamic>?;
      if (data == null) {
        throw const ApiException('上传图片失败: 响应数据格式错误');
      }

      final imageUrl = data['imageUrl'] as String?;
      debugPrint('$_tag uploadImage() - 图片URL: $imageUrl');

      if (imageUrl == null || imageUrl.isEmpty) {
        throw const ApiException('上传图片失败: 未返回图片URL');
      }

      return imageUrl;
    } on ApiException catch (e) {
      debugPrint('$_tag uploadImage() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag uploadImage() - 未知异常: $e');
      debugPrint('$_tag uploadImage() - 堆栈: $stackTrace');
      throw ApiException('上传图片失败: $e');
    }
  }

  /// 获取我的资料（从服务器）
  Future<Map<String, dynamic>> getMyProfile() async {
    debugPrint('$_tag getMyProfile() - 获取我的资料');

    try {
      final response = await _apiClient.get('/user/my-profile');
      debugPrint('$_tag getMyProfile() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        throw const ApiException('获取资料失败: 空响应');
      }

      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      debugPrint('$_tag getMyProfile() - 获取成功');
      return data;
    } on ApiException catch (e) {
      debugPrint('$_tag getMyProfile() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag getMyProfile() - 未知异常: $e');
      debugPrint('$_tag getMyProfile() - 堆栈: $stackTrace');
      throw ApiException('获取资料失败: $e');
    }
  }

  /// 登出
  Future<void> logout() async {
    debugPrint('$_tag logout() - 开始登出，清除所有数据');
    // 删除本地头像文件
    try {
      final localAvatarPath = await getLocalAvatarPath();
      if (localAvatarPath != null) {
        final file = File(localAvatarPath);
        if (await file.exists()) {
          await file.delete();
          debugPrint('$_tag logout() - 已删除本地头像文件');
        }
      }
    } catch (e) {
      debugPrint('$_tag logout() - 删除本地头像失败: $e');
    }
    await _secureStorage.deleteAll();
    debugPrint('$_tag logout() - 登出完成');
  }

  // ==================== 本地头像管理 ====================

  /// 获取本地头像文件路径
  /// 返回本地头像的完整路径，如果不存在则返回 null
  Future<String?> getLocalAvatarPath() async {
    debugPrint('$_tag getLocalAvatarPath() - 获取本地头像路径');
    try {
      final directory = await getApplicationDocumentsDirectory();
      final avatarDir = Directory('${directory.path}/avatars');

      if (!await avatarDir.exists()) {
        debugPrint('$_tag getLocalAvatarPath() - 头像目录不存在');
        return null;
      }

      // 查找头像文件（支持多种格式）
      final files = await avatarDir.list().toList();
      for (final file in files) {
        if (file is File && file.path.contains('avatar.')) {
          debugPrint('$_tag getLocalAvatarPath() - 找到本地头像: ${file.path}');
          return file.path;
        }
      }

      debugPrint('$_tag getLocalAvatarPath() - 未找到本地头像');
      return null;
    } catch (e) {
      debugPrint('$_tag getLocalAvatarPath() - 获取路径失败: $e');
      return null;
    }
  }

  /// 保存头像到本地
  /// [imageFile] - 图片文件
  /// 返回保存后的本地路径
  Future<String> _saveAvatarToLocal(File imageFile) async {
    debugPrint('$_tag _saveAvatarToLocal() - 保存头像到本地');

    final directory = await getApplicationDocumentsDirectory();
    final avatarDir = Directory('${directory.path}/avatars');

    // 创建头像目录
    if (!await avatarDir.exists()) {
      await avatarDir.create(recursive: true);
      debugPrint('$_tag _saveAvatarToLocal() - 创建头像目录: ${avatarDir.path}');
    }

    // 删除旧的头像文件
    final files = await avatarDir.list().toList();
    for (final file in files) {
      if (file is File && file.path.contains('avatar.')) {
        await file.delete();
        debugPrint('$_tag _saveAvatarToLocal() - 删除旧头像: ${file.path}');
      }
    }

    // 获取文件扩展名
    final extension = imageFile.path.split('.').last.toLowerCase();
    final localPath = '${avatarDir.path}/avatar.$extension';

    // 复制文件
    await imageFile.copy(localPath);
    debugPrint('$_tag _saveAvatarToLocal() - 头像已保存: $localPath');

    return localPath;
  }

  /// 从网络下载头像并保存到本地
  /// [url] - 头像 URL
  /// 返回保存后的本地路径
  Future<String?> downloadAndCacheAvatar(String url) async {
    debugPrint('$_tag downloadAndCacheAvatar() - 下载头像: $url');

    try {
      final directory = await getApplicationDocumentsDirectory();
      final avatarDir = Directory('${directory.path}/avatars');

      // 创建头像目录
      if (!await avatarDir.exists()) {
        await avatarDir.create(recursive: true);
      }

      // 从 URL 获取扩展名
      String extension = 'jpg';
      if (url.contains('.png')) {
        extension = 'png';
      } else if (url.contains('.gif')) {
        extension = 'gif';
      } else if (url.contains('.webp')) {
        extension = 'webp';
      }

      final localPath = '${avatarDir.path}/avatar.$extension';

      // 使用 Dio 下载文件
      final dio = Dio();
      await dio.download(url, localPath);

      debugPrint('$_tag downloadAndCacheAvatar() - 头像已下载到: $localPath');
      return localPath;
    } catch (e) {
      debugPrint('$_tag downloadAndCacheAvatar() - 下载失败: $e');
      return null;
    }
  }

  // ==================== 手机号注册/登录 ====================

  /// 验证短信验证码（仅验证，不登录/注册）
  ///
  /// [phoneNumber] - 手机号
  /// [smsCode] - 6位短信验证码
  /// [type] - 验证码类型
  Future<void> verifySmsCode({
    required String phoneNumber,
    required String smsCode,
    required SmsCodeType type,
  }) async {
    debugPrint('$_tag verifySmsCode() - 验证短信验证码');
    debugPrint('$_tag verifySmsCode() - 手机号: ${_maskPhoneNumber(phoneNumber)}, 类型: ${type.name}');

    try {
      final typeStr = type.name.toUpperCase();

      debugPrint('$_tag verifySmsCode() - 调用 POST /user/verify-sms-code');
      final response = await _apiClient.post(
        '/user/verify-sms-code',
        data: {
          'phoneNumber': phoneNumber,
          'smsCode': smsCode,
          'type': typeStr,
        },
      );
      debugPrint('$_tag verifySmsCode() - API 响应状态码: ${response.statusCode}');

      // 验证成功后保存手机号
      await _secureStorage.write(
        key: StorageKeys.phoneNumber,
        value: phoneNumber,
      );
      debugPrint('$_tag verifySmsCode() - 短信验证码验证成功');
    } on ApiException catch (e) {
      debugPrint('$_tag verifySmsCode() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag verifySmsCode() - 未知异常: $e');
      debugPrint('$_tag verifySmsCode() - 堆栈: $stackTrace');
      throw ApiException('验证码验证失败: $e');
    }
  }

  /// 验证推荐码是否存在
  ///
  /// [referralCode] - 推荐码
  /// 返回用户信息（如果存在），否则抛出异常
  Future<Map<String, dynamic>> verifyReferralCode(String referralCode) async {
    debugPrint('$_tag verifyReferralCode() - 验证推荐码: $referralCode');

    try {
      final response = await _apiClient.get(
        '/referral/validate/$referralCode',
      );

      debugPrint('$_tag verifyReferralCode() - API 响应: ${response.data}');

      // 检查响应数据
      // referral-service 直接返回 {"valid": true/false} 格式
      final responseData = response.data as Map<String, dynamic>?;
      if (responseData == null) {
        debugPrint('$_tag verifyReferralCode() - 响应数据为 null');
        throw ApiException('推荐码不存在或无效');
      }

      debugPrint('$_tag verifyReferralCode() - 推荐码验证完成');
      return responseData;
    } on ApiException catch (e) {
      debugPrint('$_tag verifyReferralCode() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag verifyReferralCode() - 未知异常: $e');
      debugPrint('$_tag verifyReferralCode() - 堆栈: $stackTrace');
      throw ApiException('推荐码验证失败: $e');
    }
  }

  /// 发送短信验证码
  ///
  /// [phoneNumber] - 手机号（中国大陆格式：1开头，11位）
  /// [type] - 验证码类型
  Future<void> sendSmsCode(String phoneNumber, SmsCodeType type) async {
    debugPrint('$_tag sendSmsCode() - 发送短信验证码');
    debugPrint('$_tag sendSmsCode() - 手机号: ${_maskPhoneNumber(phoneNumber)}, 类型: ${type.name}');

    try {
      // 转换类型枚举为后端格式
      final typeStr = type.name.toUpperCase();

      debugPrint('$_tag sendSmsCode() - 调用 POST /user/send-sms-code');
      final response = await _apiClient.post(
        '/user/send-sms-code',
        data: {
          'phoneNumber': phoneNumber,
          'type': typeStr,
        },
      );
      debugPrint('$_tag sendSmsCode() - API 响应状态码: ${response.statusCode}');
      debugPrint('$_tag sendSmsCode() - 短信验证码已发送');
    } on ApiException catch (e) {
      debugPrint('$_tag sendSmsCode() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag sendSmsCode() - 未知异常: $e');
      debugPrint('$_tag sendSmsCode() - 堆栈: $stackTrace');
      throw ApiException('发送验证码失败: $e');
    }
  }

  /// 手机号注册 (旧接口，不推荐使用)
  ///
  /// [phoneNumber] - 手机号
  /// [smsCode] - 6位短信验证码
  /// [inviterReferralCode] - 邀请人推荐码（可选）
  @Deprecated('使用 registerByPhoneWithPassword 替代')
  Future<PhoneAuthResponse> registerByPhone({
    required String phoneNumber,
    required String smsCode,
    String? inviterReferralCode,
  }) async {
    debugPrint('$_tag registerByPhone() - 开始手机号注册');
    debugPrint('$_tag registerByPhone() - 手机号: ${_maskPhoneNumber(phoneNumber)}');
    debugPrint('$_tag registerByPhone() - 邀请码: ${inviterReferralCode ?? "无"}');

    try {
      // 获取设备ID
      final deviceId = await getDeviceId();
      debugPrint('$_tag registerByPhone() - 获取设备ID成功');

      // 获取设备硬件信息
      final deviceInfo = await getDeviceHardwareInfo();
      debugPrint('$_tag registerByPhone() - 获取设备硬件信息成功');

      final deviceName = '${deviceInfo.brand ?? ''} ${deviceInfo.model ?? ''}'.trim();

      // 调用 API
      debugPrint('$_tag registerByPhone() - 调用 POST /user/register');
      final response = await _apiClient.post(
        '/user/register',
        data: {
          'phoneNumber': phoneNumber,
          'smsCode': smsCode,
          'deviceId': deviceId,
          'deviceName': deviceName.isEmpty ? null : deviceName,
          if (inviterReferralCode != null) 'inviterReferralCode': inviterReferralCode,
        },
      );
      debugPrint('$_tag registerByPhone() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag registerByPhone() - 错误: API 返回空响应');
        throw const ApiException('注册失败: 空响应');
      }

      debugPrint('$_tag registerByPhone() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = PhoneAuthResponse.fromJson(data);
      debugPrint('$_tag registerByPhone() - 解析成功: $result');

      // 保存账号数据
      debugPrint('$_tag registerByPhone() - 保存账号数据');
      await _savePhoneAuthData(result, deviceId, phoneNumber);

      debugPrint('$_tag registerByPhone() - 手机号注册完成');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag registerByPhone() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag registerByPhone() - 未知异常: $e');
      debugPrint('$_tag registerByPhone() - 堆栈: $stackTrace');
      throw ApiException('注册失败: $e');
    }
  }

  /// 手机号注册 (新接口：验证码+密码一步完成)
  ///
  /// [phoneNumber] - 手机号
  /// [smsCode] - 6位短信验证码
  /// [password] - 登录密码
  /// [inviterReferralCode] - 邀请人推荐码（可选）
  Future<CreateAccountResponse> registerByPhoneWithPassword({
    required String phoneNumber,
    required String smsCode,
    required String password,
    String? inviterReferralCode,
  }) async {
    debugPrint('$_tag registerByPhoneWithPassword() - 开始手机号注册');
    debugPrint('$_tag registerByPhoneWithPassword() - 手机号: ${_maskPhoneNumber(phoneNumber)}');
    debugPrint('$_tag registerByPhoneWithPassword() - 邀请码: ${inviterReferralCode ?? "无"}');

    try {
      // 获取设备ID
      final deviceId = await getDeviceId();
      debugPrint('$_tag registerByPhoneWithPassword() - 获取设备ID成功');

      // 获取设备硬件信息
      final deviceInfo = await getDeviceHardwareInfo();
      debugPrint('$_tag registerByPhoneWithPassword() - 获取设备硬件信息成功');

      // 调用 API
      debugPrint('$_tag registerByPhoneWithPassword() - 调用 POST /user/register-by-phone');
      final response = await _apiClient.post(
        '/user/register-by-phone',
        data: {
          'phoneNumber': phoneNumber,
          'smsCode': smsCode,
          'password': password,
          'deviceId': deviceId,
          'deviceName': deviceInfo.toJson(),
          if (inviterReferralCode != null) 'inviterReferralCode': inviterReferralCode,
        },
      );
      debugPrint('$_tag registerByPhoneWithPassword() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag registerByPhoneWithPassword() - 错误: API 返回空响应');
        throw const ApiException('注册失败: 空响应');
      }

      debugPrint('$_tag registerByPhoneWithPassword() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = CreateAccountResponse.fromJson(data);
      debugPrint('$_tag registerByPhoneWithPassword() - 解析成功: $result');

      // 保存账号数据
      debugPrint('$_tag registerByPhoneWithPassword() - 保存账号数据');
      await _saveAccountData(result, deviceId);

      // 保存手机号
      await _secureStorage.write(key: StorageKeys.phoneNumber, value: phoneNumber);

      // 标记密码已设置
      await _secureStorage.write(key: StorageKeys.isPasswordSet, value: 'true');

      debugPrint('$_tag registerByPhoneWithPassword() - 手机号注册完成');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag registerByPhoneWithPassword() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag registerByPhoneWithPassword() - 未知异常: $e');
      debugPrint('$_tag registerByPhoneWithPassword() - 堆栈: $stackTrace');
      throw ApiException('注册失败: $e');
    }
  }

  /// 跳过短信验证注册
  ///
  /// 用户收不到验证码时可以跳过验证继续注册
  /// 注册后 phoneVerified = false，需在 KYC 流程中完成验证
  ///
  /// [phoneNumber] - 手机号
  /// [password] - 登录密码
  /// [inviterReferralCode] - 邀请人推荐码（可选）
  Future<CreateAccountResponse> registerWithoutSmsVerify({
    required String phoneNumber,
    required String password,
    String? inviterReferralCode,
  }) async {
    debugPrint('$_tag registerWithoutSmsVerify() - 开始跳过验证注册');
    debugPrint('$_tag registerWithoutSmsVerify() - 手机号: ${_maskPhoneNumber(phoneNumber)}');
    debugPrint('$_tag registerWithoutSmsVerify() - 邀请码: ${inviterReferralCode ?? "无"}');

    try {
      // 获取设备ID
      final deviceId = await getDeviceId();
      debugPrint('$_tag registerWithoutSmsVerify() - 获取设备ID成功');

      // 获取设备硬件信息
      final deviceInfo = await getDeviceHardwareInfo();
      debugPrint('$_tag registerWithoutSmsVerify() - 获取设备硬件信息成功');

      // 调用 API
      debugPrint('$_tag registerWithoutSmsVerify() - 调用 POST /user/register-without-sms-verify');
      final response = await _apiClient.post(
        '/user/register-without-sms-verify',
        data: {
          'phoneNumber': phoneNumber,
          'password': password,
          'deviceId': deviceId,
          'deviceName': deviceInfo.toJson(),
          if (inviterReferralCode != null) 'inviterReferralCode': inviterReferralCode,
        },
      );
      debugPrint('$_tag registerWithoutSmsVerify() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag registerWithoutSmsVerify() - 错误: API 返回空响应');
        throw const ApiException('注册失败: 空响应');
      }

      debugPrint('$_tag registerWithoutSmsVerify() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = CreateAccountResponse.fromJson(data);
      debugPrint('$_tag registerWithoutSmsVerify() - 解析成功: $result');

      // 保存账号数据
      debugPrint('$_tag registerWithoutSmsVerify() - 保存账号数据');
      await _saveAccountData(result, deviceId);

      // 保存手机号
      await _secureStorage.write(key: StorageKeys.phoneNumber, value: phoneNumber);

      // 标记密码已设置
      await _secureStorage.write(key: StorageKeys.isPasswordSet, value: 'true');

      // 注意：跳过验证注册的用户 phoneVerified = false，需要在 KYC 流程中完成验证
      debugPrint('$_tag registerWithoutSmsVerify() - 跳过验证注册完成 (phoneVerified=false)');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag registerWithoutSmsVerify() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag registerWithoutSmsVerify() - 未知异常: $e');
      debugPrint('$_tag registerWithoutSmsVerify() - 堆栈: $stackTrace');
      throw ApiException('注册失败: $e');
    }
  }

  /// 手机号登录
  ///
  /// [phoneNumber] - 手机号
  /// [smsCode] - 6位短信验证码
  Future<PhoneAuthResponse> loginByPhone({
    required String phoneNumber,
    required String smsCode,
  }) async {
    debugPrint('$_tag loginByPhone() - 开始手机号登录');
    debugPrint('$_tag loginByPhone() - 手机号: ${_maskPhoneNumber(phoneNumber)}');

    try {
      // 获取设备ID
      final deviceId = await getDeviceId();
      debugPrint('$_tag loginByPhone() - 获取设备ID成功');

      // 调用 API
      debugPrint('$_tag loginByPhone() - 调用 POST /user/login');
      final response = await _apiClient.post(
        '/user/login',
        data: {
          'phoneNumber': phoneNumber,
          'smsCode': smsCode,
          'deviceId': deviceId,
        },
      );
      debugPrint('$_tag loginByPhone() - API 响应状态码: ${response.statusCode}');

      if (response.data == null) {
        debugPrint('$_tag loginByPhone() - 错误: API 返回空响应');
        throw const ApiException('登录失败: 空响应');
      }

      debugPrint('$_tag loginByPhone() - 解析响应数据');
      final responseData = response.data as Map<String, dynamic>;
      final data = responseData['data'] as Map<String, dynamic>;
      final result = PhoneAuthResponse.fromJson(data);
      debugPrint('$_tag loginByPhone() - 解析成功: $result');

      // 保存账号数据
      debugPrint('$_tag loginByPhone() - 保存账号数据');
      await _savePhoneAuthData(result, deviceId, phoneNumber);

      debugPrint('$_tag loginByPhone() - 手机号登录完成');
      return result;
    } on ApiException catch (e) {
      debugPrint('$_tag loginByPhone() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag loginByPhone() - 未知异常: $e');
      debugPrint('$_tag loginByPhone() - 堆栈: $stackTrace');
      throw ApiException('登录失败: $e');
    }
  }

  /// 保存手机号认证数据
  Future<void> _savePhoneAuthData(
    PhoneAuthResponse response,
    String deviceId,
    String phoneNumber,
  ) async {
    debugPrint('$_tag _savePhoneAuthData() - 开始保存手机号认证数据');

    // 保存用户序列号
    debugPrint('$_tag _savePhoneAuthData() - 保存 userSerialNum: ${response.accountSequence}');
    await _secureStorage.write(
      key: StorageKeys.userSerialNum,
      value: response.accountSequence,
    );

    // 保存 Token
    debugPrint('$_tag _savePhoneAuthData() - 保存 accessToken (长度: ${response.accessToken.length})');
    await _secureStorage.write(
      key: StorageKeys.accessToken,
      value: response.accessToken,
    );

    debugPrint('$_tag _savePhoneAuthData() - 保存 refreshToken (长度: ${response.refreshToken.length})');
    await _secureStorage.write(
      key: StorageKeys.refreshToken,
      value: response.refreshToken,
    );

    // 保存设备 ID
    debugPrint('$_tag _savePhoneAuthData() - 保存 deviceId: ${_maskAddress(deviceId)}');
    await _secureStorage.write(
      key: StorageKeys.deviceId,
      value: deviceId,
    );

    // 保存手机号
    debugPrint('$_tag _savePhoneAuthData() - 保存手机号: ${_maskPhoneNumber(phoneNumber)}');
    await _secureStorage.write(
      key: StorageKeys.phoneNumber,
      value: phoneNumber,
    );

    // 标记账号已创建
    debugPrint('$_tag _savePhoneAuthData() - 标记账号已创建');
    await _secureStorage.write(
      key: StorageKeys.isAccountCreated,
      value: 'true',
    );

    // 设置遥测服务的用户ID和访问令牌（用于心跳认证）
    if (TelemetryService().isInitialized) {
      TelemetryService().setUserId(response.accountSequence);
      TelemetryService().setAccessToken(response.accessToken);
      debugPrint('$_tag _savePhoneAuthData() - 设置TelemetryService userId: ${response.accountSequence}');
    }

    // 设置 Sentry 用户信息
    if (SentryService().isInitialized) {
      SentryService().setUser(userId: response.accountSequence);
      debugPrint('$_tag _savePhoneAuthData() - 设置SentryService userId: ${response.accountSequence}');
    }

    debugPrint('$_tag _savePhoneAuthData() - 手机号认证数据保存完成');
  }

  /// 获取手机号（从本地存储）
  Future<String?> getPhoneNumber() async {
    debugPrint('$_tag getPhoneNumber() - 获取手机号');
    final result = await _secureStorage.read(key: StorageKeys.phoneNumber);
    if (result != null) {
      debugPrint('$_tag getPhoneNumber() - 结果: ${_maskPhoneNumber(result)}');
    } else {
      debugPrint('$_tag getPhoneNumber() - 未找到手机号');
    }
    return result;
  }

  /// 设置登录密码
  ///
  /// [password] - 登录密码（6-20位，包含字母和数字）
  Future<void> setLoginPassword(String password) async {
    debugPrint('$_tag setLoginPassword() - 开始设置登录密码');

    try {
      // 调用 API
      debugPrint('$_tag setLoginPassword() - 调用 POST /user/set-password');
      final response = await _apiClient.post(
        '/user/set-password',
        data: {
          'password': password,
        },
      );
      debugPrint('$_tag setLoginPassword() - API 响应状态码: ${response.statusCode}');

      // 标记密码已设置
      await _secureStorage.write(
        key: StorageKeys.isPasswordSet,
        value: 'true',
      );

      debugPrint('$_tag setLoginPassword() - 登录密码设置完成');
    } on ApiException catch (e) {
      debugPrint('$_tag setLoginPassword() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag setLoginPassword() - 未知异常: $e');
      debugPrint('$_tag setLoginPassword() - 堆栈: $stackTrace');
      throw ApiException('设置密码失败: $e');
    }
  }

  /// 检查是否已设置密码
  Future<bool> isPasswordSet() async {
    debugPrint('$_tag isPasswordSet() - 查询登录密码状态');
    try {
      final response = await _apiClient.get('/user/password-status');
      final result = response.data['data']['isSet'] == true;
      debugPrint('$_tag isPasswordSet() - 结果: $result');
      return result;
    } catch (e) {
      debugPrint('$_tag isPasswordSet() - 异常: $e');
      rethrow;
    }
  }

  /// 修改登录密码
  ///
  /// [oldPassword] - 当前密码
  /// [newPassword] - 新密码（6-20位，包含字母和数字）
  Future<void> changePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    debugPrint('$_tag changePassword() - 开始修改登录密码');

    try {
      debugPrint('$_tag changePassword() - 调用 POST /user/change-password');
      final response = await _apiClient.post(
        '/user/change-password',
        data: {
          'oldPassword': oldPassword,
          'newPassword': newPassword,
        },
      );
      debugPrint('$_tag changePassword() - API 响应状态码: ${response.statusCode}');

      debugPrint('$_tag changePassword() - 登录密码修改完成');
    } on ApiException catch (e) {
      debugPrint('$_tag changePassword() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag changePassword() - 未知异常: $e');
      debugPrint('$_tag changePassword() - 堆栈: $stackTrace');
      throw ApiException('修改密码失败: $e');
    }
  }

  /// 验证登录密码 (POST /user/verify-password)
  ///
  /// 用于敏感操作的二次身份验证，目前用于认种前校验。
  ///
  /// [password] 用户输入的密码明文
  ///
  /// 后端响应格式（经 TransformInterceptor 包装）：{ "success": true, "data": { "valid": true/false } }
  /// - 返回 true：密码正确
  /// - 返回 false：密码错误（valid=false）
  /// - 抛出异常：网络/系统错误（ApiException 或其他）
  Future<bool> verifyLoginPassword(String password) async {
    debugPrint('$_tag verifyLoginPassword() - 开始验证登录密码');
    try {
      final response = await _apiClient.post(
        '/user/verify-password',
        data: {'password': password},
      );
      final valid = response.data['data']['valid'] == true;
      debugPrint('$_tag verifyLoginPassword() - 验证结果: $valid');
      return valid;
    } on ApiException catch (e) {
      debugPrint('$_tag verifyLoginPassword() - 验证异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag verifyLoginPassword() - 未知异常: $e');
      rethrow;
    }
  }

  // ============ 支付密码相关 ============

  /// 查询是否已设置支付密码 (GET /user/payment-password-status)
  ///
  /// 返回 true 表示已设置，false 表示未设置
  Future<bool> isPaymentPasswordSet() async {
    debugPrint('$_tag isPaymentPasswordSet() - 查询支付密码状态');
    try {
      final response = await _apiClient.get('/user/payment-password-status');
      final isSet = response.data['data']['isSet'] == true;
      debugPrint('$_tag isPaymentPasswordSet() - 结果: $isSet');
      return isSet;
    } catch (e) {
      debugPrint('$_tag isPaymentPasswordSet() - 异常: $e');
      rethrow;
    }
  }

  /// 设置支付密码（首次设置）(POST /user/set-payment-password)
  ///
  /// [password] 支付密码明文（建议6位数字）
  Future<void> setPaymentPassword(String password) async {
    debugPrint('$_tag setPaymentPassword() - 开始设置支付密码');
    try {
      await _apiClient.post(
        '/user/set-payment-password',
        data: {'password': password},
      );
      debugPrint('$_tag setPaymentPassword() - 支付密码设置成功');
    } on ApiException catch (e) {
      debugPrint('$_tag setPaymentPassword() - API 异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag setPaymentPassword() - 未知异常: $e');
      throw ApiException('设置支付密码失败: $e');
    }
  }

  /// 修改支付密码 (POST /user/change-payment-password)
  ///
  /// [oldPassword] 当前支付密码
  /// [newPassword] 新支付密码
  Future<void> changePaymentPassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    debugPrint('$_tag changePaymentPassword() - 开始修改支付密码');
    try {
      await _apiClient.post(
        '/user/change-payment-password',
        data: {'oldPassword': oldPassword, 'newPassword': newPassword},
      );
      debugPrint('$_tag changePaymentPassword() - 支付密码修改成功');
    } on ApiException catch (e) {
      debugPrint('$_tag changePaymentPassword() - API 异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag changePaymentPassword() - 未知异常: $e');
      throw ApiException('修改支付密码失败: $e');
    }
  }

  /// 验证支付密码 (POST /user/verify-payment-password)
  ///
  /// 后端响应格式（经 TransformInterceptor 包装）：{ "success": true, "data": { "valid": true/false } }
  /// - 返回 true：密码正确
  /// - 返回 false：密码错误
  /// - 抛出异常：未设置支付密码或网络错误
  Future<bool> verifyPaymentPassword(String password) async {
    debugPrint('$_tag verifyPaymentPassword() - 开始验证支付密码');
    try {
      final response = await _apiClient.post(
        '/user/verify-payment-password',
        data: {'password': password},
      );
      final valid = response.data['data']['valid'] == true;
      debugPrint('$_tag verifyPaymentPassword() - 验证结果: $valid');
      return valid;
    } on ApiException catch (e) {
      debugPrint('$_tag verifyPaymentPassword() - 验证异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag verifyPaymentPassword() - 未知异常: $e');
      rethrow;
    }
  }

  // ============ 找回支付密码相关 ============ [2026-03-05]

  /// 发送重置支付密码短信验证码 (POST /user/send-reset-payment-password-sms)
  ///
  /// 向当前登录用户绑定的手机号发送验证码，用于忘记支付密码时身份核验。
  /// 需要 Bearer Token（接口在登录态下调用）。
  Future<void> sendResetPaymentPasswordSmsCode() async {
    debugPrint('$_tag sendResetPaymentPasswordSmsCode() - 发送重置支付密码验证码');
    try {
      await _apiClient.post('/user/send-reset-payment-password-sms');
      debugPrint('$_tag sendResetPaymentPasswordSmsCode() - 发送成功');
    } on ApiException catch (e) {
      debugPrint('$_tag sendResetPaymentPasswordSmsCode() - API 异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag sendResetPaymentPasswordSmsCode() - 未知异常: $e');
      throw ApiException('发送验证码失败: $e');
    }
  }

  /// 重置支付密码 (POST /user/reset-payment-password)
  ///
  /// 通过短信验证码验证身份后，将支付密码重置为新的 6 位数字密码。
  ///
  /// [smsCode] 短信验证码
  /// [newPassword] 新支付密码（6位纯数字）
  Future<void> resetPaymentPassword({
    required String smsCode,
    required String newPassword,
  }) async {
    debugPrint('$_tag resetPaymentPassword() - 开始重置支付密码');
    try {
      await _apiClient.post(
        '/user/reset-payment-password',
        data: {'smsCode': smsCode, 'newPassword': newPassword},
      );
      debugPrint('$_tag resetPaymentPassword() - 重置成功');
    } on ApiException catch (e) {
      debugPrint('$_tag resetPaymentPassword() - API 异常: $e');
      rethrow;
    } catch (e) {
      debugPrint('$_tag resetPaymentPassword() - 未知异常: $e');
      throw ApiException('重置支付密码失败: $e');
    }
  }

  // ============ 邮箱绑定相关 ============

  /// 获取邮箱绑定状态
  ///
  /// 返回:
  /// - isBound: 是否已绑定邮箱
  /// - email: 脱敏后的邮箱地址（如 ab***c@gmail.com）
  Future<EmailStatus> getEmailStatus() async {
    debugPrint('$_tag getEmailStatus() - 开始获取邮箱绑定状态');

    try {
      final response = await _apiClient.get('/user/email-status');
      debugPrint('$_tag getEmailStatus() - API 响应状态码: ${response.statusCode}');

      final data = response.data['data'] as Map<String, dynamic>? ?? response.data as Map<String, dynamic>;
      return EmailStatus(
        isBound: data['isBound'] as bool? ?? false,
        email: data['email'] as String?,
      );
    } on ApiException catch (e) {
      debugPrint('$_tag getEmailStatus() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag getEmailStatus() - 未知异常: $e');
      debugPrint('$_tag getEmailStatus() - 堆栈: $stackTrace');
      throw ApiException('获取邮箱状态失败: $e');
    }
  }

  /// 发送邮箱验证码
  ///
  /// [email] - 目标邮箱地址
  /// [purpose] - 用途: BIND_EMAIL(绑定) 或 UNBIND_EMAIL(解绑)
  Future<void> sendEmailCode({
    required String email,
    required String purpose,
  }) async {
    debugPrint('$_tag sendEmailCode() - 发送邮箱验证码: $purpose');

    try {
      final response = await _apiClient.post(
        '/user/send-email-code',
        data: {
          'email': email,
          'purpose': purpose,
        },
      );
      debugPrint('$_tag sendEmailCode() - API 响应状态码: ${response.statusCode}');
      debugPrint('$_tag sendEmailCode() - 验证码发送成功');
    } on ApiException catch (e) {
      debugPrint('$_tag sendEmailCode() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag sendEmailCode() - 未知异常: $e');
      debugPrint('$_tag sendEmailCode() - 堆栈: $stackTrace');
      throw ApiException('发送验证码失败: $e');
    }
  }

  /// 绑定邮箱
  ///
  /// [email] - 邮箱地址
  /// [code] - 6位验证码
  Future<void> bindEmail({
    required String email,
    required String code,
  }) async {
    debugPrint('$_tag bindEmail() - 开始绑定邮箱');

    try {
      final response = await _apiClient.post(
        '/user/bind-email',
        data: {
          'email': email,
          'code': code,
        },
      );
      debugPrint('$_tag bindEmail() - API 响应状态码: ${response.statusCode}');
      debugPrint('$_tag bindEmail() - 邮箱绑定成功');
    } on ApiException catch (e) {
      debugPrint('$_tag bindEmail() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag bindEmail() - 未知异常: $e');
      debugPrint('$_tag bindEmail() - 堆栈: $stackTrace');
      throw ApiException('绑定邮箱失败: $e');
    }
  }

  /// 解绑邮箱
  ///
  /// [code] - 6位验证码（发送到当前绑定的邮箱）
  Future<void> unbindEmail({required String code}) async {
    debugPrint('$_tag unbindEmail() - 开始解绑邮箱');

    try {
      final response = await _apiClient.post(
        '/user/unbind-email',
        data: {'code': code},
      );
      debugPrint('$_tag unbindEmail() - API 响应状态码: ${response.statusCode}');
      debugPrint('$_tag unbindEmail() - 邮箱解绑成功');
    } on ApiException catch (e) {
      debugPrint('$_tag unbindEmail() - API 异常: $e');
      rethrow;
    } catch (e, stackTrace) {
      debugPrint('$_tag unbindEmail() - 未知异常: $e');
      debugPrint('$_tag unbindEmail() - 堆栈: $stackTrace');
      throw ApiException('解绑邮箱失败: $e');
    }
  }
}

/// 邮箱绑定状态
class EmailStatus {
  final bool isBound;
  final String? email;

  EmailStatus({
    required this.isBound,
    this.email,
  });
}

/// 遮蔽手机号中间部分，用于日志输出
String _maskPhoneNumber(String phoneNumber) {
  if (phoneNumber.length < 7) return phoneNumber;
  return '${phoneNumber.substring(0, 3)}****${phoneNumber.substring(phoneNumber.length - 4)}';
}
