import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/network/api_response.dart';
import '../../core/network/dio_client.dart';

/// 经纪商 Repository — 对应 agent-api AgentController
class BrokerRepository {
  BrokerRepository(this._dio);

  final Dio _dio;

  /// 获取代理商信息（包含总返佣余额）
  /// 获取代理商信息（对应安卓 uc/agent/info）
  Future<Map<String, dynamic>?> getBrokerInfo() async {
    final resp = await _dio.post('uc/agent/info');
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      return body['data'] as Map<String, dynamic>?;
    }
    return null;
  }

  /// 获取下级成员列表
  Future<List<Map<String, dynamic>>> getMemberList({int page = 1, int pageSize = 50}) async {
    final resp = await _dio.post('uc/agent/member/list', data: {
      'pageNo': page,
      'pageSize': pageSize,
    });
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      final data = body['data'];
      if (data is Map && data['content'] is List) {
        return (data['content'] as List).cast<Map<String, dynamic>>();
      }
      if (data is List) return data.cast<Map<String, dynamic>>();
    }
    return [];
  }

  /// 获取返佣记录（分页）— 对应安卓 uc/agent/reward
  Future<List<Map<String, dynamic>>> getRewardList({
    int page = 1,
    int pageSize = 20,
    DateTime? startTime,
  }) async {
    String? startTimeStr;
    if (startTime != null) {
      final y = startTime.year.toString().padLeft(4, '0');
      final mo = startTime.month.toString().padLeft(2, '0');
      final d = startTime.day.toString().padLeft(2, '0');
      final h = startTime.hour.toString().padLeft(2, '0');
      final mi = startTime.minute.toString().padLeft(2, '0');
      final s = startTime.second.toString().padLeft(2, '0');
      startTimeStr = '$y-$mo-$d $h:$mi:$s';
    }
    final resp = await _dio.post('uc/agent/reward', queryParameters: {
      'pageNo': page.toString(),
      'pageSize': pageSize.toString(),
      if (startTimeStr != null) 'startTime': startTimeStr,
    });
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      final data = body['data'];
      if (data is Map && data['content'] is List) {
        return (data['content'] as List).cast<Map<String, dynamic>>();
      }
      if (data is List) return data.cast<Map<String, dynamic>>();
    }
    return [];
  }

  /// 获取返佣比例设置列表（对应安卓 uc/agent/reward/set/list）
  Future<List<Map<String, dynamic>>> getRewardSetList() async {
    final resp = await _dio.post('uc/agent/reward/set/list');
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      final data = body['data'];
      if (data is List) return data.cast<Map<String, dynamic>>();
    }
    return [];
  }

  /// 设置下级返佣比率（对应安卓 uc/agent/reward/set）
  Future<void> setReward({required String memberId, required int rate, int? followRate}) async {
    final params = <String, String>{
      'id': memberId,
      'rate': rate.toString(),
      if (followRate != null) 'followRate': followRate.toString(),
    };
    await _dio.post(
      'uc/agent/reward/set',
      data: params,
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
  }

  /// 获取今日统计（对应安卓 uc/agent/stat）
  Future<Map<String, dynamic>> getTotalAward({String? endDate}) async {
    final resp = await _dio.get('uc/agent/stat', queryParameters: {
      if (endDate != null) 'endDate': endDate,
    });
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      return (body['data'] as Map<String, dynamic>?) ?? {};
    }
    return {};
  }

  /// 提交经纪商申请
  /// 返回 null 表示成功，非空 String 为后端 message
  Future<String?> submitApply() async {
    try {
      await _dio.post('uc/agent/apply/submit', data: <String, dynamic>{});
      return null;
    } on DioException catch (e) {
      return extractDioMessage(e);
    }
  }

  /// 查询我的申请列表
  Future<List<Map<String, dynamic>>> getMyApplyList({int page = 1, int pageSize = 10}) async {
    final resp = await _dio.post('uc/agent/apply/my-list', data: {
      'pageNo': page,
      'pageSize': pageSize,
    });
    final body = resp.data;
    if (body is Map<String, dynamic>) {
      final data = body['data'];
      if (data is Map && data['content'] is List) {
        return (data['content'] as List).cast<Map<String, dynamic>>();
      }
      if (data is List) return data.cast<Map<String, dynamic>>();
    }
    return [];
  }

}

String extractDioMessage(DioException error) {
  final fromBody = messageFromResponseData(error.response?.data);
  if (fromBody.isNotEmpty) {
    return fromBody;
  }
  if (error.error is ApiException) {
    final msg = (error.error as ApiException).message.trim();
    if (msg.isNotEmpty) {
      return msg;
    }
  }
  return error.message?.trim() ?? '';
}

String messageFromResponseData(dynamic data) {
  if (data is Map) {
    final msg = data['message']?.toString().trim() ??
        data['msg']?.toString().trim() ??
        '';
    if (msg.isNotEmpty) {
      return msg;
    }
  }
  return '';
}

bool isAlreadyBrokerError(String message) {
  return message.contains('ALREADY_BROKER') ||
      message.contains('已经是经纪商') ||
      message.contains('已是经纪商');
}

bool isApplyPendingError(String message) {
  return message.contains('APPLY_PENDING') ||
      message.contains('经纪商申请正在审批') ||
      message.contains('正在审批') ||
      message.contains('正在审核') ||
      message.contains('待审核');
}

final brokerRepositoryProvider = Provider<BrokerRepository>((ref) {
  return BrokerRepository(ref.read(dioClientProvider));
});
