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

import 'package:qhd_prevention/tools/tools.dart';

import 'http/ApiService.dart';

/// 单例角标管理，多接口分模块更新及全局原生角标同步
class BadgeManager extends ChangeNotifier {
  BadgeManager._internal();
  static final BadgeManager _instance = BadgeManager._internal();
  factory BadgeManager() => _instance;

  // 各模块未读
  int _appCount = 0;
  int _appDysCount = 0; // 新增：待验收
  int _appDzgCount = 0; // 新增：待整改
  int _notifCount = 0;
  int _envInspectCount = 0;
  int _eightWorkCount = 0;

  /// 总未读角标数
  int get count => _appCount + _notifCount + _envInspectCount + _eightWorkCount;
  /// MainPage 整体“应用”角标
  int get appCount => _appCount;
  /// MainPage “待验收”子项
  int get appDysCount => _appDysCount;
  /// MainPage “待整改”子项
  int get appDzgCount => _appDzgCount;
  int get notifCount => _notifCount;
  int get envInspectCount => _envInspectCount;
  int get eightWorkCount => _eightWorkCount;

  /// 登录后或有用户上下文时，初始化所有接口汇总数，并同步原生角标
  Future<void> initAllModules() async {
    try {
      final results = await Future.wait([
        ApiService.getWork(),                            // 应用中心
        ApiService.getNotifRedPoint(),                   // 通知公告
        ApiService.getSafetyEnvironmentalInspectionCount(), // 安全巡检
        ApiService.getRedPoint(),                        // 八项作业
      ]);

      // 应用中心部分
      final workJson = results[0];
      final hid = workJson['hidCount'] as Map<String, dynamic>? ?? {};
      _appDysCount = (hid['dys'] ?? 0) as int;
      _appDzgCount = (hid['dzg'] ?? 0) as int;
      _appCount = _appDysCount + _appDzgCount;

      // 通知公告部分
      final notifJson = results[1];
      _notifCount = notifJson['count'] as int? ?? 0;

      // 安全巡检部分
      final checkJson = results[2];
      _envInspectCount =
          (checkJson['confirmCount']?['confirmCount'] ?? 0)
              (checkJson['repulseCount']?['repulseCount'] ?? 0)
              (checkJson['repulseAndCheckCount']?['repulseAndCheckCount'] ?? 0) as int;

      // 八项作业部分
      final redPointJson = results[3];
      _eightWorkCount = 0;
      (redPointJson['count'] as Map<String, dynamic>? ?? {}).values.forEach((v) {
        _eightWorkCount += (v ?? 0) as int;
      });

      _syncNative();
      notifyListeners();
    } catch (e) {
      debugPrint('BadgeManager.initAllModules error: $e');
    }
  }

  /// 更新 MainPage 的应用中心角标
  void updateAppCount() async {
    try {
      final workJson = await ApiService.getWork();
      final hid = workJson['hidCount'] as Map<String, dynamic>? ?? {};
      _appDysCount = (hid['dys'] ?? 0) as int;
      _appDzgCount = (hid['dzg'] ?? 0) as int;
      _appCount = _appDysCount + _appDzgCount;
      _onModuleChanged();
    } catch (e) {
      debugPrint('updateAppCount error: $e');
    }
  }

  /// 更新 MainPage 的通知公告角标
  void updateNotifCount() async {
    try {
      final notifJson = await ApiService.getNotifRedPoint();
      _notifCount = notifJson['count'] as int? ?? 0;
      _onModuleChanged();
    } catch (e) {
      debugPrint('updateNotifCount error: $e');
    }
  }

  /// 更新 HomePage 安全巡检角标
  void updateEnvInspectCount() async {
    try {
      final checkJson = await ApiService.getSafetyEnvironmentalInspectionCount();
      _envInspectCount =
          (checkJson['confirmCount']?['confirmCount'] ?? 0)
              (checkJson['repulseCount']?['repulseCount'] ?? 0)
              (checkJson['repulseAndCheckCount']?['repulseAndCheckCount'] ?? 0) as int;
      _onModuleChanged();
    } catch (e) {
      debugPrint('updateEnvInspectCount error: $e');
    }
  }

  /// 更新 HomePage 八项作业角标
  void updateEightWorkCount() async {
    try {
      final redPointJson = await ApiService.getRedPoint();
      int sum = 0;
      (redPointJson['count'] as Map<String, dynamic>? ?? {}).values.forEach((v) {
        sum += (v ?? 0) as int;
      });
      _eightWorkCount = sum;
      _onModuleChanged();
    } catch (e) {
      debugPrint('updateEightWorkCount error: $e');
    }
  }

  /// 清空所有角标
  void clearAll() {
    _appCount = _notifCount = _envInspectCount = _eightWorkCount = 0;
    _appDysCount = _appDzgCount = 0;
    _syncNative();
    notifyListeners();
  }

  void _onModuleChanged() {
    _syncNative();
    notifyListeners();
  }

  void _syncNative() {
    final total = count;
    if (total > 0) {
      FlutterNewBadger.setBadge(total);
    } else {
      FlutterNewBadger.removeBadge();
    }
  }
}
