import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../storage/local_storage.dart';
import '../storage/storage_keys.dart';

/// 客服联系方式数据模型
class CustomerServiceContactData {
  final String id;
  final String type; // 'WECHAT' | 'QQ'
  final String label;
  final String value;
  final int sortOrder;

  const CustomerServiceContactData({
    required this.id,
    required this.type,
    required this.label,
    required this.value,
    required this.sortOrder,
  });

  factory CustomerServiceContactData.fromJson(Map<String, dynamic> json) {
    return CustomerServiceContactData(
      id: json['id'] as String,
      type: json['type'] as String,
      label: json['label'] as String,
      value: json['value'] as String,
      sortOrder: json['sortOrder'] as int,
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'type': type,
        'label': label,
        'value': value,
        'sortOrder': sortOrder,
      };

  bool get isWechat => type == 'WECHAT';
  bool get isQQ => type == 'QQ';
}

/// 客服联系方式服务
///
/// 策略与 AppAssetService 一致：
///   1. 优先使用 SharedPreferences 中的持久化缓存
///   2. 后台静默刷新，成功后更新缓存
///   3. 缓存为空时返回空列表
class CustomerServiceContactService {
  final ApiClient _apiClient;
  final LocalStorage _localStorage;

  /// 内存缓存
  List<CustomerServiceContactData>? _memoryCache;

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

  /// 上次网络请求时间
  DateTime? _lastFetchTime;

  CustomerServiceContactService({
    required ApiClient apiClient,
    required LocalStorage localStorage,
  })  : _apiClient = apiClient,
        _localStorage = localStorage;

  /// 获取客服联系方式列表
  ///
  /// 返回顺序：内存缓存 → 持久化缓存 → 空列表
  /// 同时在后台静默刷新数据。
  Future<List<CustomerServiceContactData>> getContacts({bool forceRefresh = false}) async {
    // 1. 检查内存缓存
    if (!forceRefresh && _memoryCache != null && _lastFetchTime != null) {
      final cacheAge = DateTime.now().difference(_lastFetchTime!);
      if (cacheAge < _cacheExpiration) {
        return _memoryCache!;
      }
    }

    // 2. 从 SharedPreferences 加载
    if (_memoryCache == null) {
      try {
        final cachedJson = _localStorage.getString(StorageKeys.cachedCustomerServiceContacts);
        if (cachedJson != null && cachedJson.isNotEmpty) {
          final list = jsonDecode(cachedJson) as List<dynamic>;
          _memoryCache = list
              .map((e) => CustomerServiceContactData.fromJson(e as Map<String, dynamic>))
              .toList()
            ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
          debugPrint('[CustomerServiceContactService] 从持久化缓存加载: ${_memoryCache!.length} contacts');
        }
      } catch (e) {
        debugPrint('[CustomerServiceContactService] 读取持久化缓存失败: $e');
      }
    }

    // 3. 后台静默刷新
    _refreshInBackground();

    return _memoryCache ?? [];
  }

  /// 后台静默刷新
  void _refreshInBackground() {
    _fetchFromApi().then((contacts) {
      if (contacts != null) {
        _memoryCache = contacts;
        _lastFetchTime = DateTime.now();
        // 持久化
        final jsonStr = jsonEncode(contacts.map((e) => e.toJson()).toList());
        _localStorage.setString(StorageKeys.cachedCustomerServiceContacts, jsonStr);
        debugPrint('[CustomerServiceContactService] 后台刷新成功: ${contacts.length} contacts');
      }
    }).catchError((e) {
      debugPrint('[CustomerServiceContactService] 后台刷新失败: $e');
    });
  }

  /// 从 API 获取数据
  Future<List<CustomerServiceContactData>?> _fetchFromApi() async {
    try {
      final response = await _apiClient.get('/customer-service-contacts');
      List<dynamic>? list;
      if (response.data is List) {
        list = response.data as List;
      } else if (response.data is Map && response.data['data'] is List) {
        list = response.data['data'] as List;
      }
      if (list != null) {
        return list
            .map((e) => CustomerServiceContactData.fromJson(e as Map<String, dynamic>))
            .toList()
          ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
      }
      return null;
    } catch (e) {
      debugPrint('[CustomerServiceContactService] API 请求失败: $e');
      return null;
    }
  }
}
