import 'dart:async';
import 'package:injectable/injectable.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:location/data/consts/constants.dart';
import 'package:location/di/get_it.dart';
import 'package:location/utils/atmob_log.dart';
import 'package:location/utils/permission_util.dart';
import '../device/atmob_platform_info.dart';
import '../dialog/net_error_dialog.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:network_info_plus/network_info_plus.dart';

@lazySingleton
class InternetConnectionHelper {
  InternetConnectionHelper();

  final String tag = 'InternetConnectionHelper';

  String? _networkName;

  NetworkType? networkType;

  StreamSubscription<InternetConnectionStatus>? _connectSubscription;
  StreamSubscription<List<ConnectivityResult>>? netTypeSubscription;

  // 控制延迟弹窗的 timer
  Timer? _disconnectTimer;

  // 当前是否显示了断网弹窗
  bool _isDialogVisible = false;

  final wifiInfo = NetworkInfo();

  final customChecker = InternetConnectionChecker.createInstance(
    checkInterval: Duration(seconds: 10),
    addresses: [
      AddressCheckOption(uri: Uri.parse('https://www.baidu.com')),
      AddressCheckOption(uri: Uri.parse('https://www.qq.com')),
      AddressCheckOption(uri: Uri.parse('https://www.aliyun.com')),
      AddressCheckOption(uri: Uri.parse('https://www.163.com')),
    ],
  );

  static InternetConnectionHelper getInstance() {
    return getIt<InternetConnectionHelper>();
  }

  Future<String?> getNetworkName() async {
    //如何网络情况不是wifi则直接返回
    if (networkType == NetworkType.mobile) {
      return _networkName;
    } else if (networkType == NetworkType.wifi) {
      if (_networkName?.isNotEmpty == true) {
        return _networkName;
      } else {
        return await _attemptGetWifiName();
      }
    } else {
      return null;
    }
  }

  /// 当前网络是否可用
  Future<bool> isConnected() {
    return customChecker.hasConnection;
  }

  void startListenNetwork() {
    netTypeSubscription?.cancel();
    netTypeSubscription = Connectivity()
        .onConnectivityChanged
        .listen((List<ConnectivityResult> result) {
      AtmobLog.d(tag, '网络类型:$result');
      if (result.contains(ConnectivityResult.wifi)) {
        //获取wif名称
        networkType = NetworkType.wifi;
        _attemptGetWifiName();
      } else if (result.contains(ConnectivityResult.none)) {
        networkType = NetworkType.none;
        _setNoNetworkName();
      } else {
        networkType = NetworkType.mobile;
        //其他情况都暂定为移动网络
        _setMobileNetworkName();
      }
    });
  }

  void stopListenNetwork() {
    netTypeSubscription?.cancel();
    netTypeSubscription = null;
  }

  void _setNoNetworkName() {
    _networkName = null;
    atmobPlatformInfo.setWifiName(null);
  }

  Future<String?> _attemptGetWifiName() async {
    //判断当前是否有权限
    if (!await PermissionUtil.checkLocationPermission()) {
      return null;
    }
    String? wifiName = await wifiInfo.getWifiName();
    wifiName = clean(wifiName);
    AtmobLog.d(tag, 'wifi名称：$wifiName');

    _networkName = wifiName;
    atmobPlatformInfo.setWifiName(wifiName);
    return wifiName;
  }

  static String? clean(String? ssid) {
    if (ssid == null || ssid.trim().isEmpty) return null;

    String trimmed = ssid.trim();

    if (trimmed.startsWith('"') &&
        trimmed.endsWith('"') &&
        trimmed.length >= 2) {
      return trimmed.substring(1, trimmed.length - 1);
    }

    return trimmed;
  }

  void _setMobileNetworkName() {
    _networkName = Constants.kMobileNetworkTag;
  }

  void startInternetConnection() {
    _connectSubscription?.cancel();
    _connectSubscription = customChecker.onStatusChange.listen(
      (InternetConnectionStatus status) {
        AtmobLog.d(tag, '网络连接情况:$status');
        if (status == InternetConnectionStatus.connected ||
            status == InternetConnectionStatus.slow) {
          // 网络恢复，取消延迟弹窗任务
          _disconnectTimer?.cancel();
          _disconnectTimer = null;

          // 关闭弹窗（如果已显示）
          if (_isDialogVisible) {
            NetErrorDialog.dismiss();
            _isDialogVisible = false;
          }
        } else {
          // 进入无网络状态，3秒内仍未恢复才弹窗
          _disconnectTimer?.cancel();
          _disconnectTimer = Timer(Duration(seconds: 3), () async {
            final stillDisconnected = !await isConnected();
            if (stillDisconnected && !_isDialogVisible) {
              NetErrorDialog.show();
              _isDialogVisible = true;
            }
          });
        }
      },
    );
  }

  void stopInternetConnection() {
    _connectSubscription?.cancel();
    _disconnectTimer?.cancel();
    _isDialogVisible = false;
  }
}

enum NetworkType {
  wifi,
  mobile,
  none,
}
