import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_background/flutter_background.dart';

class BackgroundService {
  /// 单例实例
  static final BackgroundService _instance = BackgroundService._internal();

  /// 工厂构造函数
  factory BackgroundService() => _instance;

  /// 内部构造函数
  BackgroundService._internal();

  /// 是否已初始化
  bool _isInitialized = false;

  /// 是否正在后台运行
  bool _isRunningInBackground = false;

  /// 获取是否正在后台运行
  bool get isRunningInBackground => _isRunningInBackground;

  /// 初始化后台服务
  Future<bool> initialize() async {
    if (_isInitialized) {
      return true;
    }

    // 配置 Android 后台服务
    final androidConfig = FlutterBackgroundAndroidConfig(
      notificationTitle: "应用正在后台运行",
      notificationText: "点击查看详情",
      notificationImportance: AndroidNotificationImportance.normal,
      notificationIcon: AndroidResource(
        name: 'ic_launcher',
        defType: 'mipmap',
      ),
    );

    // 初始化后台服务
    bool success = await FlutterBackground.initialize(androidConfig: androidConfig);
    _isInitialized = success;
    return success;
  }

  /// 启用后台服务
  Future<bool> enableBackgroundExecution() async {
    if (!_isInitialized) {
      bool initialized = await initialize();
      if (!initialized) {
        return false;
      }
    }

    // 启用后台执行
    bool success = await FlutterBackground.enableBackgroundExecution();
    _isRunningInBackground = success;
    return success;
  }

  /// 禁用后台服务
  Future<bool> disableBackgroundExecution() async {
    if (!_isInitialized) {
      return false;
    }

    // 禁用后台执行
    bool success = await FlutterBackground.disableBackgroundExecution();
    _isRunningInBackground = !success;
    return success;
  }

  /// 在后台执行任务
  Future<void> runInBackground(VoidCallback task) async {
    // 确保后台服务已启用
    if (!_isRunningInBackground) {
      bool enabled = await enableBackgroundExecution();
      if (!enabled) {
        return;
      }
    }

    // 执行任务
    task();
  }
}