/*
 * @Author: wangyang 1147192855@qq.com
 * @Date: 2022-07-06 13:44:45
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-09-28 18:22:42
 * @FilePath: \marking_app\lib\pages\TheMainPage.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/user/user_info.dart';
import 'package:marking_app/pages/reports/index.dart';
import 'package:marking_app/provider/do_marking_provider.dart';
import 'package:marking_app/provider/upload_file_provider.dart';
import 'package:marking_app/utils/app_upgrade/UpdateDialog.dart';
import 'package:marking_app/utils/app_upgrade/model/UpdateAppEvent.dart';
import 'package:marking_app/common/model/sys/system_version.dart';
import 'package:marking_app/pages/home/index.dart';
import 'package:marking_app/pages/marking/index.dart';
import 'package:marking_app/provider/user_provider.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/request/rest_client.dart';
import 'package:package_info/package_info.dart';

import 'homework_correction/job_home.dart';

class TheMainPage extends StatefulHookConsumerWidget {
  const TheMainPage({Key? key}) : super(key: key);

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

class TheMainPageState extends ConsumerState<TheMainPage> with CommonMixin {
  DateTime? lastPopTime;
  late final FocusNode _otherFocusNode;
  late final PageController _pageController;
  late RemoveListener _userListener;
  Timer? _timer;
  bool showUpgrade = false;

  final List<Widget> _bodyList = [
    const TheHomePage(),
    const TheMarking(),
    // const HomeworkCorrection(),
    const JobHome(),
    const TheReport()
  ];
  int tabIndex = 0;

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

  @override
  void initState() {
    _pageController = PageController(initialPage: tabIndex);
    _otherFocusNode = FocusNode();
    // 由于本项目必须登录才能浏览，所以APP升级校验在登录后
    _userListener = ref.read(userProvider.notifier).addListener((state) {
      if (state.id != '0' && state.id != '') {
        if (!showUpgrade) {
          getAppUpgrade(state);
        }
        _timer = Timer.periodic(Duration(seconds: 40), (e) {
          if (!showUpgrade) getAppUpgrade(state);
        });
      }
    });
    ref.read(uploadFileProvider.notifier).initConfig();
    ref.read(userProvider.notifier).initUserInfo(); // 获取本地用户信息
    ref.read(userTokenProvider.notifier).initToken().then((value) {
      if (!value) {
        return toLoginPage(context);
      }
      ref.read(userReportProvider.notifier).initUserReport(); // 初始化报告页面用户身份职位
    }); // 定值token
    // 初始化偏好设置
    ref.read(markingKeyboardProvider.notifier).initMarkingKeyboard();
    super.initState();
  }

  @override
  void dispose() {
    _userListener();
    _pageController.dispose();
    _otherFocusNode.dispose();
    _timer?.cancel();
    super.dispose();
  }

  void getAppUpgrade(UserInfo user) async {
    try {
      showUpgrade = true;
      if (user.loginName == '18888888888') return;
      // 获取设备信息
      String deviceInfo;
      int deviceType;
      if (Platform.isAndroid) {
        deviceInfo = "android";
        deviceType = 1;
      } else if (Platform.isIOS) {
        deviceInfo = "ios";
        deviceType = 2;
      } else {
        return;
      }

      RestClient client = await getClient();
      BaseStructureResult<SystemVersion> result = await client.getLatestVersion(deviceType);
      if (result.code == 200 && result.data != null) {
        //获取当前版本
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        //获取当前版本
        String localVersion = packageInfo.version;
        String appName = packageInfo.appName; //应用名称
        String packageName = packageInfo.packageName; //包名称
        // String buildNumber = packageInfo.buildNumber; //小版本号

        SystemVersion data = result.data!;
        Map json = {'downloadPath': data.apkUrl, 'version': data.version, 'systemType': deviceType, 'description': data.description};
        UpdateAppEvent updateAppEvent = UpdateAppEvent.fromJson(json, localVersion, deviceInfo, appName, packageName, typeName: 'systemType');
        if (updateAppEvent.upgrade) {
          await UpdateDialog.showUpdateDialog(context, updateAppEvent);
        }
      }
    } catch (e) {
    } finally {
      showUpgrade = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 触摸收起键盘
        FocusScope.of(context).requestFocus(_otherFocusNode);
      },
      child: WillPopScope(
        child: Scaffold(
          body: PageView(
            controller: _pageController,
            physics: const BouncingScrollPhysics(),
            onPageChanged: (index) => toUpState(setState, () => tabIndex = index, mounted),
            children: _bodyList,
          ),
          bottomNavigationBar: 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_marking_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_marking_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_report_normal.png'),
                activeIcon: getItemIcon('assets/images/ic_report_press.png'),
              ),
              // BottomNavigationBarItem(
              //   label: '我的',
              //   icon: getItemIcon('assets/images/ic_mine_normal.png'),
              //   activeIcon: getItemIcon('assets/images/ic_mine_press.png'),
              // ),
            ],
            //设置显示的模式
            type: BottomNavigationBarType.fixed,
            //设置当前的索引
            currentIndex: tabIndex,
            //tabBottom的点击监听
            onTap: (index) => _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);
          }
        },
      ),
    );
  }
}
