import 'package:flutter/material.dart';
import '../widget/HomeDrawer.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 'package:redux/redux.dart';
import '../model/UserInfo.dart';
import '../pages/openRoom.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, '暂时没有进行中的房间，敬请期待...');
  }

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

  @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 StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          return Scaffold(
            drawer: HomeDrawer(),
            body: WillPopScope(
              child: Container(
                width: double.infinity,
                height: double.infinity,
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: [
                          Color(0xFFC0C0C0),
                          Color(0xFF3D4043),
                          Color(0xFF383C40)
                        ],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        stops: [0.0, 0.15, 1.0])),
                child: SafeArea(
                  child: centerWidget(context, userInfo),
                ),
              ),
              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, UserInfo userInfo) {
    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>[
                                  Container(
                                    width: double.infinity,
                                    height: 52,
                                    decoration: BoxDecoration(
                                        image: DecorationImage(
                                            image: AssetImage(
                                                'images/img_guang_home.png'))),
                                    child: Text(
                                      '赛季奖金',
                                      style: TextStyle(
                                        color: Color(0xFFFFFFFF),
                                        fontSize: 26,
                                        fontFamily: 'Pangmen',
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: _moneyList(),
                                  ),
                                  Container(
                                    height: 15,
                                  ),
                                  seasonList[index]
                                              .competitionSeason
                                              .playerInfo
                                              .rank !=
                                          null
                                      ? Text(
                                          '当前排名 ' +
                                              seasonList[index]
                                                  .competitionSeason
                                                  .playerInfo
                                                  .rank
                                                  .toString(),
                                          style: TextStyle(
                                              color: Color(0xFFFFFFFF),
                                              fontSize: 24,
                                              fontFamily: 'Pangmen'))
                                      : Container(),
                                  Container(
                                    height: 12,
                                  ),
                                  Text.rich(TextSpan(
                                      children: [
                                        TextSpan(text: "倒计时 "),
                                        TextSpan(
                                          text: endSTring,
                                          style: TextStyle(fontSize: 27),
                                        ),
                                        TextSpan(
                                          text: ' 天',
                                        ),
                                      ],
                                      style: TextStyle(
                                          color: Color(0xFFFFFFFF),
                                          fontSize: 16,
                                          fontFamily: 'Pangmen')))
                                  // Container(
                                  //   height: 0.06 * (height - 334),
                                  // ),
                                  // Column(
                                  //   children: <Widget>[
                                  //     Text('当前排名',
                                  //         style: TextStyle(
                                  //             color: Color(0xFFFFFFFF),
                                  //             fontSize: 13)),
                                  //     Text('2',
                                  //         style: TextStyle(
                                  //             color: Color(0xFFFFFFFF),
                                  //             fontSize: 13))
                                  //   ],
                                  // )
                                ],
                              ),
                            ));
                          },
                        )
                      : Container()),
              Positioned(
                left: 26,
                top: 10,
                width: 48,
                height: 48,
                child: Material(
                  color: Colors.transparent,
                  child: Builder(
                    builder: (context) => InkWell(
                        onTap: () {
                          Scaffold.of(context).openDrawer();
                        },
                        child: Container(
                          width: 48,
                          height: 48,
                          padding: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [Color(0xFFFEFEFE), Color(0xFFBFBFBF)],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                              ),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(100)),
                              boxShadow: [
                                //阴影
                                BoxShadow(
                                    color: Colors.black45,
                                    offset: Offset(0, 2.0),
                                    blurRadius: 6.0)
                              ]),
                          child: CircleAvatar(
                            backgroundImage: NetworkImage(userInfo.icon),
                          ),
                        )),
                  ),
                ),
              ),
              Positioned(
                right: 12,
                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: 19),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        Builder(
          builder: (BuildContext context) {
            double aspectRatio = 1;
            aspectRatio = width / 334;
            return Container(
              height: 338,
              padding: EdgeInsets.fromLTRB(16, 34, 16, 26),
              width: double.infinity,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                colors: [
                  Color(0xFF394247),
                  Color(0xFF1C272D),
                  Color(0xFF08141A)
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              )),
              child: Column(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    height: 108,
                    child: HomeMenu(
                      '开始游戏',
                      onTapHomeMenu: () {
                        Navigator.push(
                            context,
                            CupertinoPageRoute(
                                builder: (context) => RoomList()));
                      },
                    ),
                  ),
                  Container(
                    height: 28,
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Column(
                          children: <Widget>[
                            Container(
                              height: 67,
                              child: HomeMenu(
                                '新增',
                                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) => OpenRoom(
                                            roomFlag: '0'
                                          )));
                                },
                              ),
                            ),
                            Container(
                              height: 8,
                            ),
                            Container(
                              height: 67,
                              child: HomeMenu(
                                '邮件',
                                onTapHomeMenu: () {
                                  Navigator.push(
                                      context,
                                      CupertinoPageRoute(
                                          builder: (context) => TipList()));
                                },
                              ),
                            )
                          ],
                        ),
                      ),
                      Container(
                        width: 14,
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          height: 142,
                          child: HomeMenu(
                            '商城',
                            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 = (6002222100 / 1000).toStringAsFixed(1);
    // print(bouns);
    // print(bouns.indexOf('.0'));
    if (bouns.indexOf('.0') != -1 || num.parse(bouns) > 99) {
      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('kong');
          _imageList.add('images/dian.png');
          _imageList.add('kong');
          break;
      }
    }
    if (_bounsList.isEmpty) {
      _imageList.add('images/0.png');
    }

    for (var item in _imageList) {
      if (item == 'kong') {
        _list.add(Container(
          width: 5,
        ));
      } else {
        if (_bounsList.length > 4) {
          _list.add(Image.asset(item, height: 300 / _bounsList.length));
        } else {
          _list.add(Image.asset(item));
        }
      }

      // 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(Image.asset(item));

      // } else {
      //   _list.add(Text(
      //     '.',
      //     style: TextStyle(color: Colors.white, fontSize: 36, fontFamily: 'DINEngschrift', height: 0),
      //   ));
      // }
    }
    _list.add(Container(width: 5));
    if (_bounsList.length > 4) {
      _list.add(Image.asset('images/K.png', height: 300 / _bounsList.length));
    } else {
      _list.add(Image.asset('images/K.png'));
    }

    return _list;
  }
}

typedef void OnTapHomeMenu();

class HomeMenu extends StatelessWidget {
  final String title;
  final OnTapHomeMenu onTapHomeMenu;
  final bool showBadge;
  HomeMenu(this.title, {this.onTapHomeMenu, this.showBadge = false});
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFFDFCF74), Color(0xFF6FB692)])),
      child: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFFFC30F), Color(0xFFFFA54C)])),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTapHomeMenu,
            child: Container(
              child: Center(
                  child: Text(
                title,
                style: TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 43,
                    fontFamily: 'Pangmen'),
              )),
            ),
          ),
        ),
      ),
    );
  }
}
