import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:making_school_asignment_app/common/config/app_config.dart';
import 'package:making_school_asignment_app/common/job/common/app_version_model.dart';
import 'package:making_school_asignment_app/common/job/common/base_app_version.dart';
import 'package:making_school_asignment_app/common/job/common/base_page_data.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/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';

class StartPage extends StatefulWidget {
  const StartPage({Key? key}) : super(key: key);

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

class _StartPageState extends State<StartPage> {
  DateTime? lastPopTime;
  final _pageController = Get.find<PageIndexController>();
  late final List<Widget> _bodyList;

  @override
  void initState() {
    super.initState();
    Get.put(HomeLogic());
    Get.put(WorkLogic());

    _bodyList = [
      const HomePage(),
      const WorkPage(),
      const MyInfo(),
    ];

    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) => Get.offAllNamed(Routes.login));
    }
  }

  @override
  void dispose() {
    Get.delete<PageIndexController>();
    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 WillPopScope(
      child: Scaffold(
        body: PageView(
          controller: _pageController._pageIndexState.pageController,
          physics: const BouncingScrollPhysics(),
          onPageChanged: (index) {
            _pageController._pageIndexState.pageIndex.value = index;
          },
          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,
            //设置当前的索引
            currentIndex: _pageController._pageIndexState.pageIndex.value,
            //tabBottom的点击监听
            onTap: (index) {
              print('appbar下标：${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;

  void getAppUpgrade(UserInfoDetail user) async {
    try {
      _pageIndexState.showUpgrade = true;
      if (user.name == AppConfig.SKIP_UPDATING_USER) return;
      // 获取设备信息
      String deviceInfo = "android";
      int deviceType;
      if (Platform.isAndroid) {
        deviceType = 1;
      } else if (Platform.isIOS) {
        deviceInfo = "ios";
        deviceType = 2;
      } else {
        return;
      }
      var params = BaseAppVersion(AppConfig.APP_NAME, deviceType, 1, 1);
      BasePageData<AppVersionModel>? result = await getClient().getAppVersions(params);
      if (result != null && result.total == 1) {
        //获取当前版本
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        //获取当前版本
        String localVersion = packageInfo.version;
        String appName = packageInfo.appName; //应用名称
        String packageName = packageInfo.packageName; //包名称
        // String buildNumber = packageInfo.buildNumber; //小版本号
        AppVersionModel data = result.items[0];
        // 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 {
      _pageIndexState.showUpgrade = false;
    }
  }

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

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