
import 'dart:async';
import 'dart:io';
import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:get/get.dart';
import 'package:naiyouwl/app/common/constants.dart';
import 'package:naiyouwl/app/const/const.dart';
import 'package:naiyouwl/app/controller/GlobalController.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:naiyouwl/app/utils/shell.dart';
import 'package:naiyouwl/app/utils/utils.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../clash/service/clash_service.dart';
import '../../../common/LogHelper.dart';
import '../../../common/SharedPreferencesUtil.dart';
import '../../../component/connection_status.dart';
import '../../../data/model/LocalUser.dart';
import '../../../data/model/NodeMode.dart';
import '../../../data/model/SysConfig.dart';
import '../../../data/model/UserMode.dart';
import '../../../network/api_service.dart';
import '../../../routes/app_pages.dart';
import 'package:path/path.dart' as path;


import '../../../service/connection_service.dart';
import '../../../service/local_storage_service.dart';
import '../../../service/network_service.dart';
import '../../../service/user_service.dart';

enum ImageType {
  CUSTOMER,
  PROMOTION,
  TUTORIAL,
  RENEWAL,
}

class HomeController extends GetxController {
  //TODO: Implement HomeController

  var isLoading = false.obs;
  var sysConfig = SysConfig().obs;
  var localUsers = LocalUser().obs;
  var userMode = User().obs;
  var UsersysConfig = SysConfig().obs;
  var serviceStuatus = false.obs;
  var coreStuatus = false.obs;
  var connectStatus = Rx<ConnectionStatus>(ConnectionStatus.disconnected);
  var nodeModes = <NodeMode>[];
  var isConnect = false.obs;
  var errAdminMsg = false.obs;
  var errAdmin = ''.obs;
  var isInit = false.obs;


  bool get isRunning =>
      connectStatus.value == ConnectionStatus.connected &&
          controllers.global.allowStatusUpdate;


  late final GlobalController globalController = controllers.global;

  StreamSubscription<RunningState>? _statusSubscription;
  final Map<ImageType, String> imageMap = {
    ImageType.CUSTOMER: "assets/images/main/customer.png",
    ImageType.PROMOTION: "assets/images/main/promotion.png",
    ImageType.TUTORIAL: "assets/images/main/tutorial.png",
    ImageType.RENEWAL: "assets/images/main/renewal.png",
  };

  final NetworkService networkService = NetworkService(controllers.global);
  final LocalStorageService localStorageService = LocalStorageService();
  final UserService userService = UserService(controllers.global);


  late final ConnectionService connectionService;

  void onImageTap(ImageType type) async {
    if (type == ImageType.CUSTOMER) {
      await launchUrl(Uri.parse(UsersysConfig.value.userTicket ?? ""));
    } else if (type == ImageType.PROMOTION) {
      await launchUrl(Uri.parse(UsersysConfig.value.affUrl ?? ""));
    } else if (type == ImageType.TUTORIAL) {
      await launchUrl(Uri.parse(UsersysConfig.value.userDownload ?? ""));
    } else if (type == ImageType.RENEWAL) {
      await launchUrl(Uri.parse(UsersysConfig.value.userBuy ?? ""));
    }
    LogHelper().d("${imageMap[type]} tapped as ${type
        .toString()
        .split('.')
        .last}");
  }

  void updateStatus(ConnectionStatus newStatus) {
    connectStatus.value = newStatus;

  }

  void _handleStateChange([dynamic _]) async {
    final coreStatus = controllers.service.coreStatus.value;
    final isVisible = controllers.window.isVisible.value;
    if (coreStatus == RunningState.running && isVisible &&
        controllers.global.allowStatusUpdate) {
      // 核心运行中且窗口可见时的逻辑

    }
  }

  Future<void> handleButtonClick() async {
    // if (userMode.value.enable != 1) {
    //   controllers.global.handleApiError("账号禁用,请刷新账号状态或重启软件");
    //   return;
    // }

    if(controllers.cc_service.serviceStatus == RunningState.starting){
      controllers.global.handleApiError("服务安装中,请等待");
      return;
    }

    if(controllers.cc_service.serviceStatus.value == RunningState.uninstall){
      controllers.global.handleApiError("服务卸载中,请等待");
      return;
    }

    if (connectStatus.value == ConnectionStatus.connecting) {

      return;
    }

    if (connectStatus.value == ConnectionStatus.connected) {
      await connectionService.stopConnection();
    } else {


    if(Platform.isMacOS){
      if(controllers.global.routeModesSelect.value  == "tun"){
        //网卡模式
        if(!controllers.cc_service.serviceIsRuning){
          controllers.global.errorMsg.value = "通过右上角安装服务来获取管理员权限";
          return;
        }
      }
    }


      updateStatus(ConnectionStatus.connecting);

      // if(Platform.isMacOS){
      //   // 检查服务是否运行
      //   if (!controllers.cc_service.serviceIsRuning) {
      //     // 尝试获取 hello 的返回结果并处理
      //     if(controllers.service.coreStatus.value != RunningState.running)
      //     {
      //       var hellow = await controllers.core.fetchHello();
      //
      //       // 如果获取不到 hellow，则重试启动内核
      //       if (hellow == null) {
      //         controllers.global.updateMsg("尝试重新启动内核");
      //         bool success = await restartClashCoreWithRetry(maxRetries: 3);  // 重试 3 次
      //         if (!success) {
      //           controllers.global.updateMsg("内核重启失败，已达到最大重试次数");
      //           updateStatus(ConnectionStatus.stopped);
      //           return;  // 如果重启失败，直接返回，阻止继续进行
      //         }
      //       }
      //     }
      //   }
      // }


     // await Future.delayed(Duration(seconds: 3)); // 等待核心状态更新
      if(globalController.selectedNode.value != null)
      {
        await connectionService.startConnection();
      } else {
        // 继续后面的逻辑
        var error = await networkService.fetchAuthUser();

        // 根据 error 的结果继续处理
        if (error == "") {
          await connectionService.startConnection();
        } else {
          connectionService.updateStatus(ConnectionStatus.disconnected);
          globalController.updateMsg("验证失败,{$error}");
        }
      }


    }
  }

  // 重试机制，确保内核重启
  Future<bool> restartClashCoreWithRetry({int maxRetries = 3}) async {
    int attempts = 0;
    bool success = false;

    while (attempts < maxRetries && !success) {
      attempts++;
      controllers.global.updateMsg("正在尝试第 $attempts 次重启内核...");

      await controllers.service.stopClashCore();
      success = await controllers.service.initClashCoreConfig();

      if (success) {
        controllers.global.updateMsg("第 $attempts 次重启内核成功！");
      } else {
        controllers.global.updateMsg("第 $attempts 次重启内核失败...");
        await Future.delayed(Duration(seconds: 2));  // 等待2秒再重试
      }
    }

    return success;
  }

  void init(){
    Future.delayed(Duration.zero, () async {
      isLoading.value = true;
      var userinfo = await networkService.fetchUserinfo();
      if(userinfo != null )
      {
         userMode.value = userinfo;
      }

      var sysconfig = await networkService.fetchUserSysConfig();
      if(sysconfig != null){
        UsersysConfig.value = sysconfig;
      }


      var localUser =  await userService.fetchLocalUser();
      if(localUser != null){
        localUsers.value = localUser;
      }
      await controllers.global.fetchNodes();
      nodeModes =  controllers.global.nodeModes;
      isLoading.value = false;
      await Future.delayed(Duration(seconds: 2)); // 等待核心状态更新
      await connectionService.coreInit();
    });
  }
  @override
  void onInit() {
    super.onInit();
    connectionService = ConnectionService(controllers.global, updateStatus);
    _statusSubscription =
        controllers.service.coreStatus.stream.listen(_handleStateChange);
    init();
  }

  bool   GetEnable()  => userMode.value.enable == 1;
  String GetUserName() => localUsers.value.email.toString();
  String GetExpiredAt() => "到期时间:${userMode.value.expiredAt}";
  String GetTraffic() => "用户流量:${userMode.value.unusedTraffic}";
  String GetNode() => controllers.global.selectedNode.value?.name ?? "未选择节点";
  String getHttp() => "http 127.0.0.1:${controllers.config.mixedPort.value}";
  String getSocket() => "sock 127.0.0.1:${controllers.config.mixedPort.value}";
  String getSerivce() => "${controllers.config.servicePort.value}";

  void RouteNode() =>  Get.toNamed(Routes.NODE);
}