import 'package:flutter/material.dart';
import '../widget/HomeDrawer.dart';
import 'CreateRoom.dart';
import 'RoomList.dart';
import 'rankList.dart';
import 'roomInfo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../model/GameInfoSeasons.dart';
import '../styles/totast.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'TipList.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import 'setting.dart';
import '../widget/Dialog.dart';

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

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  List<GameInfoSeasons> seasonList = [];
  int nowIndex = 0;
  PageController _pageController;
  bool showBadge = false;

  void getSeasonInfo() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get("gameInfo/seasons");
    Toast.hide();
    if (res.success) {
      List<GameInfoSeasons> list = [];
      for (var item in res.data) {
        list.add(GameInfoSeasons.fromJson(item));
      }
      setState(() {
        seasonList = list;
      });
    } else {}
  }

  void showBackDialog() {
    MyDialog.showDialog(context, '暂时没有进行中的房间，敬请期待...');
    // showDialog<Null>(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (BuildContext context) {
    //     return new AlertDialog(
    //       content: Container(
    //         height: 50,
    //         child: Text(
    //           '暂时没有进行中的房间，敬请期待...',
    //           style: TextStyle(color: Colors.black),
    //         ),
    //       ),
    //       actions: <Widget>[
    //         new FlatButton(
    //           child: new Text('确定'),
    //           onPressed: () {
    //             Navigator.of(context).pop();
    //           },
    //         ),
    //       ],
    //     );
    //   },
    // ).then((val) {});
  }

  void getOneRoom() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get("houseInfo/getOne", data: {'statusFlag': 0});
    Toast.hide();
    if (res.success) {
      if (res.data != null) {
        Navigator.push(context, new CupertinoPageRoute(builder: (context) => new RoomInfo(roomId: res.data['id'].toString())));
      } else {
        showBackDialog();
      }
    }
  }

  void getUnreadMsg() async {
    Result res = await HttpManager.get("systemNotice/unread", data: {'userId': StoreProvider.of<AppState>(context).state.userInfo.id, 'statusFlag': 0});
    if (res.success && res.data != null) {
      if (res.data > 0) {
        setState(() {
          showBadge = true;
        });
      } else {
        setState(() {
          showBadge = false;
        });
      }
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _pageController = PageController(initialPage: 0);
    Future.delayed(Duration.zero, () {
      getSeasonInfo();
      getUnreadMsg();
    });
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      getUnreadMsg();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: HomeDrawer(),
      body: WillPopScope(
        child: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color.fromARGB(255, 177, 59, 56), Color.fromARGB(255, 147, 64, 61)], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
          child: SafeArea(
            child: centerWidget(context),
          ),
        ),
        onWillPop: () {
          Future.value(true);
        },
      ),
    );
  }

  Widget centerWidget(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: Stack(
            children: <Widget>[
              Container(
                  child: seasonList.length > 0
                      ? Swiper(
                          index: nowIndex,
                          itemCount: seasonList.length,
                          scrollDirection: Axis.horizontal,
                          loop: false,
                          onTap: (index) {
                            Navigator.push(
                                context,
                                new CupertinoPageRoute(
                                    builder: (context) =>
                                        new RankList(raceId: seasonList[index].competitionSeason.id, gameId: seasonList[index].competitionSeason.gameId)));
                          },
                          onIndexChanged: (index) {
                            setState(() {
                              nowIndex = index;
                            });
                          },
                          itemBuilder: (context, index) {
                            return Center(
                              child: SizedBox(
                                  width: 214,
                                  height: 214,
                                  child: Stack(
                                    children: <Widget>[
                                      Image.asset("images/home_icon_yuan.png"),
                                      Center(
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          crossAxisAlignment: CrossAxisAlignment.baseline,
                                          textBaseline: TextBaseline.alphabetic,
                                          children: <Widget>[
                                            Text(
                                              (seasonList[index].competitionSeason.bonus / 1000).toStringAsFixed(1),
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 68,
                                                fontFamily: 'DINEngschrift',
                                              ),
                                            ),
                                            Text(
                                              "K",
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 36,
                                                fontFamily: 'DINEngschrift',
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                      Positioned(
                                        bottom: 30,
                                        left: 0,
                                        right: 0,
                                        child: Column(
                                          children: <Widget>[
                                            // Text(
                                            //   "当前排名",
                                            //   style: TextStyle(
                                            //       color: Colors.white, fontSize: 13),
                                            // ),
                                            // Text(
                                            //   "98686",
                                            //   style: TextStyle(
                                            //       color: Colors.white, fontSize: 13),
                                            // )
                                          ],
                                        ),
                                      ),
                                    ],
                                  )),
                            );
                          },
                        )
                      : Container()),
              Positioned(
                left: 0,
                top: 0,
                width: 48,
                height: 48,
                child: Material(
                  color: Colors.transparent,
                  child: Builder(
                    builder: (context) => InkWell(
                          onTap: () {
                            Scaffold.of(context).openDrawer();
                          },
                          child: Padding(
                            padding: EdgeInsets.all(12),
                            child: Image.asset("images/home_icon_wode.png"),
                          ),
                        ),
                  ),
                ),
              ),
              Positioned(
                right: 0,
                top: 0,
                width: 48,
                height: 48,
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      Navigator.push(context, new CupertinoPageRoute(builder: (context) => new Setting()));
                    },
                    child: Padding(
                      padding: EdgeInsets.all(12),
                      child: Image.asset("images/home_icon_shezhi.png"),
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 11,
                left: 0,
                right: 0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      seasonList.length > 0 ? seasonList[nowIndex].competitionSeason.season : '',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    Text(
                      seasonList.length > 0 ? seasonList[nowIndex].gameName : '',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
        Builder(
          builder: (BuildContext context) {
            double width = MediaQuery.of(context).size.width;
            double height = MediaQuery.of(context).size.height;
            double aspectRatio = 1;
            // if (height / width < 20 / 9) {

            // }
            aspectRatio = width / (height - 350);
            return Container(
              child: GridView.count(
                physics: new BouncingScrollPhysics(),
                shrinkWrap: true,
                crossAxisCount: 2,
                childAspectRatio: aspectRatio,
                children: <Widget>[
                  HomeMenu(
                    "images/home_icon_fangjian.png",
                    "创建房间",
                    onTapHomeMenu: () {
                      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 CreateRoom();
                          }));
                    },
                  ),
                  HomeMenu(
                    "images/home_icon_kuaisu.png",
                    "快速进入",
                    onTapHomeMenu: () {
                      getOneRoom();
                    },
                  ),
                  HomeMenu(
                    "images/home_icon_sousuo.png",
                    "搜索",
                    onTapHomeMenu: () {
                      Navigator.push(context, new CupertinoPageRoute(builder: (context) => new RoomList()));
                    },
                  ),
                  HomeMenu(
                    "images/home_icon_youjian.png",
                    "邮件",
                    onTapHomeMenu: () async {
                      bool result = await Navigator.push(context, new CupertinoPageRoute(builder: (context) => new TipList()));
                      if (result) {
                        getUnreadMsg();
                      }
                    },
                    showBadge: showBadge,
                  ),
                ],
              ),
            );
          },
        ),
      ],
    );
  }
}

typedef void OnTapHomeMenu();

class HomeMenu extends StatelessWidget {
  final String icon;
  final String title;
  final OnTapHomeMenu onTapHomeMenu;
  final bool showBadge;
  HomeMenu(this.icon, this.title, {this.onTapHomeMenu, this.showBadge = false});
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration:
          BoxDecoration(gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Color(0xFF626C85), Color(0xFF3D3E6C)])),
      child: Container(
        decoration: BoxDecoration(
            border: Border(
                left: BorderSide(width: 0.5, color: Color(0x80000000)),
                right: BorderSide(width: 0.5, color: Color(0x80000000)),
                bottom: BorderSide(width: 1, color: Color(0x80000000)))),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTapHomeMenu,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: 44,
                  height: 34,
                  child: Stack(
                    children: <Widget>[
                      Image.asset(
                        icon,
                        fit: BoxFit.contain,
                        width: 44,
                        height: 34,
                      ),
                      Positioned(
                        right: 0,
                        top: 0,
                        child: Container(
                          width: showBadge ? 10 : 0,
                          height: showBadge ? 10 : 0,
                          decoration: BoxDecoration(color: Color.fromARGB(255, 239, 0, 9), borderRadius: BorderRadius.all(Radius.circular(10))),
                        ),
                      )
                    ],
                  ),
                ),
                Text(
                  title,
                  style: TextStyle(color: Colors.white, fontSize: 14),
                  textAlign: TextAlign.center,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
