import 'dart:async';

import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:tone_snap/ads/app_open_ad_manager.dart';
import 'package:tone_snap/data/api/tikustok_api.dart';
import 'package:tone_snap/data/enum/app_side_enum.dart';
import 'package:tone_snap/data/models/base_model.dart';
import 'package:tone_snap/data/models/isocode_model.dart';
import 'package:tone_snap/data/storage/music_box.dart';
import 'package:tone_snap/global/app_config.dart';
import 'package:tone_snap/global/app_lifecycle_reactor.dart';
import 'package:tone_snap/global/network_connectivity_service.dart';
import 'package:tone_snap/modules/sideb/controllers/main_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/log_util.dart';

class LaunchController extends GetxController with GetSingleTickerProviderStateMixin {
  static LaunchController get to => Get.find<LaunchController>();
  Timer? _timer;
  /// 进度总时长
  var timeTotal = 10 * 1000;
  /// 当前进度
  var currentProcess = 0.obs;
  /// 进度每次变化值
  var changeValue = 10;

  late AppLifecycleReactor _appLifecycleReactor;

  @override
  void onInit() {
    super.onInit();
    _appLifecycleReactor = AppLifecycleReactor();
    _appLifecycleReactor.listenToAppStateChanges();

    // 监听网络变化
    Get.putAsync(() async => NetworkConnectivityService());

    _startTimer();
  }

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

  /// 开始定时器
  void _startTimer() {
    _timer = Timer.periodic(Duration(milliseconds: changeValue), (Timer t) {
      if (currentProcess.value + changeValue >= timeTotal) {
        currentProcess.value = timeTotal;
        if (currentProcess >= timeTotal) {
          _stopTimer();
          _checkEnter();
          return;
        }
      }
      currentProcess.value += changeValue;
    });
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }

  /// 修改进度变化值
  void editChangeValue() {
    changeValue = 3000;
  }

  /// 校验开关和版本，决定进A还是B
  Future<void> _checkEnter() async {
    bool isOpenedSideB = MusicBox().getIsOpenedSideB();
    if (isOpenedSideB) {
      LogUtil.d('进入过B面');
      _openSideB();
    } else {
      bool enter = MusicBox().getEnter();
      String versionCode = await MusicBox().getVersionCode();
      final packageInfo = await PackageInfo.fromPlatform();
      if (versionCode != packageInfo.version) {
        LogUtil.d('版本不相同，进入B面');
        _openSideB();
      } else {
        if (enter) {
          LogUtil.d('开关：打开');
          _openSideB();
        } else {
          LogUtil.d('开关：关闭');
          _openSideA();
        }
      }
    }
  }

  void _openSideA() {
    AppOpenAdManager().showAdIfAvailable(onTap: () {
      AppConfig.appSideEnum = AppSideEnum.sideA;
      Get.offNamed(AppRoutes.initialA);
    });
  }

  void _openSideB() {
    AppOpenAdManager().showAdIfAvailable(onTap: () {
      AppConfig.appSideEnum = AppSideEnum.sideB;
      MainController.to.changeTheme();
      Get.offNamed(AppRoutes.initialB);
      MusicBox().putIsOpenedSideB(true);
    });
  }

  /// 获取所在区域
  Future<void> getIsoCode() async {
    BaseModel<IsoCodeModel>? model = await TikUsTokApi.getIsoCode();
    if (model != null && model.success && model.data?.isoCode != null) {
      AppConfig.isoCode = model.data!.isoCode!;
    }
  }
}
