import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nomo/app/base/base_controller.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../../../utils/log/logger.dart';
import '../../../components/country_restricted_overlay.dart';
import '../../../constants/enums.dart';
import '../../../controllers/api_controller.dart';
import '../../../data/models/launch/launch.dart';
import '../../../data/sp/ix_sp.dart';
import '../../../routes/app_pages.dart';

class SplashController extends BaseController {
  static const String TAG = 'SplashController';
  final _apiController = Get.find<ApiController>();

  final _showLoading = false.obs;

  bool get showLoading => _showLoading.value;
  set showLoading(bool value) => _showLoading.value = value;

  // 是否已经登录
  final _hasLogin = true.obs;

  bool get hasLogin => _hasLogin.value;
  set hasLogin(bool value) => _hasLogin.value = value;

  final _versionName = ''.obs;

  String get versionName => _versionName.value;
  set versionName(String value) => _versionName.value = value;

  @override
  void onInit() {
    super.onInit();
    getVersionInfo();
    initApiInfo();
    // Get.offAllNamed(Routes.HOME);
    // Get.to(
    //   () => CountryRestrictedOverlay(type: RestrictedType.network),
    //   transition: Transition.fadeIn,
    // );

    // Get.to(
    //   () => const ProtocolOverlay(),
    //   transition: Transition.native,
    //   curve: Curves.easeInOut,
    // );
  }

  void getVersionInfo() async {
    // versionCode =
    //     await PackageInfo.fromPlatform().then((value) => value.buildNumber);
    versionName = await PackageInfo.fromPlatform().then(
      (value) => value.version,
    );
  }

  Future<void> initApiInfo() async {
    try {
      await _apiController.initFingerprint();
      final launch = IXSP.getLaunch();
      if (launch != null) {
        _apiController.fp.exData = launch.exData;
        _apiController.initLaunch(launch);
        handleLaunch(launch, isFirstRequest: false);
        _apiController.asyncHandleLaunch();
      } else {
        showLoading = true;
        try {
          final launch = await _apiController.launch();
          handleLaunch(launch);
        } catch (e, st) {
          handleLaunchError(e, st);
        } finally {
          showLoading = false;
        }
      }
    } catch (e, s) {
      handleLaunchError(e, s);
    }
  }

  void handleLaunch(Launch launch, {bool isFirstRequest = true}) {
    if (launch.userConfig != null && launch.appConfig != null) {
      final user = launch.userConfig!;
      final appConfig = launch.appConfig!;
      switch (MemberLevel.fromLevel(user.memberLevel)) {
        case MemberLevel.guest:
          //游客禁用，必须登录
          if (appConfig.visitorDisabled ?? true) {
            // 延迟1秒后设置为未登录
            Future.delayed(const Duration(seconds: 1), () {
              // hasLogin = false;
              Get.offAllNamed(Routes.HOME);
            });
          } else {
            //允许游客访问，直接进入主页
            Get.offAllNamed(Routes.HOME);
          }
          break;
        default:
          //登录用户，直接进入主页
          Get.offAllNamed(Routes.HOME);
          break;
      }
    }
  }

  Future<void> handleLaunchError(dynamic e, StackTrace s) async {
    if (IXSP.getLastIsUserDisabled()) {
      if (!_apiController.isShowDisabled) {
        Get.offAll(
          () => CountryRestrictedOverlay(
            type: RestrictedType.user,
            onPressed: () async {
              // 清除LaunchData
              await IXSP.clearLaunchData();
              // 清除禁用状态
              IXSP.setLastIsUserDisabled(false);
              // 发送事件
            },
          ),
          transition: Transition.fadeIn,
        );
      }
      return;
    } else if (IXSP.getLastIsRegionDisabled()) {
      if (!_apiController.isShowDisabled) {
        Get.offAll(
          () => const CountryRestrictedOverlay(type: RestrictedType.region),
          transition: Transition.fadeIn,
        );
      }
      return;
    } else if (IXSP.getLastIsDeviceDisabled()) {
      if (!_apiController.isShowDisabled) {
        Get.offAll(
          () => const CountryRestrictedOverlay(type: RestrictedType.device),
          transition: Transition.fadeIn,
        );
      }
      return;
    }
    handleSnackBarError(e, s);
    log(TAG, 'initApiInfo error: $e');
    final launch = IXSP.getLaunch();
    if (launch != null) {
      _apiController.initLaunch(launch);
      handleLaunch(launch);
    } else {
      Get.to(
        () => CountryRestrictedOverlay(
          type: RestrictedType.network,
          onPressed: () async {
            Navigator.pop(Get.context!);
            initApiInfo();
          },
        ),
        transition: Transition.fadeIn,
      );
    }
  }
}
