import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/user_info.dart';
import 'package:making_school_asignment_app/common/job/user_info_detail.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/store/user_store.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/upgradeLogic.dart';
import 'package:making_school_asignment_app/common/utils/storage.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/home_page/children/my_info.dart';
import 'package:making_school_asignment_app/page/home_page/home_view.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';

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

  @override
  State<StartPage> createState() => _StartPageState();
}

class _StartPageState extends State<StartPage> with RequestToolMixin {
  Timer? _timer;
  Timer? _timerPermission;
  DateTime? lastPopTime;
  final _pageController = Get.find<PageIndexController>();
  final _upgradeLogic = Get.find<UpgradeLogic>();

  late final List<Widget> _bodyList;

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

    // const WorkPage(),
    _bodyList = [const HomePage(), const MyInfo()];
    // APP 启动后就直接更新
    WidgetsBinding.instance.addPostFrameCallback((e) {
      /// 首页用户未更新不进行更新判断，没有登陆的用户在登陆页面和40秒回调中检查弹出更新APP
      if (!_upgradeLogic.showUpgrade.value && UserStore.to.userDetailInfo.value != null)
        _upgradeLogic.getAppUpgrade(context);
    });
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 40), (e) {
      if (Get.currentRoute == Routes.login) return; // 在登录页面不更新APP
      if (!_upgradeLogic.showUpgrade.value) _upgradeLogic.getAppUpgrade(context);
    });

    String? token = UserStore.to.token;
    UserInfo? userInfo = UserStore.to.userInfo.value;
    UserInfoDetail? userInfoDetail = UserStore.to.userDetailInfo.value;

    if ((token?.isNotEmpty ?? false) && userInfo != null) {
      // Future.delayed(const Duration(milliseconds: 200)).then((e) {
      //   Get.toNamed(Routes.home);
      // });
      // 更新用户信息
      if (userInfoDetail == null) UserStore.to.updateUserInfo();
    } else {
      Future.delayed(const Duration(milliseconds: 100)).then((e) {
        UserStore.to.erase();
        StorageService.to.erase();
        Get.offAllNamed(Routes.login);
      });
    }
  }

  @override
  void dispose() {
    Get.delete<PageIndexController>();
    _timer?.cancel();
    _timerPermission?.cancel();
    super.dispose();
  }

  /// 获取项目 icon
  Widget getItemIcon(String icon) {
    return Image.asset(
      icon,
      fit: BoxFit.contain,
      width: 24.w,
      height: 24.h,
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      child: Scaffold(
        body: PageView(
          controller: _pageController._pageIndexState.pageController,
          physics: const BouncingScrollPhysics(),
          onPageChanged: (index) {
            _pageController._pageIndexState.pageIndex.value = index;
            // if (index == 2) {
            //   SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light));
            // } else {
            //   SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
            // }
          },
          children: _bodyList,
        ),
        bottomNavigationBar: Obx(() {
          return BottomNavigationBar(
            backgroundColor: Colors.white,
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                label: '作业',
                icon: getItemIcon('assets/images/ic_home_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_home_active.png'),
              ),
              // BottomNavigationBarItem(
              //   label: '考试',
              //   icon: getItemIcon('assets/images/ic_work_normal.png'),
              //   activeIcon: getItemIcon('assets/images/ic_work_active.png'),
              // ),
              BottomNavigationBarItem(
                label: '我的',
                icon: getItemIcon('assets/images/ic_mine_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_mine_active.png'),
              ),
            ],
            //设置显示的模式
            type: BottomNavigationBarType.fixed,
            fixedColor: Theme.of(context).primaryColor,
            unselectedItemColor: Colors.grey,
            // unselectedItemColor: const Color.fromRGBO(80, 87, 103, 1),
            // backgroundColor: Colors.white,
            //设置当前的索引
            currentIndex: _pageController._pageIndexState.pageIndex.value,
            //tabBottom的点击监听
            onTap: (index) {
              _pageController._pageIndexState.pageController.jumpToPage(index);
            },
          );
        }),
      ),
      onPopInvokedWithResult: (bool didPop, dynamic result) async {
        if (lastPopTime == null || DateTime.now().difference(lastPopTime!) > const Duration(seconds: 1)) {
          lastPopTime = DateTime.now();
          ToastUtils.getFluttertoast(
            context: context,
            msg: '连续两次返回就退出',
            gravity: ToastGravity.CENTER,
            fontSize: 18,
          );
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          SystemNavigator.pop();
        }
      },
    );
  }
}

class PageIndexState {
  PageIndexState({required this.pageController, this.showUpgrade = false});

  RxInt pageIndex = 0.obs;
  bool showUpgrade;

  //文本输入框控制器
  final PageController pageController;
}

class PageIndexController extends GetxController with RequestToolMixin {
  late PageIndexState _pageIndexState;

  @override
  void onInit() {
    _pageIndexState = PageIndexState(pageController: PageController());
    super.onInit();
  }

  /// TODO 升级插件 暂时不使用
  // @override
  // void onReady() {
  //   AppUpgradeSimple.instance.checkUpdate(
  //     context: Get.context!,
  //     url: 'https://dpc-teacher-api.23544.com/api/infra/AppVersion/Get',
  //     params: {
  //       'appName': 'making_school_asignment_app',
  //       'ftuType': 1,
  //     },
  //     showNoUpdateToast: true,
  //     autoDownload: false,
  //     autoInstall: true,
  //   );
  //   super.onReady();
  // }
}

class StartPageIndexBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => PageIndexController());
  }
}
