import 'dart:async';
import 'package:chat/routes/app_routes.dart';
import 'package:chat/routes/auth_routes.dart';
import 'package:chat/services/auth_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';

class TransitPage extends StatefulWidget {
  const TransitPage({Key? key}) : super(key: key);

  @override
  State<TransitPage> createState() => _TransitPageState();
}

/// 这里的加载图片，应该是可以请求网络图片的，但是要考虑网络图片的加载周期，还有网络环境因素等
class _TransitPageState extends State<TransitPage> {
  int _leftTime = 5;
  late Timer _timer;

  @override
  void initState() {
    super.initState();

    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if (mounted) {
        setState(() {
          _leftTime--;
        });
      }
      if (_leftTime <= 0) {
        timer.cancel();
        _jumpToRootPage();
      }
    });
  }

  void _jumpToRootPage() {
    if (AuthService.to.isUserLogin) {
      Get.offAllNamed(AppRoutes.app);
    } else {
      Get.offAllNamed(AuthRoutes.index);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Swiper(
            autoplay: true,
            itemCount: 2,
            pagination: const SwiperPagination(),
            itemBuilder: (BuildContext context, int index) {
              return Image.asset(
                'assets/transits/${index + 1}.png',
                fit: BoxFit.cover,
              );
            },
          ),
        ),
        Positioned(
          bottom: 32,
          right: 32,
          child: GestureDetector(
            onTap: () {
              _timer.cancel();
              _jumpToRootPage();
            },
            child: Text(
              '跳过($_leftTime)',
              style: const TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
