
import 'dart:async';
import 'dart:ui';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/bbs/page/bbs_page.dart';
import 'package:liftmanager/internal/bbs/page/hospital_page.dart';
import 'package:liftmanager/internal/friends/page/friends_list.dart';
import 'package:liftmanager/internal/home/provider/home_provider.dart';
import 'package:liftmanager/internal/wode/model/version_item.dart';
import 'package:liftmanager/internal/wode/page/wode_page.dart';
import 'package:liftmanager/internal/work/page/work_page.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/update_dialog.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:uni_links/uni_links.dart';

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

class _HomeState extends State<HomePage> {

  var _pageList = [
    BbsPage(),
    WorkPage(),
    // MeansPage(),
    HospitalPage(),
    FriendsList(),
    WodePage(),
  ];

  

  var _appBarTitles = ['首页', '工作台', '医院','聊天', '我的'];
  final _pageController = PageController();
  VersionItem versionItem = VersionItem();
  HomeProvider provider = HomeProvider();

  List<BottomNavigationBarItem> _list;
  double devicesHeight = window.physicalSize.height;
  Offset idleOffset=Offset(0, 0);
  Offset moveOffset=Offset(99999, 99999);
  Offset lastStartOffset=Offset(0, 0);
  PackageInfo packageInfo;
  @override
  void initState() {
    super.initState();
    initData();
    
    initUniLinks();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      getNewVersion();
    });
    // if (_sub != null) _sub.cancel();
    
  }

  getNewVersion() async{
    packageInfo = await PackageInfo.fromPlatform();
    ApiService(context: context).version(onSuccess: (res){
      if(res !=null){
        versionItem = res;
        int versionCode = FlutterStars.SpUtil.getInt("version_code")??0;

        if(versionItem.code>versionCode &&versionItem.code >int.parse(packageInfo.buildNumber)){
          _showUpdateDialog();
        }
        setState(() {

        });
      }

    },onError: (code,msg){

    });
  }

  void _showUpdateDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return UpdateDialog(content: versionItem.content,url:versionItem.url,code:versionItem.code,version: versionItem.version,forceUpdate: versionItem.forceUpdate==1?true:false,);
        }
    );
  }

  showAlertEvent(){
    showAlert(
                              context,
                              "提示",
                              "确定登录？",
                              "确定",
                              () {
                                NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                              },
                              txt2: "取消",
                              onPre2: () {
                                // NavigatorUtils.goBack(context);
                                // provider.value = 0;
                                //跳转到home
                                Navigator.of(context).pushAndRemoveUntil(
                                  MaterialPageRoute(builder: (context) => HomePage()),
                                      (route) => route == null);
                              },
                            );
  }

  String initialLink;
  Uri initialUri;

  @override
  dispose() {
    if (_sub != null) _sub.cancel();
    super.dispose();
  }

  void initData(){
    _pageList = [
      BbsPage(),
      WorkPage(),
      // MeansPage(),
      HospitalPage(),
      FriendsList(),
      WodePage(),
    ];
  }
  
  double middleSize = 60;
  

  List<BottomNavigationBarItem> _buildBottomNavigationBarItem(){
    if (_list == null){
      var _tabImages = [
        [
          const LoadAssetImage("home/tabar_quanzi_normal", width: 25.0, color: Colours.unselected_item_color,),
          const LoadAssetImage("home/tabar_quanzi_selected", width: 25.0,),
        ],
        [
          const LoadAssetImage("home/tabar_gongjutai_normal", width: 25.0, color: Colours.unselected_item_color,),
          const LoadAssetImage("home/tabar_gongjutai_selected", width: 25.0,),
        ],
        [
          const LoadAssetImage("home/yiyuan_b", width: 25.0, color: Colours.unselected_item_color,),
          const LoadAssetImage("home/yiyuan_a", width: 25.0,),
        ],
        [
          const LoadAssetImage("home/tabar_pengyou_normal", width: 25.0, color: Colours.unselected_item_color,),
          const LoadAssetImage("home/tabar_pengyou_selected", width: 25.0,),
        ],
        [
          const LoadAssetImage("home/tabar_wode_normal", width: 25.0, color: Colours.unselected_item_color,),
          const LoadAssetImage("home/tabar_wode_selected", width: 25.0,),
        ]
      ];
      _list = List.generate(5, (i){
        return BottomNavigationBarItem(
            icon: _tabImages[i][0],
            activeIcon: _tabImages[i][1],
            title: Padding(
              padding: const EdgeInsets.only(top: 1.5),
              child: Text(_appBarTitles[i], key: Key(_appBarTitles[i]),),
            )
        );
      });
    }
    return _list;
  }

  DateTime  _lastTime;

  Future<bool> _isExit(){
    if (_lastTime == null || DateTime.now().difference(_lastTime) > Duration(milliseconds: 2500)) {
      _lastTime = DateTime.now();
      toasts("再次点击退出应用");
      return Future.value(false);
    }
//    Toast.cancelToast();
    return Future.value(true);
  }
  
  StreamSubscription _sub;
  Future<void> initUniLinks() async {
    print('------获取参数--------');
    // Platform messages may fail, so we use a try/catch PlatformException.
      _sub = getLinksStream().listen((String link) {
        Uri u = Uri.parse(link);
        String path = u.queryParameters['page'];
        String id = u.queryParameters['id'];
        print('path');
        print(path);
        print(context);
        if(path.isNotEmpty && (FlutterStars.SpUtil.getString(Constant.userId) != "-1" || (FlutterStars.SpUtil.getString(Constant.userId) == "-1" && path != "/wode/vip"))){
          NavigatorUtils.push(context,"$path?id=$id");
        }else if (FlutterStars.SpUtil.getString(Constant.userId) == "-1" && path == "/wode/vip"){
          showAlertEvent();
        }
        print('---213---');
        print(link);
      // Parse the link and warn the user, if it is not correct
    }, onError: (err) {
      // Handle exception by warning the user their action did not succeed
    });

    initialLink = null;
    initialUri = null;
    // FlutterStars.SpUtil.putBool('isInitLink', false);
    // FlutterStars.SpUtil.getBool('isInitLink');
    if(FlutterStars.SpUtil.getBool('isInitLink') == null){
      FlutterStars.SpUtil.putBool('isInitLink', false);
    }
    if(FlutterStars.SpUtil.getBool('isInitLink')){
      initialLink = await getInitialLink();
      // toasts('initial link: $initialLink');
      if (initialLink != null) {
        initialUri = Uri.parse(initialLink);
        String path = initialUri.queryParameters['page'];
            String id = initialUri.queryParameters['id'];
            print('path');
            // toasts(path);
            // toasts("444");
            print(context);
            if(path.isNotEmpty && (FlutterStars.SpUtil.getString(Constant.userId) != "-1" || (FlutterStars.SpUtil.getString(Constant.userId) == "-1" && path != "/wode/vip"))){
              NavigatorUtils.push(context,"$path?id=$id");
            }else if (FlutterStars.SpUtil.getString(Constant.userId) == "-1" && path == "/wode/vip"){
              showAlert(
                              context,
                              "提示",
                              "确定登录？",
                              "确定",
                              () {
                                NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                              },
                              txt2: "取消",
                              onPre2: () {
                                NavigatorUtils.goBack(context);
                                //跳转到home
                                
                              },
                            );
            }
      }
    }
    FlutterStars.SpUtil.putBool('isInitLink', true);
    
  }

  @override
  Widget build(BuildContext context) {
    // ScreenUtil.instance = ScreenUtil(width: 750,height:1334)..init(context);
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
  
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);

    return ChangeNotifierProvider<HomeProvider>(
      create: (_) => provider,
      child: WillPopScope(
        onWillPop: _isExit,
        child: Container(
        color: Colors.white,
        child: SafeArea(
            top: false,
            child: Stack(
              children: <Widget>[
                Scaffold(
                    bottomNavigationBar: Consumer<HomeProvider>(
                      builder: (_, provider, __){
                        return BottomNavigationBar(
                          backgroundColor:  ThemeUtils.getTabsBg(context),
                          items:  _buildBottomNavigationBarItem(),
                          type: BottomNavigationBarType.fixed,
                          currentIndex: provider.value,
                          elevation: 0,
                          iconSize: 21.0,
                          selectedFontSize: Dimens.font_sp10,
                          unselectedFontSize: Dimens.font_sp10,
                          selectedItemColor: Theme.of(context).primaryColor,
                          unselectedItemColor:  Colours.unselected_item_color,
                          onTap: (index){
                            _pageController.jumpToPage(index);
                            setState(() {
                              middleSize = 60;
                            });
                          },
                        );
                      },
                    ),
                    // 使用PageView的原因参看 https://zhuanlan.zhihu.com/p/58582876
                    body: PageView(
                      controller: _pageController,
                      onPageChanged: _onPageChanged,
                      children: _pageList,
                      physics: NeverScrollableScrollPhysics(), // 禁止滑动
                    )
                ),
                
                
              ]
            )
        )
      ),
      )
    );
  }

  void _onPageChanged(int index) {
    if(index != 0 && FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
      showAlertEvent();
    }
    
    provider.value = index;
  }


}


