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

/// [2026-02-26] 认种树定价配置
///
/// 总部运营成本压力涨价：基础价不变，加价部分全额归总部。
/// - 正式认种总价 = basePrice + currentSupplement
/// - 预种总价 = totalPrice / 10（取整）
class TreePricingConfig {
  /// 正式认种基础价（固定 15831）
  final int basePrice;

  /// 预种基础价（固定 1887）
  final int basePortionPrice;

  /// 当前加价金额
  final int currentSupplement;

  /// 正式认种总价 = basePrice + currentSupplement
  final int totalPrice;

  /// 预种总价 = totalPrice / 5
  final int totalPortionPrice;

  /// 是否启用自动涨价
  final bool autoIncreaseEnabled;

  /// 自动涨价金额
  final int autoIncreaseAmount;

  /// 自动涨价间隔天数
  final int autoIncreaseIntervalDays;

  /// 下次自动涨价时间
  final DateTime? nextAutoIncreaseAt;

  TreePricingConfig({
    required this.basePrice,
    required this.basePortionPrice,
    required this.currentSupplement,
    required this.totalPrice,
    required this.totalPortionPrice,
    required this.autoIncreaseEnabled,
    required this.autoIncreaseAmount,
    required this.autoIncreaseIntervalDays,
    this.nextAutoIncreaseAt,
  });

  factory TreePricingConfig.fromJson(Map<String, dynamic> json) {
    return TreePricingConfig(
      basePrice: json['basePrice'] ?? 15831,
      basePortionPrice: json['basePortionPrice'] ?? 1887,
      currentSupplement: json['currentSupplement'] ?? 0,
      totalPrice: json['totalPrice'] ?? 15831,
      totalPortionPrice: json['totalPortionPrice'] ?? 1887,
      autoIncreaseEnabled: json['autoIncreaseEnabled'] ?? false,
      autoIncreaseAmount: json['autoIncreaseAmount'] ?? 0,
      autoIncreaseIntervalDays: json['autoIncreaseIntervalDays'] ?? 0,
      nextAutoIncreaseAt: json['nextAutoIncreaseAt'] != null
          ? DateTime.tryParse(json['nextAutoIncreaseAt'])
          : null,
    );
  }

  /// 默认配置（supplement=0，与原硬编码价格一致）
  factory TreePricingConfig.defaultConfig() {
    return TreePricingConfig(
      basePrice: 15831,
      basePortionPrice: 1887,
      currentSupplement: 0,
      totalPrice: 15831,
      totalPortionPrice: 1887,
      autoIncreaseEnabled: false,
      autoIncreaseAmount: 0,
      autoIncreaseIntervalDays: 0,
    );
  }
}

/// 认种树定价配置服务
///
/// 从 admin-service 公开接口获取当前定价，5 分钟缓存。
/// 失败时安全降级返回默认配置（supplement=0）。
class TreePricingService {
  final ApiClient _apiClient;

  /// 缓存的定价配置
  TreePricingConfig? _cachedConfig;

  /// 上次获取时间
  DateTime? _lastFetchTime;

  /// 缓存有效期（5 分钟）
  static const Duration _cacheExpiration = Duration(minutes: 5);

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

  /// 获取当前定价配置
  ///
  /// [forceRefresh] 强制刷新，不使用缓存
  Future<TreePricingConfig> getConfig({bool forceRefresh = false}) async {
    // 检查缓存是否有效
    if (!forceRefresh && _cachedConfig != null && _lastFetchTime != null) {
      final cacheAge = DateTime.now().difference(_lastFetchTime!);
      if (cacheAge < _cacheExpiration) {
        return _cachedConfig!;
      }
    }

    try {
      final response = await _apiClient.get(
        '/tree-pricing/config',
      );

      _cachedConfig = TreePricingConfig.fromJson(response.data);
      _lastFetchTime = DateTime.now();

      debugPrint(
        '[TreePricingService] 获取定价成功: totalPrice=${_cachedConfig!.totalPrice}, '
        'totalPortionPrice=${_cachedConfig!.totalPortionPrice}, '
        'supplement=${_cachedConfig!.currentSupplement}',
      );

      return _cachedConfig!;
    } catch (e) {
      debugPrint('[TreePricingService] 获取定价失败: $e');

      // 有缓存则返回缓存，否则返回默认配置（安全降级）
      return _cachedConfig ?? TreePricingConfig.defaultConfig();
    }
  }

  /// 清除缓存
  void clearCache() {
    _cachedConfig = null;
    _lastFetchTime = null;
  }
}
