import 'package:flutter/material.dart';
import 'package:wanna_battle/model/PlayerInfo.dart';
import '../widget/HomeDrawer.dart';
import 'Appeal.dart';
import 'CreateRoom.dart';
import 'RoomList.dart';
import 'RankList.dart';
import 'RoomInfo.dart';
import 'ShoppingMall.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';
import '../pages/openRoom.dart';
import 'GuidePage.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;

  Future<void> getSeasonInfo() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('gameInfo/seasons', data: {
      'userId': StoreProvider.of<AppState>(context).state.userInfo.id,
    });
    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 AlertDialog(
    //       content: Container(
    //         height: 50,
    //         child: Text(

    //           style: TextStyle(color: Colors.black),
    //         ),
    //       ),
    //       actions: <Widget>[
    //         FlatButton(
    //           child: Text('确定'),
    //           onPressed: () {
    //             Navigator.of(context).pop();
    //           },
    //         ),
    //       ],
    //     );
    //   },
    // ).then((val) {});
  }

  Future<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, CupertinoPageRoute(builder: (context) => RoomInfo(roomId: res.data['id'].toString())));
      } else {
        showBackDialog();
      }
    }
  }

  Future<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;
        });
      }
    }
  }

  Future<void> checkErrorPlayerInfo() async {
    final Result res = await HttpManager.get('playerInfo/getErrorPlayerInfo');
    if (res.success) {
      final PlayerInfo playerInfo = PlayerInfo.fromJson(res.data);
      MyDialog.showDialog(
        context,
        '由于系统性能安全策略问题导致本次比赛结果上传失败，你可以上传本次比赛结果照片进行结果申诉',
        isCancel: true,
        onsubmit: () {
          Navigator.push(context, CupertinoPageRoute(builder: (context) => Appeal(playerInfo)));
        },
      );
    }
  }

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

      
    });
  }

  @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: () {
          return Future.value(true);
        },
      ),
      // floatingActionButton: floatWidget(),
      // floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget floatWidget() {
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100)), border: Border.all(width: 1, color: Color(0xFF1B1C28))),
      width: 166,
      height: 166,
      margin: EdgeInsets.only(bottom: 84),
      child: CircleAvatar(
          backgroundImage: AssetImage('images/centerBtn.png'),
          child: ClipOval(
              child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    child: Container(
                      width: 166,
                      height: 166,
                      child: Center(
                        child: UnconstrainedBox(
                          child: Image.asset('images/join.png', width: 85),
                        ),
                      ),
                    ),
                    onTap: () {
                      getOneRoom();
                    },
                  )))),
    );
  }

  Widget centerWidget(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    String endSTring = '';
    if (seasonList.isNotEmpty) {
      int _time = seasonList[nowIndex].competitionSeason.endTime - DateTime.now().millisecondsSinceEpoch;
      _time = _time ~/ 1000 ~/ 3600 ~/ 24;
      endSTring = '倒计时 ' + _time.toString() + ' 天';
    }

    return Column(
      children: <Widget>[
        Expanded(
          child: Stack(
            children: <Widget>[
              Container(
                  child: seasonList.isNotEmpty
                      ? Swiper(
                          index: nowIndex,
                          itemCount: seasonList.length,
                          scrollDirection: Axis.horizontal,
                          loop: false,
                          onTap: (index) {
                            Navigator.push(
                                context,
                                CupertinoPageRoute(
                                    builder: (context) =>
                                        RankList(raceId: seasonList[index].competitionSeason.id, gameId: seasonList[index].competitionSeason.gameId)));
                          },
                          onIndexChanged: (index) {
                            setState(() {
                              nowIndex = index;
                            });
                          },
                          itemBuilder: (context, index) {
                            return Center(
                                child: Container(
                              width: 0.64 * (height - 334),
                              height: 0.64 * (height - 334),
                              decoration: BoxDecoration(image: DecorationImage(image: AssetImage('images/home_icon_yuan.png'), fit: BoxFit.contain)),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text('赛季奖金', style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 13)),
                                  Container(
                                    height: 0.1 * (height - 334),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: _moneyList(),
                                  ),
                                  Container(
                                    height: 0.06 * (height - 334),
                                  ),
                                  Column(
                                    children: <Widget>[
                                      Text('当前排名', style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 13)),
                                      Text(
                                          seasonList[index].competitionSeason.playerInfo.rank != null
                                              ? seasonList[index].competitionSeason.playerInfo.rank.toString()
                                              : '无排名',
                                          style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 13))
                                    ],
                                  )
                                ],
                              ),
                            ));
                          },
                        )
                      : Container()),
              Positioned(
                left: 10,
                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/person.png',
                              width: 24,
                            ),
                          ),
                        ),
                  ),
                ),
              ),
              Positioned(
                right: 10,
                top: 0,
                width: 48,
                height: 48,
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => Setting()));
                    },
                    child: Padding(
                      padding: EdgeInsets.all(12),
                      child: Image.asset('images/setting.png', width: 24),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 15,
                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.isNotEmpty ? seasonList[nowIndex].gameName : '',
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    )
                  ],
                ),
              ),
              Positioned(
                bottom: 20,
                left: 0,
                right: 0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      endSTring,
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
        Builder(
          builder: (BuildContext context) {
            double aspectRatio = 1;
            aspectRatio = width / 334;
            return Container(
              child: GridView.count(
                physics: BouncingScrollPhysics(),
                shrinkWrap: true,
                crossAxisCount: 2,
                childAspectRatio: aspectRatio,
                children: <Widget>[
                  HomeMenu(
                    'images/home_icon_01.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();
                      //     }));
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => RoomList()));
                    },
                  ),
                  HomeMenu(
                    'images/home_icon_02.png',
                    '发起赛事',
                    onTapHomeMenu: () {
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => OpenRoom(roomFlag: '0')));
                    },
                  ),
                  HomeMenu(
                    'images/home_icon_03.png',
                    '系统通知',
                    onTapHomeMenu: () async {
                      bool result = await Navigator.push(context, CupertinoPageRoute(builder: (context) => TipList()));
                      if (result) {
                        getUnreadMsg();
                      }
                    },
                    showBadge: showBadge,
                  ),
                  HomeMenu(
                    'images/home_icon_04.png',
                    '充值',
                    onTapHomeMenu: () {
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => ShoppingMall()));
                    },
                  ),
                ],
              ),
            );
          },
        ),
      ],
    );
  }

  List<Widget> _moneyList() {
    double height = MediaQuery.of(context).size.height;
    List<Widget> _list = [];

    String bouns = (seasonList[nowIndex].competitionSeason.bonus / 1000).toStringAsFixed(1);

    // String bouns = (900000000100 / 1000).toStringAsFixed(1);
    // print(bouns);
    // print(bouns.indexOf('.0'));
    if (bouns.indexOf('.0') != -1 || num.parse(bouns) > 999) {
      bouns = bouns.substring(0, bouns.length - 2);
    }

    List<String> _bounsList = bouns.split('');
    List<String> _imageList = [];
    for (var item in _bounsList) {
      switch (item) {
        case '0':
          _imageList.add('images/0.png');
          break;
        case '1':
          _imageList.add('images/1.png');
          break;
        case '2':
          _imageList.add('images/2.png');
          break;
        case '3':
          _imageList.add('images/3.png');
          break;
        case '4':
          _imageList.add('images/4.png');
          break;
        case '5':
          _imageList.add('images/5.png');
          break;
        case '6':
          _imageList.add('images/6.png');
          break;
        case '7':
          _imageList.add('images/7.png');
          break;
        case '8':
          _imageList.add('images/8.png');
          break;
        case '9':
          _imageList.add('images/9.png');
          break;
        case '.':
          _imageList.add('.');
          break;
      }
    }
    if (_bounsList.isEmpty) {
      _imageList.add('images/0.png');
    }

    for (var item in _imageList) {
      if (item != '.') {
        if (_imageList.length > 4) {
          double _scale = 1 - (_imageList.length - 4) * 0.2;
          _list.add(Image.asset(item, height: 0.18 * 0.64 * (height - 334) * _scale));
        } else {
          _list.add(Image.asset(item, height: 0.18 * 0.64 * (height - 334)));
        }

        // _list.add(Container(width: 5));
      } else {
        _list.add(Text(
          '.',
          style: TextStyle(color: Colors.white, fontSize: 36, fontFamily: 'DINEngschrift', height: 1),
        ));
      }
    }
    _list.add(Text(
      'K',
      style: TextStyle(color: Colors.white, fontSize: 24, fontFamily: 'DINEngschrift', height: .5),
    ));
    return _list;
  }
}

typedef void OnTapHomeMenu();

class HomeMenu extends StatelessWidget {
  final String icon;
  final String name;
  final OnTapHomeMenu onTapHomeMenu;
  final bool showBadge;
  HomeMenu(this.icon, this.name, {this.onTapHomeMenu, this.showBadge = false});
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              stops: [0.0, 0.01, 0.8],
              colors: [Color(0xFF7E89B7), Color(0xFF4E536F), Color(0xFF333558)])),
      child: Container(
        decoration: BoxDecoration(
            border: Border(
                // top: BorderSide(width: 2,color: Color(0xFF7E89B7)),
                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: Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    icon,
                    fit: BoxFit.contain,
                  ),
                  Container(
                    height: 5,
                  ),
                  Text(
                    name,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
