import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:naiyouwl/app/bean/proxie.dart';
import 'package:naiyouwl/app/common/LogHelper.dart';
import 'package:naiyouwl/app/common/SharedPreferencesUtil.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/data/model/NodeMode.dart';
import 'package:naiyouwl/app/network/api_service.dart';
import 'package:proxy_manager/proxy_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:window_manager/window_manager.dart';
import 'package:path/path.dart' as path;
import 'package:wl_base_help/wl_base_help.dart';
import '../common/constants.dart';
import '../const/const.dart';
import '../data/model/UserMode.dart';
import '../network/dio_client.dart';
import '../utils/shell.dart';
import '../utils/utils.dart';

class GlobalController extends GetxController {
  final proxyManager = ProxyManager();
  var systemProxy = false.obs;
  late BuildContext context;
  final List<String> modes = ['rule', 'global'];
  final List<String> routeModes = ['sys', 'tun'];
  var msgStatus = "未连接".obs;
  var routeModesSelect = "sys".obs;
  var modesSelect = "rule".obs;
  var nodeModes = <NodeMode>[].obs;
  var isLoading = false.obs;
  var errorMsg = ''.obs;
  var statusCode = 0.obs;
  var selectMageNode = false.obs;
  var systemProxySwitchIng = false.obs;
  var tunProxySwitchIng = false.obs;
  var nodeId = 0.obs;
  bool allowStatusUpdate = false;
  final _wlBaseHelpPlugin = WlBaseHelp();
  var sysInfo = ''.obs;
  var sysVersion = kVersion.obs;
  var connectStatus = false.obs;

  final selectedNode = Rx<NodeMode?>(null);

  final List<String> groupInternalTypes = ['DIRECT', 'REJECT', 'GLOBAL'];
  final List<String> groupTypes = [
    ProxieProxieType.selector,
    ProxieProxieType.urltest,
    ProxieProxieType.fallback,
    ProxieProxieType.loadbalance,
  ];

  Future<void> init(BuildContext context) async {
    this.context = context;
    watchExit();
    await controllers.config.initConfig();
    await controllers.cc_service.initConfig();
    sysInfo.value =  await platformState();
    await SharedPreferencesUtil().delete("last_successful_url");
    await controllers.tray.initTray();
    controllers.window.initWindow();
    await controllers.cc_service.isCanOperationService();
  }

  Future<bool> checkAllCoresStopped() async {
    bool allStopped = true;

    // 检查 Clash 核心是否已停止
    if (Platform.isWindows) {
      allStopped =  controllers.service.coreStatus.value == RunningState.running;
    } else if (Platform.isMacOS) {
      if(await controllers.cc_service.isCanOperationService()){
        allStopped = controllers.cc_service.coreStatus.value == RunningState.running;
      } else {
        allStopped =  controllers.service.coreStatus.value == RunningState.running;
      }

    }

    // 检查其他可能的核心进程
    // if (!controllers.service.serviceMode.value) {
    //   if (Platform.isWindows) {
    //     allStopped = allStopped && !(await isProcessRunning(path.basename(Files.assetsClashService.path)));
    //   }
    //   allStopped = allStopped && !(await isProcessRunning(path.basename(Files.assetsCCore.path)));
    //   allStopped = allStopped && !(await isProcessRunning(path.basename(Files.assetsClashService.path)));
    // }

    return allStopped;
  }

  Future<bool> isProcessRunning(String processName) async {
    try {
      String command = Platform.isWindows ? 'tasklist' : 'ps aux';
      ProcessResult result = await Process.run(command, []);
      return result.stdout.toString().contains(processName);
    } catch (e) {
      print('检查进程运行状态时出错: $e');
      return false;
    }
  }


  Future<void> checkAndStopIfPortsOccupied() async {
    List<int> portsToCheck = [
      controllers.config.mixedPort.value,
      controllers.config.apiAddressPort.value,
      controllers.config.servicePort.value
    ];

    for (int port in portsToCheck) {
      if (!(await isPortAvailable(port))) {
        LogHelper().d('端口 $port 被占用，正在停止所有内核');
        await stopAllCore();
        updateMsg('端口被占用，已停止所有内核');
        return;
      }
    }
  }

  @override
  void onInit() {
    super.onInit();
    // checkAndStopIfPortsOccupied();
  }

  void updateMsg(String msg) {
    msgStatus.value = msg;
  }

  Future<void> updateMode(String route) async {
    if(allowStatusUpdate) return;
    modesSelect.value = route;
    await controllers.core.fetchConfigUpdate({
      "mode": modesSelect.value
    });
    await controllers.global.swift(selectedNode.value?.name ?? "");
  }

  void updateUserInfo(User user) {
    update();
  }

  Future<void> updateRoute(String route) async {
    if(allowStatusUpdate) return;
    routeModesSelect.value = route;
    LogHelper().d("当前ROUTE模式${routeModesSelect.value}");
  }

  Future<void> fetchNodes() async {
    nodeModes.value = await ApiService().getNode("/api/client/v4/nodes?vless=1");
  }

  Future<void> updateNode() async {
    NodeMode? targetNode;
    if (selectedNode.value == null) {
      targetNode = await findNodeWithMinUsers(nodeModes);
      selectedNode.value = targetNode;
    } else {
      targetNode = selectedNode.value;
    }
    if (targetNode != null){
      selectNode(targetNode);
      await swift(targetNode.name ?? "");
    }
  }

  Future<void> showConsole() async {
    await _wlBaseHelpPlugin.showConsole();
  }

  Future<void> hideConsole() async {
    await _wlBaseHelpPlugin.hideConsole();
  }

  Future<void> swift(String name) async {
    try{
      var g = "proxy";
      if(modesSelect.value == "global") {
        g = "GLOBAL";
      }

      await controllers.core.fetchSetProxieGroup(g, name);
      final conn = await controllers.core.fetchConnection();
      if(conn == null) return;
      for (final it in conn.connections) {
        if (it.chains.contains(name)) controllers.core.fetchCloseConnections(it.id);
      }
    } catch (e) {
      //LogHelper().d(e.toString());
    }
  }
  // 创建代理配置文件
  Future<void> makeProxy() async {
    // final clashService = ClashService();
    //if (!await Paths.config.exists()) await Paths.config.create(recursive: true);
    await controllers.service.saveConfigToFile(path.join(Paths.config.path, Files.makeProxyConfig.path), nodeModes);
  }
  Future<NodeMode> findNodeWithMinUsers(List<NodeMode> nodes) async {
    return nodes
        .where((node) => node.countryCode == "hk")
        .reduce((a, b) => a.onlineUsers! < b.onlineUsers! ? a : b);
  }


  Future<void> TunProxySwitch(bool open) async {
    tunProxySwitchIng.value = true;
    routeModesSelect.value = open ? "tun": "sys";
    LogHelper().d("TunProxySwitch ----- 当前ROUTE模式${routeModesSelect.value}");
    tunProxySwitchIng.value = false;
  }

  Future<void> systemProxySwitch(bool open) async {
    systemProxySwitchIng.value = !open;
    if (!open){
      await closeProxy();
    } else {
      await openProxy();
    }
  }

  void watchExit() {
    if (Platform.isMacOS) {
      ProcessSignal.sigterm.watch().listen((_) {
        stdout.writeln('exit: sigterm');
        handleExit();
      });
    }
    ProcessSignal.sigint.watch().listen((_) {
      stdout.writeln('exit: sigint');
      handleExit();
    });
  }

  void selectNode(NodeMode node) {
    nodeId.value = node.id ?? 0;
    controllers.global.selectedNode.value = node;
    _storeSelectedNode(node);
  }

  Future<void> _storeSelectedNode(NodeMode node) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt('selectedNodeId', node.id ?? -1);
    await loadSelectedNode();
  }

  Future<void> loadSelectedNode() async {
    final prefs = await SharedPreferences.getInstance();
    final selectedNodeId = prefs.getInt('selectedNodeId');
    if (selectedNodeId != null) {
      selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
    }
  }

  Future<void> openProxy() async {
    int? port = controllers.config.mixedPort.value;
    if (port == 0) {
      port = null;
    }
    int? socksPort = controllers.config.mixedPort.value;
    if (socksPort == 0) {
      socksPort = null;
    }
    int? mixedPort = controllers.config.mixedPort.value;
    if (mixedPort == 0) {
      mixedPort = null;
    }
    port = port ?? mixedPort ?? 0;
    if (port != 0) {
      await proxyManager.setAsSystemProxy(
        ProxyTypes.http,
        "127.0.0.1",
        port,
      );
      await proxyManager.setAsSystemProxy(
        ProxyTypes.https,
        "127.0.0.1",
        port,
      );

      await proxyManager.setAsSystemProxy(
        ProxyTypes.socks,
        "127.0.0.1",
        port,
      );

    }

    socksPort = socksPort ?? mixedPort ?? 0;
    if (socksPort != 0) {
      if (!Platform.isWindows) {
        await proxyManager.setAsSystemProxy(
          ProxyTypes.socks,
          "127.0.0.1",
          socksPort,
        );
      }

    }

    systemProxy.value = true;
  }

  Future<void> closeProxy() async {
    await proxyManager.cleanSystemProxy();
    systemProxy.value = false;
  }

  Future<void> stopAllCore() async {
    await systemProxySwitch(false);
    if(Platform.isWindows){
      await controllers.service.stopClashCore();
    } else if(Platform.isMacOS) {
      if (controllers.cc_service.serviceIsRuning) {
        await controllers.cc_service.fetchStop();
      } else {
        await controllers.service.stopClashCore();
      }

    }
    if(!controllers.service.serviceMode.value){
      if(Platform.isWindows){
        await onKillProcess(path.basename(Files.assetsClashService.path));
      }
      await killProcess(path.basename(Files.assetsCCore.path));
      await killProcess(path.basename(Files.assetsClashService.path));
    }

    if(!controllers.service.serviceMode.value){
      await killProcess(path.basename(Files.assetsClashService.path));
    }
  }

  Future<void> handleExit() async {
    await stopAllCore();
    await trayManager.destroy();
    await windowManager.destroy();
  }

  void handleApiError(dynamic error) {
    if (error is AppException) {
      LogHelper().d('API error with status code: ${error.statusCode}');
      statusCode.value = error.statusCode ?? -1;
      errorMsg.value = error.toString();
    } else {
      LogHelper().d('Other error: $error');
      errorMsg.value = error.toString();
    }
  }

  @override
  void dispose() {
    controllers.tray.dispose();
    controllers.window.dispose();
    super.dispose();
  }
}
