import 'dart:async';

import 'package:flutter_translate/ads/interstitial_ad_manage.dart';
import 'package:flutter_translate/common/hive/remote_config_box.dart';
import 'package:flutter_translate/global/app_config.dart';
import 'package:flutter_translate/global/network_connectivity_service.dart';
import 'package:flutter_translate/router/get_gages.dart';
import 'package:get/get.dart';

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

  @override
  void onReady() async {
    super.onReady();
    await _checkGuaranteedDate();
    Get.put(NetworkConnectivityService());
  }

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

  /// 检查是否到保底日期
  Future<void> _checkGuaranteedDate() async {
    if (!RemoteConfigBox().getAdSwitch()) {
      if (getGuaranteedDate().isBefore(DateTime.now())) {
        await RemoteConfigBox().putAdSwitch(true);
      }
    }
  }

  /// 开始定时器
  void startTimer() {
    timer = Timer.periodic(const Duration(milliseconds: 10), (Timer t) async {
      if (currentProcess.value + changeValue >= timeTotal) {
        currentProcess.value = timeTotal;
        _stopTimer();
        _openHome();
        return;
      }
      currentProcess.value += changeValue;
    });
  }

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

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

  void _openHome() {
    InterstitialAdManager().showAdIfReady(
      InterstitialAdManager().adIds[0],
      onTap: () {
        Get.offNamed(GetPages.home);
      },
    );
  }
}
