import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../config/app_config.dart';

/// 系统维护状态
class MaintenanceStatus {
  final bool isUnderMaintenance;
  final MaintenanceInfo? maintenance;

  const MaintenanceStatus({
    required this.isUnderMaintenance,
    this.maintenance,
  });

  factory MaintenanceStatus.fromJson(Map<String, dynamic> json) {
    return MaintenanceStatus(
      isUnderMaintenance: json['isUnderMaintenance'] ?? false,
      maintenance: json['maintenance'] != null
          ? MaintenanceInfo.fromJson(json['maintenance'])
          : null,
    );
  }

  /// 无维护状态
  static const normal = MaintenanceStatus(isUnderMaintenance: false);
}

/// 维护详情
class MaintenanceInfo {
  final String title;
  final String message;
  final DateTime startTime;
  final DateTime endTime;
  final int remainingMinutes;

  const MaintenanceInfo({
    required this.title,
    required this.message,
    required this.startTime,
    required this.endTime,
    required this.remainingMinutes,
  });

  factory MaintenanceInfo.fromJson(Map<String, dynamic> json) {
    return MaintenanceInfo(
      title: json['title'] ?? '系统维护中',
      message: json['message'] ?? '系统正在维护，请稍后再试',
      startTime: DateTime.parse(json['startTime']),
      endTime: DateTime.parse(json['endTime']),
      remainingMinutes: json['remainingMinutes'] ?? 0,
    );
  }
}

/// 系统维护检查服务
///
/// 独立的服务，不依赖 ApiClient，因为：
/// 1. 需要在用户登录前检查
/// 2. 需要绕过 ApiClient 的 token 逻辑
/// 3. 维护接口不需要认证
class MaintenanceService {
  static final MaintenanceService _instance = MaintenanceService._internal();
  factory MaintenanceService() => _instance;
  MaintenanceService._internal();

  late final Dio _dio;
  bool _initialized = false;

  /// 初始化服务
  void initialize() {
    if (_initialized) return;

    _dio = Dio(BaseOptions(
      baseUrl: AppConfig.instance.apiBaseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ));

    _initialized = true;
    debugPrint('[MaintenanceService] 初始化完成');
  }

  /// 检查系统维护状态
  ///
  /// 返回维护状态，如果发生网络错误返回正常状态（容错处理）
  Future<MaintenanceStatus> checkStatus() async {
    if (!_initialized) {
      initialize();
    }

    try {
      final response = await _dio.get('/mobile/system/maintenance-status');

      if (response.statusCode == 200) {
        final data = response.data;
        return MaintenanceStatus.fromJson(data);
      }

      // 非 200 响应，返回正常状态
      return MaintenanceStatus.normal;
    } on DioException catch (e) {
      debugPrint('[MaintenanceService] 检查维护状态失败: ${e.message}');
      // 网络错误时返回正常状态，避免阻断用户
      // 只有明确收到维护状态时才阻断
      return MaintenanceStatus.normal;
    } catch (e) {
      debugPrint('[MaintenanceService] 检查维护状态异常: $e');
      return MaintenanceStatus.normal;
    }
  }
}
