import 'package:flutter/material.dart';
import '../core/network/api_response.dart';
import '../core/network/dio_client.dart';
import '../data/models/account_models.dart';
import '../data/models/order_models.dart';
import '../data/services/asset_service.dart';
import '../data/services/fund_service.dart';

/// 资产状态管理
class AssetProvider extends ChangeNotifier {
  final AssetService _assetService;
  final FundService _fundService;

  AssetOverview? _overview;
  AccountFund? _fundAccount;
  List<AccountTrade> _tradeAccounts = [];
  List<AccountFlow> _flows = [];
  List<OrderFund> _fundOrders = [];
  bool _isLoading = false;
  bool _isLoadingFlows = false;
  bool _isLoadingOrders = false;
  String? _error;

  // 加载状态标记，防止重复加载
  bool _overviewLoaded = false;
  bool _fundAccountLoaded = false;
  bool _tradeAccountLoaded = false;

  AssetProvider(this._assetService, this._fundService);

  // Getters
  AssetOverview? get overview => _overview;
  AccountFund? get fundAccount => _fundAccount;
  List<AccountTrade> get tradeAccounts => _tradeAccounts;
  List<AccountTrade> get holdings => _tradeAccounts;
  List<AccountFlow> get flows => _flows;
  List<OrderFund> get fundOrders => _fundOrders;
  bool get isLoading => _isLoading;
  bool get isLoadingFlows => _isLoadingFlows;
  bool get isLoadingOrders => _isLoadingOrders;
  String? get error => _error;

  /// 加载资产总览
  Future<void> loadOverview({bool force = false}) async {
    // 如果已经加载过且不是强制刷新，则跳过
    if (_overviewLoaded && !force && _overview != null) {
      return;
    }

    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final response = await _assetService.getOverview();
      if (response.success) {
        _overview = response.data;
        _overviewLoaded = true;
      } else {
        _error = response.message;
      }
    } catch (e) {
      _error = '加载失败: $e';
    }

    _isLoading = false;
    notifyListeners();
  }

  /// 加载资金账户
  Future<void> loadFundAccount({bool force = false}) async {
    // 如果已经加载过且不是强制刷新，则跳过
    if (_fundAccountLoaded && !force && _fundAccount != null) {
      return;
    }

    try {
      final response = await _assetService.getFundAccount();
      if (response.success) {
        _fundAccount = response.data;
        _fundAccountLoaded = true;
        notifyListeners();
      }
    } catch (_) {
      // 忽略错误
    }
  }

  /// 加载交易账户
  Future<void> loadTradeAccount({bool force = false}) async {
    // 如果已经加载过且不是强制刷新，则跳过
    if (_tradeAccountLoaded && !force && _tradeAccounts.isNotEmpty) {
      return;
    }

    try {
      final response = await _assetService.getTradeAccount();
      if (response.success) {
        _tradeAccounts = response.data ?? [];
        _tradeAccountLoaded = true;
        notifyListeners();
      }
    } catch (_) {
      // 忽略错误
    }
  }

  /// 加载资金流水
  Future<void> loadFlows({int? flowType, int pageNum = 1}) async {
    _isLoadingFlows = true;
    notifyListeners();

    try {
      final response = await _assetService.getFlow(
        flowType: flowType,
        pageNum: pageNum,
      );
      if (response.success && response.data != null) {
        final list = response.data!['list'] as List?;
        _flows = list?.map((e) => AccountFlow.fromJson(e as Map<String, dynamic>)).toList() ?? [];
      }
    } catch (_) {
      // 忽略错误
    }

    _isLoadingFlows = false;
    notifyListeners();
  }

  /// 划转资金
  Future<ApiResponse<void>> transfer({
    required int direction,
    required String amount,
  }) async {
    try {
      final response = await _assetService.transfer(
        direction: direction,
        amount: amount,
      );
      if (response.success) {
        // 强制刷新数据
        await loadOverview(force: true);
        await loadFundAccount(force: true);
        await loadTradeAccount(force: true);
      }
      return response;
    } catch (e) {
      return ApiResponse.fail('划转失败: $e');
    }
  }

  /// 充值 - 返回订单详情包含钱包地址
  Future<ApiResponse<Map<String, dynamic>>> deposit({required String amount, String? remark}) async {
    try {
      final response = await _fundService.deposit(amount: amount, remark: remark);
      if (response.success) {
        await loadOverview(force: true);
        await loadFundAccount(force: true);
      }
      return response;
    } catch (e) {
      return ApiResponse.fail('充值申请失败: $e');
    }
  }

  /// 确认已打款
  Future<ApiResponse<void>> confirmPay(String orderNo) async {
    try {
      final response = await _fundService.confirmPay(orderNo);
      if (response.success) {
        await loadFundOrders();
      }
      return response;
    } catch (e) {
      return ApiResponse.fail('确认打款失败: $e');
    }
  }

  /// 提现
  Future<ApiResponse<Map<String, dynamic>>> withdraw({
    required String amount,
    required String withdrawAddress,
    String? withdrawContact,
    String? remark,
  }) async {
    try {
      final response = await _fundService.withdraw(
        amount: amount,
        withdrawAddress: withdrawAddress,
        withdrawContact: withdrawContact,
        remark: remark,
      );
      if (response.success) {
        await loadOverview(force: true);
        await loadFundAccount(force: true);
      }
      return response;
    } catch (e) {
      return ApiResponse.fail('提现申请失败: $e');
    }
  }

  /// 加载充提订单
  Future<void> loadFundOrders({int? type, int pageNum = 1, int pageSize = 20}) async {
    _isLoadingOrders = true;
    notifyListeners();

    try {
      final response = await _fundService.getOrders(
        type: type,
        pageNum: pageNum,
        pageSize: pageSize,
      );
      if (response.success && response.data != null) {
        final list = response.data!['list'] as List?;
        _fundOrders = _fundService.parseOrderList(list);
      }
    } catch (_) {
      // 忽略错误
    }

    _isLoadingOrders = false;
    notifyListeners();
  }

  /// 取消订单
  Future<ApiResponse<void>> cancelOrder(String orderNo) async {
    try {
      final response = await _fundService.cancelOrder(orderNo);
      if (response.success) {
        await loadFundOrders();
        await loadFundAccount();
      }
      return response;
    } catch (e) {
      return ApiResponse.fail('取消订单失败: $e');
    }
  }

  /// 刷新所有资产数据
  Future<void> refreshAll({bool force = false}) async {
    await Future.wait([
      loadOverview(force: force),
      loadFundAccount(force: force),
      loadTradeAccount(force: force),
    ]);
  }

  /// 重置加载状态（用于退出登录时）
  void resetLoadState() {
    _overviewLoaded = false;
    _fundAccountLoaded = false;
    _tradeAccountLoaded = false;
    _overview = null;
    _fundAccount = null;
    _tradeAccounts = [];
    _flows = [];
    _fundOrders = [];
    _error = null;
    notifyListeners();
  }
}
