import 'dart:async';

import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/upgradeLogic.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/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_logic.dart';
import 'package:making_school_asignment_app/page/home_page/home_view.dart';
import 'package:making_school_asignment_app/page/work_page/work_logic.dart';
import 'package:making_school_asignment_app/page/work_page/work_view.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';
import 'package:permission_handler/permission_handler.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;

  void getStoragePermission() async {
    _timerPermission?.cancel();
    _timerPermission = null;
    var status = await Permission.storage.status;
    if (status != PermissionStatus.granted) {
      print(status);
      if (status == PermissionStatus.denied) {
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("权限拒绝"),
              content: Text("权限被永久拒绝，请前往权限设置页面通过权限"),
              actions: [
                ElevatedButton(
                  onPressed: () async {
                    await AppSettings.openAppSettings(asAnotherTask: true);
                    Navigator.of(context).pop();
                    _timerPermission = Timer.periodic(const Duration(seconds: 30), (_) => getStoragePermission());
                  },
                  child: Text('前往'),
                )
              ],
            );
          },
        );

        return;
      }
      await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("内存权限"),
            content: Text("为了提供更好的服务，需要获取到存储权限用于保存批阅笔记"),
            actions: [
              ElevatedButton(
                onPressed: () async {
                  await Permission.storage.request();
                  Navigator.of(context).pop();
                  getStoragePermission();
                },
                child: Text('允许'),
              )
            ],
          );
        },
      );
    }
  }

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

    Future.delayed(const Duration(seconds: 3), () => FlutterNativeSplash.remove());
    Future.delayed(const Duration(seconds: 4), () => getStoragePermission());

    Get.put(HomeLogic());
    Get.put(WorkLogic());

    _bodyList = [const HomePage(), const WorkPage(), const MyInfo()];
    // APP 启动后就直接更新
    if (!_upgradeLogic.showUpgrade.value) _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) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
    return WillPopScope(
      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(
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                label: '作业',
                icon: getItemIcon('assets/images/ic_home_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_home_press.png'),
              ),
              BottomNavigationBarItem(
                label: '考试',
                icon: getItemIcon('assets/images/ic_work_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_work_press.png'),
              ),
              BottomNavigationBarItem(
                label: '我的',
                icon: getItemIcon('assets/images/ic_mine_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_mine_press.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);
            },
          );
        }),
      ),
      onWillPop: () async {
        if (lastPopTime == null || DateTime.now().difference(lastPopTime!) > const Duration(seconds: 1)) {
          lastPopTime = DateTime.now();
          ToastUtils.getFluttertoast(context: context, msg: '连续两次返回就退出');
          return Future.value(false);
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          return Future.value(true);
        }
      },
    );
  }
}

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();
  }
}

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