import 'package:cashier_reserve/common/manager/app_manager.dart';
import 'package:cashier_reserve/home/home_view.dart';
import 'package:cashier_reserve/home/home_view_model.dart';
import 'package:flutter/services.dart';

import 'common/base/provider.dart';
import 'common/base/ui.dart';
import 'common/utils/utils.dart';

class RootView extends StatefulWidget {
  const RootView({super.key});

  @override
  _RootView createState() => _RootView();
}

class _RootView extends State<RootView>
    with AutomaticKeepAliveClientMixin, RouteAware {
  @override
  bool get wantKeepAlive => true;
  DateTime? lastPopTime;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    AppManager.setGlobalContext(context);
    super.build(context);
    return PopScope(
        canPop: false,
        onPopInvokedWithResult: (didPop, result) async {
      // 点击返回键的操作
      if (lastPopTime == null ||
          DateTime.now().difference(lastPopTime!) > const Duration(seconds: 2)) {
        lastPopTime = DateTime.now();
        Utils.toast('再按一次退出', context);
      } else {
        lastPopTime = DateTime.now();
        // 退出app
        await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      }
    },
    child: MultiProvider(
      providers: [
        ChangeNotifierProvider<HomeViewModel>(
          create: (_) => HomeViewModel(),
        )
      ],
      child: BaseUIController(stateWidget: HomeView()),
    ));
  }
}