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

/// 认种订单状态
enum PlantingOrderStatus {
  created,           // 已创建
  provinceCitySelected,  // 已选择省市
  provinceCityConfirmed, // 已确认省市
  paid,              // 已支付
  fundAllocated,     // 资金已分配
  miningEnabled,     // 挖矿已启用
  cancelled,         // 已取消
}

/// 认种订单响应
class PlantingOrder {
  final String orderNo;
  final int treeCount;
  final double totalAmount;
  final PlantingOrderStatus status;
  final String? selectedProvince;
  final String? selectedCity;
  final DateTime? provinceCitySelectedAt;
  final DateTime? provinceCityConfirmedAt;
  final DateTime? paidAt;
  final bool isMiningEnabled;
  final DateTime createdAt;

  PlantingOrder({
    required this.orderNo,
    required this.treeCount,
    required this.totalAmount,
    required this.status,
    this.selectedProvince,
    this.selectedCity,
    this.provinceCitySelectedAt,
    this.provinceCityConfirmedAt,
    this.paidAt,
    required this.isMiningEnabled,
    required this.createdAt,
  });

  factory PlantingOrder.fromJson(Map<String, dynamic> json) {
    return PlantingOrder(
      orderNo: json['orderNo'] ?? '',
      treeCount: json['treeCount'] ?? 0,
      totalAmount: (json['totalAmount'] ?? 0).toDouble(),
      status: _parseStatus(json['status']),
      selectedProvince: json['selectedProvince'],
      selectedCity: json['selectedCity'],
      provinceCitySelectedAt: json['provinceCitySelectedAt'] != null
          ? DateTime.parse(json['provinceCitySelectedAt'])
          : null,
      provinceCityConfirmedAt: json['provinceCityConfirmedAt'] != null
          ? DateTime.parse(json['provinceCityConfirmedAt'])
          : null,
      paidAt: json['paidAt'] != null ? DateTime.parse(json['paidAt']) : null,
      isMiningEnabled: json['isMiningEnabled'] ?? false,
      createdAt: json['createdAt'] != null
          ? DateTime.parse(json['createdAt'])
          : DateTime.now(),
    );
  }

  static PlantingOrderStatus _parseStatus(String? status) {
    switch (status) {
      case 'CREATED':
        return PlantingOrderStatus.created;
      case 'PROVINCE_CITY_SELECTED':
        return PlantingOrderStatus.provinceCitySelected;
      case 'PROVINCE_CITY_CONFIRMED':
        return PlantingOrderStatus.provinceCityConfirmed;
      case 'PAID':
        return PlantingOrderStatus.paid;
      case 'FUND_ALLOCATED':
        return PlantingOrderStatus.fundAllocated;
      case 'MINING_ENABLED':
        return PlantingOrderStatus.miningEnabled;
      case 'CANCELLED':
        return PlantingOrderStatus.cancelled;
      default:
        return PlantingOrderStatus.created;
    }
  }
}

/// 创建订单响应
class CreateOrderResponse {
  final String orderNo;
  final int treeCount;
  final double totalAmount;
  final double pricePerTree;

  CreateOrderResponse({
    required this.orderNo,
    required this.treeCount,
    required this.totalAmount,
    required this.pricePerTree,
  });

  factory CreateOrderResponse.fromJson(Map<String, dynamic> json) {
    return CreateOrderResponse(
      orderNo: json['orderNo'] ?? '',
      treeCount: json['treeCount'] ?? 0,
      totalAmount: (json['totalAmount'] ?? 0).toDouble(),
      pricePerTree: (json['pricePerTree'] ?? 15831).toDouble(),
    );
  }
}

/// 用户持仓信息
class PlantingPosition {
  final int totalTreeCount;
  final int effectiveTreeCount;
  final int pendingTreeCount;

  PlantingPosition({
    required this.totalTreeCount,
    required this.effectiveTreeCount,
    required this.pendingTreeCount,
  });

  factory PlantingPosition.fromJson(Map<String, dynamic> json) {
    return PlantingPosition(
      totalTreeCount: json['totalTreeCount'] ?? 0,
      effectiveTreeCount: json['effectiveTreeCount'] ?? 0,
      pendingTreeCount: json['pendingTreeCount'] ?? 0,
    );
  }
}

/// 认种服务
///
/// 提供认种订单创建、省市选择、支付等功能
class PlantingService {
  final ApiClient _apiClient;

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

  /// 获取我的持仓信息
  ///
  /// 返回用户的总认种数量、有效数量、待生效数量
  Future<PlantingPosition> getMyPosition() async {
    try {
      debugPrint('[PlantingService] 获取我的持仓信息');

      final response = await _apiClient.get('/planting/position');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[PlantingService] 持仓信息: totalTreeCount=${data['totalTreeCount']}');
        return PlantingPosition.fromJson(data);
      }

      throw Exception('获取持仓信息失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 获取持仓信息失败: $e');
      rethrow;
    }
  }

  /// 创建认种订单
  ///
  /// [treeCount] 认种数量
  /// 返回订单号和总金额
  Future<CreateOrderResponse> createOrder(int treeCount) async {
    try {
      debugPrint('[PlantingService] 创建认种订单: treeCount=$treeCount');

      final response = await _apiClient.post(
        '/planting/orders',
        data: {'treeCount': treeCount},
      );

      if (response.statusCode == 201 || response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[PlantingService] 订单创建成功: ${data['orderNo']}');
        return CreateOrderResponse.fromJson(data);
      }

      throw Exception('创建订单失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 创建订单失败: $e');
      rethrow;
    }
  }

  /// 选择省市
  ///
  /// [orderNo] 订单号
  /// [provinceCode] 省份代码
  /// [provinceName] 省份名称
  /// [cityCode] 城市代码
  /// [cityName] 城市名称
  Future<PlantingOrder> selectProvinceCity(
    String orderNo, {
    required String provinceCode,
    required String provinceName,
    required String cityCode,
    required String cityName,
  }) async {
    try {
      debugPrint('[PlantingService] 选择省市: orderNo=$orderNo');
      debugPrint('[PlantingService]   provinceCode=$provinceCode, provinceName=$provinceName');
      debugPrint('[PlantingService]   cityCode=$cityCode, cityName=$cityName');

      final response = await _apiClient.post(
        '/planting/orders/$orderNo/select-province-city',
        data: {
          'provinceCode': provinceCode,
          'provinceName': provinceName,
          'cityCode': cityCode,
          'cityName': cityName,
        },
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[PlantingService] 省市选择成功');
        return PlantingOrder.fromJson(data);
      }

      throw Exception('选择省市失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 选择省市失败: $e');
      rethrow;
    }
  }

  /// 确认省市选择
  ///
  /// [orderNo] 订单号
  /// 确认后不可修改省市
  Future<PlantingOrder> confirmProvinceCity(String orderNo) async {
    try {
      debugPrint('[PlantingService] 确认省市选择: orderNo=$orderNo');

      final response = await _apiClient.post(
        '/planting/orders/$orderNo/confirm-province-city',
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[PlantingService] 省市确认成功');
        return PlantingOrder.fromJson(data);
      }

      throw Exception('确认省市失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 确认省市失败: $e');
      rethrow;
    }
  }

  /// 支付订单
  ///
  /// [orderNo] 订单号
  /// 支付成功后开始挖矿
  Future<PlantingOrder> payOrder(String orderNo) async {
    try {
      debugPrint('[PlantingService] 支付订单: orderNo=$orderNo');

      final response = await _apiClient.post(
        '/planting/orders/$orderNo/pay',
      );

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('[PlantingService] 支付成功');
        return PlantingOrder.fromJson(data);
      }

      throw Exception('支付失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 支付失败: $e');
      rethrow;
    }
  }

  /// 获取订单详情
  ///
  /// [orderNo] 订单号
  Future<PlantingOrder> getOrder(String orderNo) async {
    try {
      debugPrint('[PlantingService] 获取订单详情: orderNo=$orderNo');

      final response = await _apiClient.get('/planting/orders/$orderNo');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        return PlantingOrder.fromJson(data);
      }

      throw Exception('获取订单失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 获取订单失败: $e');
      rethrow;
    }
  }

  /// 获取我的订单列表
  ///
  /// [page] 页码
  /// [pageSize] 每页数量
  Future<List<PlantingOrder>> getMyOrders({int page = 1, int pageSize = 20}) async {
    try {
      debugPrint('[PlantingService] 获取我的订单列表: page=$page, pageSize=$pageSize');

      final response = await _apiClient.get(
        '/planting/orders',
        queryParameters: {
          'page': page,
          'pageSize': pageSize,
        },
      );

      if (response.statusCode == 200) {
        // 兼容两种格式：直接数组 [...] 或包装格式 {items: [...]}
        List<dynamic> items;
        if (response.data is List) {
          items = response.data as List<dynamic>;
        } else if (response.data is Map<String, dynamic>) {
          final data = response.data as Map<String, dynamic>;
          items = data['items'] as List<dynamic>? ?? [];
        } else {
          items = [];
        }
        return items.map((e) => PlantingOrder.fromJson(e as Map<String, dynamic>)).toList();
      }

      throw Exception('获取订单列表失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 获取订单列表失败: $e');
      rethrow;
    }
  }

  /// 取消订单
  ///
  /// [orderNo] 订单号
  /// 只有未支付的订单可以取消
  Future<void> cancelOrder(String orderNo) async {
    try {
      debugPrint('[PlantingService] 取消订单: orderNo=$orderNo');

      final response = await _apiClient.post(
        '/planting/orders/$orderNo/cancel',
      );

      if (response.statusCode == 200) {
        debugPrint('[PlantingService] 订单取消成功');
        return;
      }

      throw Exception('取消订单失败: ${response.statusCode}');
    } catch (e) {
      debugPrint('[PlantingService] 取消订单失败: $e');
      rethrow;
    }
  }
}
