import 'package:get/get.dart';

import 'dart:io' show Platform;
import 'package:kaer_with_panels/app/utils/kr_network_check.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/routes/app_pages.dart';
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/services/singbox_imp/kr_sing_box_imp.dart';

import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'dart:async';

class KRSplashController extends GetxController {
  // 加载状态
  final RxBool kr_isLoading = true.obs;
  
  // 错误状态
  final RxBool kr_hasError = false.obs;
  
  // 错误信息
  final RxString kr_errorMessage = ''.obs;

  // 倒计时
  // final count = 0.obs;
  // 是否正在加载
  final isLoading = true.obs;
  // // 是否初始化成功
  // final isInitialized = false.obs;

  @override
  void onInit() {
    super.onInit();
    _kr_initialize();
  }

  Future<void> _kr_initialize() async {
    try {
      // 只在手机端检查网络权限
      if (Platform.isIOS || Platform.isAndroid) {
        final bool hasNetworkPermission = await KRNetworkCheck.kr_initialize(
          Get.context!,
          onPermissionGranted: () async {
            await _kr_continueInitialization();
          },
        );

        if (!hasNetworkPermission) {
          kr_hasError.value = true;
          kr_errorMessage.value = AppTranslations.kr_splash.kr_networkPermissionFailed;
          return;
        }
      } else {
        // 非手机端直接继续初始化
        await _kr_continueInitialization();
      }
    } catch (e) {
      kr_hasError.value = true;
      kr_errorMessage.value = '${AppTranslations.kr_splash.kr_initializationFailed}$e';
    }
  }

  Future<void> _kr_continueInitialization() async {
    try {
      // 只在手机端检查网络连接
      if (Platform.isIOS || Platform.isAndroid) {
        final bool isConnected = await KRNetworkCheck.kr_checkNetworkConnection();
        if (!isConnected) {
          kr_hasError.value = true;
          kr_errorMessage.value = AppTranslations.kr_splash.kr_networkConnectionFailed;
          return;
        }
      }

      // 初始化配置
      await AppConfig().initConfig(
        onSuccess: () async {
          // 配置初始化成功，继续后续步骤
          await _kr_continueAfterConfig();
        },
      );
    } catch (e) {
      // 配置初始化失败，显示错误信息
      kr_hasError.value = true;
      kr_errorMessage.value = '${AppTranslations.kr_splash.kr_initializationFailed}$e';
    }
  }

  // 配置初始化成功后的后续步骤
  Future<void> _kr_continueAfterConfig() async {
    try {
      // 初始化SingBox
      await KRSingBoxImp.instance.init();
      
      // 初始化用户信息
      await KRAppRunData.getInstance().kr_initializeUserInfo();

      // 等待一小段时间确保所有初始化完成
      await Future.delayed(const Duration(milliseconds: 200));
      
      // 验证登录状态是否已正确设置
      final loginStatus = KRAppRunData.getInstance().kr_isLogin.value;
      KRLogUtil.kr_i('启动完成，最终登录状态: $loginStatus', tag: 'SplashController');
      
      // 直接导航到主页
      Get.offAllNamed(Routes.KR_MAIN);
    } catch (e) {
      // 后续步骤失败，显示错误信息
      KRLogUtil.kr_e('启动初始化失败: $e', tag: 'SplashController');
      kr_hasError.value = true;
      kr_errorMessage.value = '${AppTranslations.kr_splash.kr_initializationFailed}$e';
    }
  }

  // 重试按钮点击事件
  void kr_retry() {
    kr_hasError.value = false;
    kr_errorMessage.value = '';
    _kr_initialize();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
} 