import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/routes/nav_ids.dart';
import 'package:vitalapp/routes/routes.dart';
import 'package:vitalapp/store/store.dart';

class RedirectPage extends StatefulWidget {
  static bool _isBusy = false;
  static int count = 0;

  static bool get isBusy => _isBusy;
  static set isBusy(bool val) {
    print("isBusy -> $val");
    _isBusy = val;
  }

  const RedirectPage({super.key});

  @override
  State<StatefulWidget> createState() => _RedirectPageState();
}

class _RedirectPageState extends State<RedirectPage> {
  late final String targetName;
  late final String? targetPatientInfo;
  bool isLoading = true;

  @override
  void initState() {
    RedirectPage.isBusy = true;
    RedirectPage.count++;
    targetName = Routes.parameters["name"]!;
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      wait();
    });
  }

  @override
  void dispose() {
    RedirectPage.count--;
    if (RedirectPage.count == 0) {
      RedirectPage.isBusy = false;
    }
    super.dispose();
  }

  void wait() {
    Future.delayed(const Duration(milliseconds: 300), () {
      setState(() {
        isLoading = false;
      });
      redirectTo();
    });
  }

  void redirectTo() {
    Future.delayed(const Duration(milliseconds: 100), () {
      Get.offAllNamed(targetName, id: NavIds.HOME);
      // Routes.parameters = {};
      RedirectPage.isBusy = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      Store.app.setBusy("加载中...");
    } else {
      Store.app.busy = false;
    }

    return const SizedBox();
  }
}
