import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../constants/api_endpoints.dart';

/// 角色类型
enum RoleType {
  community,
  authProvinceCompany, // 省团队
  provinceCompany, // 省区域
  authCityCompany, // 市团队
  cityCompany, // 市区域
}

extension RoleTypeExtension on RoleType {
  String get value {
    switch (this) {
      case RoleType.community:
        return 'COMMUNITY';
      case RoleType.authProvinceCompany:
        return 'AUTH_PROVINCE_COMPANY';
      case RoleType.provinceCompany:
        return 'PROVINCE_COMPANY';
      case RoleType.authCityCompany:
        return 'AUTH_CITY_COMPANY';
      case RoleType.cityCompany:
        return 'CITY_COMPANY';
    }
  }

  String get displayName {
    switch (this) {
      case RoleType.community:
        return '社区';
      case RoleType.authProvinceCompany:
        return '省团队';
      case RoleType.provinceCompany:
        return '省区域';
      case RoleType.authCityCompany:
        return '市团队';
      case RoleType.cityCompany:
        return '市区域';
    }
  }

  static RoleType? fromString(String? value) {
    if (value == null) return null;
    switch (value.toUpperCase()) {
      case 'COMMUNITY':
        return RoleType.community;
      case 'AUTH_PROVINCE_COMPANY':
        return RoleType.authProvinceCompany;
      case 'PROVINCE_COMPANY':
        return RoleType.provinceCompany;
      case 'AUTH_CITY_COMPANY':
        return RoleType.authCityCompany;
      case 'CITY_COMPANY':
        return RoleType.cityCompany;
      default:
        return null;
    }
  }
}

/// 授权状态
enum AuthorizationStatus {
  pending,
  active,
  suspended,
  revoked,
}

extension AuthorizationStatusExtension on AuthorizationStatus {
  String get value {
    switch (this) {
      case AuthorizationStatus.pending:
        return 'PENDING';
      case AuthorizationStatus.active:
        return 'ACTIVE';
      case AuthorizationStatus.suspended:
        return 'SUSPENDED';
      case AuthorizationStatus.revoked:
        return 'REVOKED';
    }
  }

  static AuthorizationStatus fromString(String? value) {
    switch (value?.toUpperCase()) {
      case 'PENDING':
        return AuthorizationStatus.pending;
      case 'ACTIVE':
        return AuthorizationStatus.active;
      case 'SUSPENDED':
        return AuthorizationStatus.suspended;
      case 'REVOKED':
        return AuthorizationStatus.revoked;
      default:
        return AuthorizationStatus.pending;
    }
  }
}

/// 授权信息响应
class AuthorizationResponse {
  final String authorizationId;
  final String userId;
  final RoleType roleType;
  final String regionCode;
  final String regionName;
  final AuthorizationStatus status;
  final String displayTitle;
  final bool benefitActive;
  final int currentMonthIndex;
  final double requireLocalPercentage;
  final bool exemptFromPercentageCheck;
  // 考核进度字段
  final int initialTargetTreeCount;   // 初始考核目标（社区10，市100，省500）
  final int currentTreeCount;         // 当前团队认种数量
  final int monthlyTargetTreeCount;   // 月度考核目标
  final DateTime createdAt;
  final DateTime updatedAt;

  AuthorizationResponse({
    required this.authorizationId,
    required this.userId,
    required this.roleType,
    required this.regionCode,
    required this.regionName,
    required this.status,
    required this.displayTitle,
    required this.benefitActive,
    required this.currentMonthIndex,
    required this.requireLocalPercentage,
    required this.exemptFromPercentageCheck,
    required this.initialTargetTreeCount,
    required this.currentTreeCount,
    required this.monthlyTargetTreeCount,
    required this.createdAt,
    required this.updatedAt,
  });

  factory AuthorizationResponse.fromJson(Map<String, dynamic> json) {
    return AuthorizationResponse(
      authorizationId: json['authorizationId']?.toString() ?? '',
      userId: json['userId']?.toString() ?? '',
      roleType: RoleTypeExtension.fromString(json['roleType']) ?? RoleType.community,
      regionCode: json['regionCode'] ?? '',
      regionName: json['regionName'] ?? '',
      status: AuthorizationStatusExtension.fromString(json['status']),
      displayTitle: json['displayTitle'] ?? '',
      benefitActive: json['benefitActive'] ?? false,
      currentMonthIndex: json['currentMonthIndex'] ?? 0,
      requireLocalPercentage: (json['requireLocalPercentage'] ?? 0).toDouble(),
      exemptFromPercentageCheck: json['exemptFromPercentageCheck'] ?? false,
      initialTargetTreeCount: json['initialTargetTreeCount'] ?? 0,
      currentTreeCount: json['currentTreeCount'] ?? 0,
      monthlyTargetTreeCount: json['monthlyTargetTreeCount'] ?? 0,
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
      updatedAt: json['updatedAt'] != null
          ? DateTime.parse(json['updatedAt'])
          : DateTime.now(),
    );
  }
}

/// 用户授权汇总信息
class UserAuthorizationSummary {
  /// 社区授权 (如果有)
  final AuthorizationResponse? community;
  /// 省团队授权 (如果有)
  final AuthorizationResponse? authProvinceCompany;
  /// 省区域授权 (如果有)
  final AuthorizationResponse? provinceCompany;
  /// 市团队授权 (如果有)
  final AuthorizationResponse? authCityCompany;
  /// 市区域授权 (如果有)
  final AuthorizationResponse? cityCompany;
  /// 所有授权列表
  final List<AuthorizationResponse> allAuthorizations;

  UserAuthorizationSummary({
    this.community,
    this.authProvinceCompany,
    this.provinceCompany,
    this.authCityCompany,
    this.cityCompany,
    required this.allAuthorizations,
  });

  /// 是否有任何授权
  bool get hasAnyAuthorization => allAuthorizations.isNotEmpty;

  /// 社区名称
  String? get communityName => community?.displayTitle;

  /// 省团队名称
  String? get authProvinceCompanyName => authProvinceCompany?.displayTitle;

  /// 省区域名称
  String? get provinceCompanyName => provinceCompany?.displayTitle;

  /// 市团队名称
  String? get authCityCompanyName => authCityCompany?.displayTitle;

  /// 市区域名称
  String? get cityCompanyName => cityCompany?.displayTitle;

  factory UserAuthorizationSummary.fromList(List<AuthorizationResponse> authorizations) {
    AuthorizationResponse? community;
    AuthorizationResponse? authProvinceCompany;
    AuthorizationResponse? provinceCompany;
    AuthorizationResponse? authCityCompany;
    AuthorizationResponse? cityCompany;

    // 过滤掉已撤销的授权
    final activeAuthorizations = authorizations
        .where((auth) => auth.status != AuthorizationStatus.revoked)
        .toList();

    for (final auth in activeAuthorizations) {
      switch (auth.roleType) {
        case RoleType.community:
          community = auth;
          break;
        case RoleType.authProvinceCompany:
          authProvinceCompany = auth;
          break;
        case RoleType.provinceCompany:
          provinceCompany = auth;
          break;
        case RoleType.authCityCompany:
          authCityCompany = auth;
          break;
        case RoleType.cityCompany:
          cityCompany = auth;
          break;
      }
    }

    return UserAuthorizationSummary(
      community: community,
      authProvinceCompany: authProvinceCompany,
      provinceCompany: provinceCompany,
      authCityCompany: authCityCompany,
      cityCompany: cityCompany,
      allAuthorizations: activeAuthorizations,
    );
  }
}

/// 社区简要信息
class CommunityInfo {
  final String authorizationId;
  final String accountSequence; // 账户序列号（新格式: D + YYMMDD + 5位序号）
  final String communityName;
  final String? userId;
  final bool isHeadquarters;

  CommunityInfo({
    required this.authorizationId,
    required this.accountSequence,
    required this.communityName,
    this.userId,
    required this.isHeadquarters,
  });

  factory CommunityInfo.fromJson(Map<String, dynamic> json) {
    return CommunityInfo(
      authorizationId: json['authorizationId'] ?? '',
      accountSequence: json['accountSequence']?.toString() ?? '',
      communityName: json['communityName'] ?? '',
      userId: json['userId'],
      isHeadquarters: json['isHeadquarters'] ?? false,
    );
  }
}

/// 社区层级信息
class CommunityHierarchy {
  /// 我的社区授权（如果有）
  final CommunityInfo? myCommunity;
  /// 上级社区（最近的，如果没有则为总部社区）
  final CommunityInfo parentCommunity;
  /// 下级社区列表
  final List<CommunityInfo> childCommunities;
  /// 是否有上级社区（非总部）
  final bool hasParentCommunity;
  /// 下级社区数量
  final int childCommunityCount;

  CommunityHierarchy({
    this.myCommunity,
    required this.parentCommunity,
    required this.childCommunities,
    required this.hasParentCommunity,
    required this.childCommunityCount,
  });

  factory CommunityHierarchy.fromJson(Map<String, dynamic> json) {
    return CommunityHierarchy(
      myCommunity: json['myCommunity'] != null
          ? CommunityInfo.fromJson(json['myCommunity'])
          : null,
      parentCommunity: CommunityInfo.fromJson(json['parentCommunity']),
      childCommunities: (json['childCommunities'] as List<dynamic>?)
          ?.map((e) => CommunityInfo.fromJson(e as Map<String, dynamic>))
          .toList() ?? [],
      hasParentCommunity: json['hasParentCommunity'] ?? false,
      childCommunityCount: json['childCommunityCount'] ?? 0,
    );
  }
}

/// 自助申请授权类型
enum SelfApplyAuthorizationType {
  community,
  cityTeam,
  provinceTeam,
}

extension SelfApplyAuthorizationTypeExtension on SelfApplyAuthorizationType {
  String get value {
    switch (this) {
      case SelfApplyAuthorizationType.community:
        return 'COMMUNITY';
      case SelfApplyAuthorizationType.cityTeam:
        return 'CITY_TEAM';
      case SelfApplyAuthorizationType.provinceTeam:
        return 'PROVINCE_TEAM';
    }
  }

  String get displayName {
    switch (this) {
      case SelfApplyAuthorizationType.community:
        return '社区';
      case SelfApplyAuthorizationType.cityTeam:
        return '市团队';
      case SelfApplyAuthorizationType.provinceTeam:
        return '省团队';
    }
  }
}

/// 团队链中已被占用的区域信息
class TeamChainOccupiedRegion {
  final String accountSequence;
  final String nickname;
  final String regionCode;
  final String regionName;

  TeamChainOccupiedRegion({
    required this.accountSequence,
    required this.nickname,
    required this.regionCode,
    required this.regionName,
  });

  factory TeamChainOccupiedRegion.fromJson(Map<String, dynamic> json) {
    return TeamChainOccupiedRegion(
      accountSequence: json['accountSequence'] ?? '',
      nickname: json['nickname'] ?? '',
      regionCode: json['regionCode'] ?? '',
      regionName: json['regionName'] ?? '',
    );
  }
}

/// 用户授权状态响应
class UserAuthorizationStatusResponse {
  final bool hasPlanted;
  final int plantedCount;
  final List<String> existingAuthorizations;
  /// 团队链中已被占用的市团队区域列表
  final List<TeamChainOccupiedRegion> teamChainOccupiedCities;
  /// 团队链中已被占用的省团队区域列表
  final List<TeamChainOccupiedRegion> teamChainOccupiedProvinces;

  UserAuthorizationStatusResponse({
    required this.hasPlanted,
    required this.plantedCount,
    required this.existingAuthorizations,
    this.teamChainOccupiedCities = const [],
    this.teamChainOccupiedProvinces = const [],
  });

  factory UserAuthorizationStatusResponse.fromJson(Map<String, dynamic> json) {
    return UserAuthorizationStatusResponse(
      hasPlanted: json['hasPlanted'] ?? false,
      plantedCount: json['plantedCount'] ?? 0,
      existingAuthorizations: (json['existingAuthorizations'] as List<dynamic>?)
          ?.map((e) => e.toString())
          .toList() ?? [],
      teamChainOccupiedCities: (json['teamChainOccupiedCities'] as List<dynamic>?)
          ?.map((e) => TeamChainOccupiedRegion.fromJson(e as Map<String, dynamic>))
          .toList() ?? [],
      teamChainOccupiedProvinces: (json['teamChainOccupiedProvinces'] as List<dynamic>?)
          ?.map((e) => TeamChainOccupiedRegion.fromJson(e as Map<String, dynamic>))
          .toList() ?? [],
    );
  }

  /// 检查指定城市是否在团队链中已被占用
  bool isCityOccupied(String cityCode) {
    return teamChainOccupiedCities.any((r) => r.regionCode == cityCode);
  }

  /// 检查指定省份是否在团队链中已被占用
  bool isProvinceOccupied(String provinceCode) {
    return teamChainOccupiedProvinces.any((r) => r.regionCode == provinceCode);
  }

  /// 获取占用指定城市的持有者信息
  TeamChainOccupiedRegion? getCityOccupier(String cityCode) {
    try {
      return teamChainOccupiedCities.firstWhere((r) => r.regionCode == cityCode);
    } catch (_) {
      return null;
    }
  }

  /// 获取占用指定省份的持有者信息
  TeamChainOccupiedRegion? getProvinceOccupier(String provinceCode) {
    try {
      return teamChainOccupiedProvinces.firstWhere((r) => r.regionCode == provinceCode);
    } catch (_) {
      return null;
    }
  }
}

/// 自助申请授权响应
/// 自助申请直接生效，无需审核
class SelfApplyAuthorizationResponse {
  final String authorizationId;
  final String type;
  final DateTime grantedAt;
  final bool benefitsActivated;

  SelfApplyAuthorizationResponse({
    required this.authorizationId,
    required this.type,
    required this.grantedAt,
    required this.benefitsActivated,
  });

  factory SelfApplyAuthorizationResponse.fromJson(Map<String, dynamic> json) {
    return SelfApplyAuthorizationResponse(
      authorizationId: json['authorizationId'] ?? '',
      type: json['type'] ?? '',
      grantedAt: json['grantedAt'] != null
          ? DateTime.parse(json['grantedAt'])
          : DateTime.now(),
      benefitsActivated: json['benefitsActivated'] ?? false,
    );
  }
}

/// 火柴人排名响应
class StickmanRankingResponse {
  final String id;
  final String userId;
  final String authorizationId;
  final String nickname;
  final String? avatarUrl;
  final int completedCount;
  final double monthlyEarnings;
  final bool isCurrentUser;
  final String? accountSequence;
  final int finalTarget;          // 最终目标数量
  final double progressPercentage; // 进度百分比 (0-100)

  StickmanRankingResponse({
    required this.id,
    required this.userId,
    required this.authorizationId,
    required this.nickname,
    this.avatarUrl,
    required this.completedCount,
    required this.monthlyEarnings,
    required this.isCurrentUser,
    this.accountSequence,
    required this.finalTarget,
    required this.progressPercentage,
  });

  factory StickmanRankingResponse.fromJson(Map<String, dynamic> json) {
    return StickmanRankingResponse(
      id: json['id']?.toString() ?? '',
      userId: json['userId']?.toString() ?? '',
      authorizationId: json['authorizationId']?.toString() ?? '',
      nickname: json['nickname'] ?? '',
      avatarUrl: json['avatarUrl'],
      completedCount: json['completedCount'] ?? 0,
      monthlyEarnings: (json['monthlyEarnings'] ?? 0).toDouble(),
      isCurrentUser: json['isCurrentUser'] ?? false,
      accountSequence: json['accountSequence']?.toString(),
      finalTarget: json['finalTarget'] ?? 50000,
      progressPercentage: (json['progressPercentage'] ?? 0).toDouble(),
    );
  }
}

/// 用户授权简要信息
class UserAuthorizationInfo {
  final String authorizationId;
  final RoleType roleType;
  final String regionCode;
  final String regionName;
  final String displayTitle;
  final bool benefitActive;

  UserAuthorizationInfo({
    required this.authorizationId,
    required this.roleType,
    required this.regionCode,
    required this.regionName,
    required this.displayTitle,
    required this.benefitActive,
  });

  factory UserAuthorizationInfo.fromJson(Map<String, dynamic> json) {
    return UserAuthorizationInfo(
      authorizationId: json['authorizationId'] ?? '',
      roleType: RoleTypeExtension.fromString(json['roleType']) ?? RoleType.community,
      regionCode: json['regionCode'] ?? '',
      regionName: json['regionName'] ?? '',
      displayTitle: json['displayTitle'] ?? '',
      benefitActive: json['benefitActive'] ?? false,
    );
  }
}

/// 用户公开资料响应
class UserProfileResponse {
  final String userId;
  final String accountSequence;
  final String nickname;
  final String? avatarUrl;
  final String registeredAt;
  final String? inviterSequence;
  final String? inviterNickname;
  final int directReferralCount;
  final int umbrellaUserCount;
  final String? province;
  final String? city;
  final int personalPlantingCount;
  final int teamPlantingCount;
  final List<UserAuthorizationInfo> authorizations;
  // 私密字段（仅特权用户可见）
  final String? phoneNumber;
  final String? email;
  final String? realName;
  final String? kycStatus;

  UserProfileResponse({
    required this.userId,
    required this.accountSequence,
    required this.nickname,
    this.avatarUrl,
    required this.registeredAt,
    this.inviterSequence,
    this.inviterNickname,
    required this.directReferralCount,
    required this.umbrellaUserCount,
    this.province,
    this.city,
    required this.personalPlantingCount,
    required this.teamPlantingCount,
    required this.authorizations,
    this.phoneNumber,
    this.email,
    this.realName,
    this.kycStatus,
  });

  factory UserProfileResponse.fromJson(Map<String, dynamic> json) {
    return UserProfileResponse(
      userId: json['userId']?.toString() ?? '',
      accountSequence: json['accountSequence']?.toString() ?? '',
      nickname: json['nickname'] ?? '',
      avatarUrl: json['avatarUrl'],
      registeredAt: json['registeredAt'] ?? '',
      inviterSequence: json['inviterSequence'],
      inviterNickname: json['inviterNickname'],
      directReferralCount: json['directReferralCount'] ?? 0,
      umbrellaUserCount: json['umbrellaUserCount'] ?? 0,
      province: json['province'],
      city: json['city'],
      personalPlantingCount: json['personalPlantingCount'] ?? 0,
      teamPlantingCount: json['teamPlantingCount'] ?? 0,
      authorizations: (json['authorizations'] as List<dynamic>?)
          ?.map((e) => UserAuthorizationInfo.fromJson(e as Map<String, dynamic>))
          .toList() ?? [],
      phoneNumber: json['phoneNumber'],
      email: json['email'],
      realName: json['realName'],
      kycStatus: json['kycStatus'],
    );
  }

  /// 注册时间（解析后）
  DateTime get registeredAtDateTime => DateTime.tryParse(registeredAt) ?? DateTime.now();

  /// 是否有私密信息
  bool get hasPrivateInfo => phoneNumber != null || email != null || realName != null;
}

/// 授权服务
///
/// 处理用户授权相关功能:
/// - 获取用户授权列表
/// - 社区/省公司/市公司授权信息
/// - 火柴人排名数据
class AuthorizationService {
  final ApiClient _apiClient;

  AuthorizationService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 获取我的授权列表
  ///
  /// 调用 GET /authorizations/my (authorization-service)
  Future<List<AuthorizationResponse>> getMyAuthorizations() async {
    try {
      debugPrint('获取授权列表...');
      final response = await _apiClient.get(ApiEndpoints.myAuthorizations);

      if (response.statusCode == 200) {
        final responseData = response.data;
        // API 返回格式: {"success": true, "data": [...]}
        // 需要先提取 data 字段
        List<dynamic>? dataList;
        if (responseData is Map<String, dynamic>) {
          dataList = responseData['data'] as List<dynamic>?;
        } else if (responseData is List) {
          dataList = responseData;
        }

        if (dataList != null) {
          final authorizations = dataList
              .map((e) => AuthorizationResponse.fromJson(e as Map<String, dynamic>))
              .toList();
          debugPrint('授权列表获取成功: ${authorizations.length} 个授权');
          return authorizations;
        }
        return [];
      }

      throw Exception('获取授权列表失败');
    } catch (e) {
      debugPrint('获取授权列表失败: $e');
      rethrow;
    }
  }

  /// 获取用户授权汇总信息
  ///
  /// 方便前端快速访问社区/省公司/市公司信息
  Future<UserAuthorizationSummary> getMyAuthorizationSummary() async {
    final authorizations = await getMyAuthorizations();
    return UserAuthorizationSummary.fromList(authorizations);
  }

  /// 获取我的社区层级信息
  ///
  /// 返回上级社区（如果没有则为总部社区）和下级社区列表
  /// 调用 GET /authorizations/my/community-hierarchy
  Future<CommunityHierarchy> getMyCommunityHierarchy() async {
    try {
      debugPrint('获取社区层级...');
      final response = await _apiClient.get(ApiEndpoints.myCommunityHierarchy);

      if (response.statusCode == 200) {
        final responseData = response.data;
        // API 返回格式: {"success": true, "data": {...}}
        Map<String, dynamic>? data;
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data')) {
            data = responseData['data'] as Map<String, dynamic>?;
          } else {
            data = responseData;
          }
        }

        if (data != null) {
          final hierarchy = CommunityHierarchy.fromJson(data);
          debugPrint('社区层级获取成功: 上级=${hierarchy.parentCommunity.communityName}, 下级数量=${hierarchy.childCommunityCount}');
          return hierarchy;
        }
        throw Exception('社区层级数据格式错误');
      }

      throw Exception('获取社区层级失败');
    } catch (e) {
      debugPrint('获取社区层级失败: $e');
      rethrow;
    }
  }

  /// 获取火柴人排名数据
  ///
  /// 用于显示省公司/市公司的排名赛跑
  /// [month] 月份格式: YYYY-MM
  /// [roleType] 角色类型: AUTH_PROVINCE_COMPANY 或 AUTH_CITY_COMPANY
  /// [regionCode] 区域代码/名称
  Future<List<StickmanRankingResponse>> getStickmanRanking({
    required String month,
    required String roleType,
    required String regionCode,
  }) async {
    try {
      debugPrint('获取火柴人排名: month=$month, roleType=$roleType, regionCode=$regionCode');
      final response = await _apiClient.get(
        ApiEndpoints.stickmanRanking,
        queryParameters: {
          'month': month,
          'roleType': roleType,
          'regionCode': regionCode,
        },
      );

      if (response.statusCode == 200) {
        final responseData = response.data;
        List<dynamic>? dataList;
        if (responseData is Map<String, dynamic>) {
          dataList = responseData['data'] as List<dynamic>?;
        } else if (responseData is List) {
          dataList = responseData;
        }

        if (dataList != null) {
          final rankings = dataList
              .map((e) => StickmanRankingResponse.fromJson(e as Map<String, dynamic>))
              .toList();
          debugPrint('火柴人排名获取成功: ${rankings.length} 个');
          return rankings;
        }
        return [];
      }

      throw Exception('获取火柴人排名失败');
    } catch (e) {
      debugPrint('获取火柴人排名失败: $e');
      rethrow;
    }
  }

  /// 获取用户授权申请状态
  ///
  /// 返回用户是否已认种、认种棵数、已有授权和待审核申请
  /// 调用 GET /authorizations/self-apply/status
  Future<UserAuthorizationStatusResponse> getSelfApplyStatus() async {
    try {
      debugPrint('获取授权申请状态...');
      final response = await _apiClient.get(ApiEndpoints.selfApplyStatus);

      if (response.statusCode == 200) {
        final responseData = response.data;
        Map<String, dynamic>? data;
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data')) {
            data = responseData['data'] as Map<String, dynamic>?;
          } else {
            data = responseData;
          }
        }

        if (data != null) {
          final status = UserAuthorizationStatusResponse.fromJson(data);
          debugPrint('授权申请状态获取成功: hasPlanted=${status.hasPlanted}, plantedCount=${status.plantedCount}');
          return status;
        }
        throw Exception('授权申请状态数据格式错误');
      }

      throw Exception('获取授权申请状态失败');
    } catch (e) {
      debugPrint('获取授权申请状态失败: $e');
      rethrow;
    }
  }

  /// 自助申请授权
  ///
  /// [type] 申请类型（社区、市团队、省团队）
  /// [officePhotoUrls] 办公室照片URL列表（至少2张，最多6张）
  /// [communityName] 社区名称（申请社区时必填）
  /// [provinceCode] 省份代码（申请省团队时必填）
  /// [provinceName] 省份名称（申请省团队时必填）
  /// [cityCode] 城市代码（申请市团队时必填）
  /// [cityName] 城市名称（申请市团队时必填）
  Future<SelfApplyAuthorizationResponse> selfApplyAuthorization({
    required SelfApplyAuthorizationType type,
    required List<String> officePhotoUrls,
    String? communityName,
    String? provinceCode,
    String? provinceName,
    String? cityCode,
    String? cityName,
  }) async {
    try {
      debugPrint('自助申请授权: type=${type.value}');

      final body = <String, dynamic>{
        'type': type.value,
        'officePhotoUrls': officePhotoUrls,
      };

      // 根据申请类型添加必填字段
      if (type == SelfApplyAuthorizationType.community && communityName != null) {
        body['communityName'] = communityName;
      }
      if (type == SelfApplyAuthorizationType.provinceTeam) {
        if (provinceCode != null) body['provinceCode'] = provinceCode;
        if (provinceName != null) body['provinceName'] = provinceName;
      }
      if (type == SelfApplyAuthorizationType.cityTeam) {
        if (cityCode != null) body['cityCode'] = cityCode;
        if (cityName != null) body['cityName'] = cityName;
      }

      final response = await _apiClient.post(
        ApiEndpoints.selfApply,
        data: body,
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        final responseData = response.data;
        Map<String, dynamic>? data;
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data')) {
            data = responseData['data'] as Map<String, dynamic>?;
          } else {
            data = responseData;
          }
        }

        if (data != null) {
          final result = SelfApplyAuthorizationResponse.fromJson(data);
          debugPrint('自助申请授权成功: authorizationId=${result.authorizationId}, benefitsActivated=${result.benefitsActivated}');
          return result;
        }
        throw Exception('申请响应数据格式错误');
      }

      throw Exception('自助申请授权失败');
    } catch (e) {
      debugPrint('自助申请授权失败: $e');
      rethrow;
    }
  }

  /// 获取用户公开资料
  ///
  /// [accountSequence] 目标用户的账户序列号
  /// 返回用户的公开资料，包括昵称、头像、注册时间、推荐人、直推人数等
  Future<UserProfileResponse> getUserProfile(String accountSequence) async {
    try {
      debugPrint('获取用户资料: accountSequence=$accountSequence');
      final response = await _apiClient.get(
        '/authorizations/users/$accountSequence/profile',
      );

      if (response.statusCode == 200) {
        final responseData = response.data;
        Map<String, dynamic>? data;
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data')) {
            data = responseData['data'] as Map<String, dynamic>?;
          } else {
            data = responseData;
          }
        }

        if (data != null) {
          final profile = UserProfileResponse.fromJson(data);
          debugPrint('用户资料获取成功: ${profile.nickname}');
          return profile;
        }
        throw Exception('用户资料数据格式错误');
      }

      throw Exception('获取用户资料失败');
    } catch (e) {
      debugPrint('获取用户资料失败: $e');
      rethrow;
    }
  }

  /// 获取用户私密资料（需要省团队以上权限）
  ///
  /// [accountSequence] 目标用户的账户序列号
  /// 返回用户的私密资料，包括脱敏的手机号、邮箱、真实姓名等
  Future<UserProfileResponse> getUserPrivateProfile(String accountSequence) async {
    try {
      debugPrint('获取用户私密资料: accountSequence=$accountSequence');
      final response = await _apiClient.get(
        '/authorizations/users/$accountSequence/profile/private',
      );

      if (response.statusCode == 200) {
        final responseData = response.data;
        Map<String, dynamic>? data;
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data')) {
            data = responseData['data'] as Map<String, dynamic>?;
          } else {
            data = responseData;
          }
        }

        if (data != null) {
          final profile = UserProfileResponse.fromJson(data);
          debugPrint('用户私密资料获取成功: ${profile.nickname}');
          return profile;
        }
        throw Exception('用户私密资料数据格式错误');
      }

      throw Exception('获取用户私密资料失败');
    } catch (e) {
      debugPrint('获取用户私密资料失败: $e');
      rethrow;
    }
  }
}
