import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:dartin/dartin.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sport/application.dart';
import 'package:sport/config_inject.dart';
import 'package:sport/pages/game/index.dart';
import 'package:sport/pages/home/home_info_page.dart';
import 'package:sport/pages/my/my_page.dart';
import 'package:sport/pages/social/new_social_index_page.dart';
import 'package:sport/pages/social/social_index_page.dart';
import 'package:sport/provider/bluetooth.dart';
import 'package:sport/provider/message_model.dart';
import 'package:sport/services/app_lifecycle_state.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/utils/update_apk.dart';
import 'package:sport/widgets/decoration.dart';
import 'package:sport/widgets/dialog/share_popup.dart';
import 'package:sport/widgets/misc.dart';

import 'game/detail_bottom.dart';

class HomePage extends StatefulWidget {
  @override
  createState() => _HomePageState();
}

class _HomePageState extends LifecycleState<HomePage> with ConfigInject {
  var _pageController = PageController();
  DateTime _lastPressed;

  ValueNotifier<int> _valueNotifierIndex = ValueNotifier(0);
  final Duration _exitDuration = Duration(seconds: 2);

  final List<Widget> _pages = <Widget>[HomeInfoPage(), GamePage(), NewSocialIndexPage(), MyPage()];


  @override
  void initState() {
    super.initState();
    updateApp(context);
    Provider.of<MessageModel>(context, listen: false).init(); // 这就开始轮询了?
    Provider.of<Bluetooth>(context, listen: false).listen();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("$state");
    switch (state) {
      case AppLifecycleState.resumed:
        Provider.of<Bluetooth>(context, listen: false).listen();
        SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
        break;
      case AppLifecycleState.paused:
        Provider.of<Bluetooth>(context, listen: false).disposeBluetooth();
        break;
      default:
        break;
    }
    Provider.of<MessageModel>(context, listen: false).state = state;
  }

  @override
  void dispose() {
    _valueNotifierIndex?.dispose();
    _pageController?.dispose();
    super.dispose();
    AmapLocation.instance?.dispose();
  }

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

  @override
  void didUpdateWidget(HomePage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        backgroundColor: Colors.white,
        bottomNavigationBar: SafeArea(
          child: SizedBox(
            height: 49,
            child: Container(
              child: ValueListenableBuilder(
                valueListenable: _valueNotifierIndex,
                builder: (BuildContext context, int value, Widget child) => CupertinoTabBar(
                  backgroundColor: const Color(0xff1D1D1D),
                  border: null,
                  iconSize: 22.0,
                  activeColor: const Color(0xffFFC400),
                  inactiveColor: const Color(0xff666666),
                  items: <BottomNavigationBarItem>[
                    BottomNavigationBarItem(
                      icon: Padding(
                        padding: const EdgeInsets.only(top: 6.0),
                        child: Image.asset("lib/assets/img/tab_home_${value == 0 ? "press" : "normal"}.png"),
                      ),
                      title: Text(
                        "首页",
                        style: TextStyle(fontSize: 11.0),
                      ),
                    ),
                    BottomNavigationBarItem(
                      icon: Padding(
                        padding: const EdgeInsets.only(top: 6.0),
                        child: Image.asset("lib/assets/img/tab_game_${value == 1 ? "press" : "normal"}.png"),
                      ),
                      title: Text("运动", style: TextStyle(fontSize: 11.0)),
                    ),
                    BottomNavigationBarItem(
                      icon: Padding(
                        padding: const EdgeInsets.only(top: 6.0),
                        child: Image.asset("lib/assets/img/tab_bbs_${value == 2 ? "press" : "normal"}.png"),
                      ),
                      title: Text("社区", style: TextStyle(fontSize: 11.0)),
                    ),
                    BottomNavigationBarItem(
                      icon: Padding(
                        padding: const EdgeInsets.only(top: 6.0),
                        child: Image.asset("lib/assets/img/tab_my_${value == 3 ? "press" : "normal"}.png"),
                      ),
                      title: Text("我的", style: TextStyle(fontSize: 11.0)),
                    ),
                  ],
                  currentIndex: value,
                  onTap: (index) {
                    _pageController.jumpToPage(index);
                    _valueNotifierIndex.value = index;
                    // 这里得轮询解决
//
                  },
                ),
              ),
            ),
          ),
        ),
        body: WillPopScope(
          onWillPop: () async {
            if (_lastPressed == null || DateTime.now().difference(_lastPressed) > _exitDuration) {
              //两次点击间隔超过2秒则重新计时
              _lastPressed = DateTime.now();
              ToastUtil.show("再次点击返回键退出");
              return false;
            }
            return true;
          },
          child: PageView.builder(
            itemBuilder: (ctx, index) => _pages[index],
            itemCount: _pages.length,
            controller: _pageController,
            physics: NeverScrollableScrollPhysics(),
            onPageChanged: (index) {
              Application.currentPage = index;
            },
          ),
        ),
      ),
    );
  }
}
