import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanna_battle/model/PlayerInfo.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/cupertino.dart';
import 'package:wanna_battle/model/PopNotice.dart';
import 'GuidePage.dart';
import 'MatchPage.dart';
import 'RankList.dart';
import '../widget/BottomTabs.dart';
import 'UserPage.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'RoomInfo.dart';
import '../styles/totast.dart';
import 'dart:async';
import 'dart:ui';
import '../model/PhoneInfo.dart';
import 'PhoneLogin.dart';
import '../model/PopNotice.dart';
import '../utils/Utils.dart';

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

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  TabController controller;
  bool isFirst = true;
  bool showPage = false;
  List<PhoneInfo> phoneList;
  List<PopNotice> popNoticeList;

  Future<bool> getPhoneInfo() async {
    List<PhoneInfo> _phoneList = [];
    Result res = await HttpManager.get('phoneInfo/all');
    if (res.success && res.data != null) {
      for (var item in res.data) {
        PhoneInfo phone = PhoneInfo.fromJson(item);
        _phoneList.add(phone);
      }
      setState(() {
        phoneList = _phoneList;
      });
    }

    final prefs = await SharedPreferences.getInstance();
    var now = new DateTime.now();
    var timeStr = now.year.toString() + '/' + now.month.toString() + '/' + now.day.toString();
    prefs.setString('showPhoneInfo', timeStr);

    bool reslt = await Navigator.of(context).push(
      PageRouteBuilder(
        opaque: false,
        transitionDuration: Duration(milliseconds: 300),
        transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
          return FadeTransition(
            opacity: CurvedAnimation(parent: animation, curve: Curves.linear),
            child: child,
          );
        },
        pageBuilder: (BuildContext context, _, __) {
          return PhoneLogin(
            // text: '部分手机自动设置了省电策略，会将我们的app在游戏进程中从后台停掉，为了你的正常比赛，请点击你的手机型号查看具体设置',
            phoneList: phoneList,
          );
        },
      ),
    );

    if (reslt != null && reslt) {
      return true;
    } else {
      return false;
    }
  }

  Future<void> checkErrorPlayerInfo() async {
    popNoticeList = [];
    Result res1 = await HttpManager.get('popNotice/all');
    if (res1.success) {
      for (var item in res1.data) {
        popNoticeList.add(PopNotice.fromJson(item));
      }
    }

    final prefs = await SharedPreferences.getInstance();
    var now = new DateTime.now();
    var timeStr = now.year.toString() + '/' + now.month.toString() + '/' + now.day.toString();
    bool show = false;
    if (prefs.getString('showPhoneInfo') != timeStr && Platform.isAndroid) {
      await getPhoneInfo();
    }

    showGruide(context, popNoticeList);

    final Result res = await HttpManager.get('playerInfo/getErrorPlayerInfo');
    print('&********');
    print(res.error);
    if (res.success) {
      final PlayerInfo playerInfo = PlayerInfo.fromJson(res.data);
      // MyDialog.showDialog(
      //   context,
      //   '由于系统性能安全策略问题导致本次比赛结果上传失败，你可以上传本次比赛结果照片进行结果申诉',
      //   isCancel: true,
      //   onsubmit: () {
      //     Navigator.push(context, CupertinoPageRoute(builder: (context) => Appeal(playerInfo)));
      //   },
      // );
      final res1 = await HttpManager.get('houseInfo/getOne', data: {'id': playerInfo.houseId});
      if (res1.success && res1.data != null) {
        Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => RoomInfo(
              roomId: res1.data['id'].toString(),
              // playerInfo: playerInfo,
              // interrupted: true,
            ),
          ),
        );
      }
    } else {
      //引导页

    }
  }

  @override
  void initState() {
    super.initState();
    controller = new TabController(length: 3, vsync: this);
    Future.delayed(Duration.zero, () async {
      await checkErrorPlayerInfo();
      getVersion(context);
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xFF2E3049),
        body: WillPopScope(
          child: Container(
            color: Color(0xFF2E3049),
            child: showPage
                ? MyTabBarView(
                    controller: controller,
                    children: <Widget>[MatchPage(), RankList(), UserPage()],
                  )
                : Container(),
          ),
          onWillPop: () async {
            if (isFirst) {
              isFirst = false;
              Toast.show(context, '再次点击退出程序', 1000, 'info');
              Timer(Duration(seconds: 1), () {
                isFirst = true;
              });
              return Future.value(false);
            } else {
              return await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            }
          },
        ),
        bottomNavigationBar: showPage
            ? Container(
                color: Color(0xFF23253C),
                height: 49,
                child: MyTabBar(
                  controller: controller,
                  labelColor: Theme.of(context).primaryColor,
                  unselectedLabelColor: Color(0xFF46496C),
                  indicatorColor: Color(0xFF171721),
                  labelPadding: EdgeInsets.zero,
                  labelStyle: TextStyle(fontSize: 11, height: 1),
                  tabs: <Widget>[
                    MyTab(
                      text: "赛事",
                      icon: ImageIcon(AssetImage('images/tabbar_icon_01_pre.png'), size: 28),
                    ),
                    MyTab(
                      text: "排行",
                      icon: ImageIcon(AssetImage('images/tabbar_icon_02.png'), size: 28),
                    ),
                    MyTab(
                      text: "我的",
                      icon: ImageIcon(AssetImage('images/tabbar_icon_03.png'), size: 28),
                    ),
                  ],
                ),
              )
            : Container()
        // floatingActionButton: floatWidget(),
        // floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        );
  }

  Future<void> showGruide(BuildContext context, List<PopNotice> popNoticeList) async {
    bool res = await Navigator.of(context).push(PageRouteBuilder(
        opaque: false,
        transitionDuration: Duration(milliseconds: 300),
        transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
          return FadeTransition(
            opacity: CurvedAnimation(parent: animation, curve: Curves.linear),
            child: child,
          );
        },
        pageBuilder: (BuildContext context, _, __) {
          return GuidePage(popNoticeList);
        }));

    if (res != null && res) {
      setState(() {
        showPage = true;
      });
    }
  }
}
