import 'dart:async';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/shared/tools/sc_version_utils.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/app/routes/sc_routes.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/data_sources/sources/local/file_cache_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_config_repository_imp.dart';
import 'package:yumi/shared/business_logic/models/res/sc_start_page_res.dart';
import 'package:yumi/modules/auth/login_route.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  Timer? _timer;
  int countdown = 6;
  int status = 0;
  SCStartPageRes? currentStartPage;

  List<SCStartPageRes> startPages = [];

  @override
  void initState() {
    super.initState();
    FileCacheManager.getInstance().getFilePath();
    getStartPage();
    _startTimer(context);
  }

  ///加载启动页配置
  void getStartPage() {
    SCConfigRepositoryImp().getStartPage().then((result) {
      startPages = result;
      if (startPages.length > 1) {
        int index = Random().nextInt(startPages.length);
        currentStartPage = result[index];
      } else if (startPages.isNotEmpty) {
        currentStartPage = result.first;
      } else {
        currentStartPage = null;
      }

      status = 1;
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  /// 启动倒计时
  void _startTimer(BuildContext context) {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (countdown == 0) {
        _cancelTimer();
        _goMainPage(context);
        return;
      }
      countdown--;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Stack(
        alignment: Alignment.center,
        children: [
          Image.asset(
            SCGlobalConfig.businessLogicStrategy.getSplashPageBackgroundImage(),
            width: ScreenUtil().screenWidth,
            height: ScreenUtil().screenHeight,
            fit: BoxFit.cover,
          ),
          Image.asset(
            SCGlobalConfig.businessLogicStrategy.getSplashPageIcon(),
            width: 107.w,
            height: 159.w,
          ),
        ],
      ),
    );
  }

  void _goMainPage(BuildContext context) async {
    try {
      await SCVersionUtils.checkReview();
      var user = AccountStorage().getCurrentUser();
      var token = AccountStorage().getToken();
      if (user != null && token.isNotEmpty) {
        SCNavigatorUtils.push(context, SCRoutes.home, replace: true);
      } else {
        SCNavigatorUtils.push(context, LoginRouter.login, replace: true);
      }
    } catch (e) {
      SCNavigatorUtils.push(context, LoginRouter.login, replace: true);
    }
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }
}


