import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/cupertino.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 '../widget/LinearButton.dart';
import '../model/BannerInfo.dart';
import '../widget/HouseItem.dart';
import '../model/HouseInfo.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'CompetitionInformation.dart';
import '../model/GameInfo.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'dart:math';
import 'SelectRoom.dart';
import '../model/PhoneInfo.dart';
import 'PhoneLogin.dart';

class MatchPage extends StatefulWidget {
  @override
  _MatchPageState createState() => _MatchPageState();
}

class _MatchPageState extends State<MatchPage> with WidgetsBindingObserver {
  List<HouseInfo> houseList = [];
  int currentPage = 0;
  bool showBadge = false;
  int gameId = 0;
  String searchKey = '';
  bool scrollFlag = false;
  List<BannerInfo> bannerList = [];
  ScrollController _controller;
  List<GameInfo> gameList = [];
  String gameName = '全部游戏';
  FocusNode _focusNode = new FocusNode();
  List<PhoneInfo> phoneList = [];
  int tipNum = 0;
  bool showMoreRoom = false;
  bool isFinish = false;
  Timer timer;

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

  //展示通知
  void showNotice() {
    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 CompetitionInformation();
        }));
  }

  void showPicker(BuildContext context) {
    List<String> _list = [];
    for (var item in gameList) {
      _list.add(item.gameName);
    }
    String PickerData = json.encode(_list);
    Picker(
        confirmText: '确定',
        cancelText: '取消',
        adapter: PickerDataAdapter<String>(pickerdata: JsonDecoder().convert(PickerData)),
        changeToFirst: true,
        textAlign: TextAlign.left,
        columnPadding: const EdgeInsets.all(8.0),
        onConfirm: (Picker picker, List value) {
          setState(() {
            gameId = gameList[value[0]].id;
            gameName = gameList[value[0]].gameName;
          });
        }).showModal(this.context);
  }

  Future<void> getGame() async {
    // Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('gameInfo/all');
    // Toast.hide();
    if (res.success) {
      List<GameInfo> _list = [];
      for (var item in res.data) {
        _list.add(GameInfo.fromJson(item));
      }
      setState(() {
        gameList = _list;
      });
    } else {}
  }

  Future<void> getRoomInfo() async {
    print('获取房间');
    Map<String, dynamic> data = {
      'currentPage': currentPage,
      'pageNumber': 20,
      'statusStr': '0,2',
      'myUserId': StoreProvider.of<AppState>(context).state.userInfo.id
    };

    data['advancedQuery'] = '';
    if (gameId != 0) {
      data['gameId'] = gameId;
    }
    data['searchKey'] = searchKey;
    List<HouseInfo> _allList = houseList;
    if (currentPage == 1) {
      _allList = [];
    }

    if (StoreProvider.of<AppState>(context).state.userInfo.recommender != null) {
      data['recommender'] = StoreProvider.of<AppState>(context).state.userInfo.recommender;
    }
    Result res = await HttpManager.get('houseInfo/page', data: data);
    if (res.success && res.data['pp'] != null) {
      for (var item in res.data['pp']) {
        HouseInfo _temHouse = HouseInfo.fromJson(item);
        _allList.add(_temHouse);
      }
      if (res.data['page']['currentPage'] < res.data['page']['totalPage']) {
        scrollFlag = true;
      } else {
        setState(() {
          isFinish = true;
        });
        scrollFlag = false;
      }
    } else {}

    setState(() {
      houseList = _allList;
    });
  }

  Future<void> search(String text) async {
    if (text != searchKey) {
      currentPage = 1;
      searchKey = text;
      getRoomInfo();
    }
  }

  Future<void> getBannerInfo() async {
    List<BannerInfo> _bannerList = [];
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('bannerInfo/all');
    Toast.hide();
    if (res.success && res.data != null) {
      for (var item in res.data) {
        BannerInfo banner = BannerInfo.fromJson(item);
        _bannerList.add(banner);
      }
      setState(() {
        bannerList = _bannerList;
      });
    }
  }

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

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

  @override
  void initState() {
    super.initState();
    bannerList = [];
    _controller = ScrollController();
    // gameList.add(GameInfo.fromJson({"id": 0, "gameName": '全部游戏'}));
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        print('底部。。。');
        setState(() {
          showMoreRoom = true;
        });
        if (scrollFlag) {
          setState(() {
            currentPage++;
          });
          getRoomInfo();
        } else {
          Future.delayed(Duration(seconds: 2), () async {
            setState(() {
              showMoreRoom = false;
            });
          });
        }
      }
    });
    Future.delayed(Duration.zero, () async {
      getUnreadMsg();
      getBannerInfo();
      getGame();
      getRoomInfo();

      if (timer != null) {
        timer.cancel();
      }
      timer = Timer.periodic(Duration(seconds: 2), (timer) {
        getUnreadMsg();
      });
    });
  }

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

  @override
  void dispose() {
    if (timer != null) {
      timer.cancel();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Scaffold(
          appBar: AppBar(
            title: Text('赛事'),
            centerTitle: true,
            leading: Material(
              color: Colors.transparent,
              child: Builder(
                builder: (context) => InkWell(
                  onTap: () async {
                    if (timer != null) {
                      timer.cancel();
                    }
                    bool result = await Navigator.push(context, CupertinoPageRoute(builder: (context) => TipList()));
                    if (result) {
                      timer = Timer.periodic(Duration(seconds: 2), (timer) {
                        getUnreadMsg();
                      });
                    }
                  },
                  child: Container(
                    width: 30,
                    height: 30,
                    child: Stack(
                      children: <Widget>[
                        Center(
                          child: Image.asset('images/home_icon_xiaoxi.png'),
                        ),
                        showBadge
                            ? Positioned(
                                right: 10,
                                top: 12,
                                child: Container(
                                  padding: EdgeInsets.all(1),
                                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(100))),
                                  child: Center(
                                    child: Container(
                                      padding: EdgeInsets.symmetric(horizontal: 3),
                                      height: 12,
                                      decoration: BoxDecoration(color: Color(0xFFD4504B), borderRadius: BorderRadius.all(Radius.circular(12))),
                                      child: Center(
                                        child: Text('${tipNum}', style: TextStyle(color: Colors.white, fontSize: 10)),
                                      ),
                                    ),
                                  ),
                                ),
                              )
                            : Container()
                      ],
                    ),
                  ),
                ),
              ),
            ),
            actions: <Widget>[
              Platform.isIOS
                  ? Container()
                  : Container(
                      width: 102,
                      padding: EdgeInsets.all(15),
                      child: LinearButton(
                        btntext: '配置帮助',
                        textColor: Color(0xFF2E3049),
                        btnHeight: 26.0,
                        colorList: [Color(0xFFFFB726), Color(0xFFFFB726)],
                        textSize: 12.0,
                        onTapHomeMenu: () {
                          // showNotice();
                          getPhoneInfo();
                        },
                      ),
                    )
            ],
          ),
          body: Container(
            color: Color(0xFF2E3049),
            height: double.infinity,
            width: double.infinity,
            child: RefreshIndicator(
              color: Theme.of(context).primaryColor,
              backgroundColor: Colors.white,
              displacement: 10,
              onRefresh: () async {
                await Future.delayed(const Duration(seconds: 1));
                gameId = 0;
                currentPage = 1;
                searchKey = '';
                getRoomInfo();
                // getBannerInfo();
                getGame();
              },
              child: CustomScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                controller: _controller,
                slivers: <Widget>[
                  SliverToBoxAdapter(
                    child: Container(
                      width: double.infinity,
                      height: 200,
                      child: new Swiper(
                          itemBuilder: (BuildContext context, int index) {
                            return Image.network(
                              bannerList[index].imageUrl,
                              fit: BoxFit.fill,
                            );
                          },
                          itemCount: bannerList.length,
                          loop: false,
                          autoplay: true,
                          autoplayDelay: 5000,
                          pagination: SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
                            Color activeColor = Color(0xFFD4504B);
                            Color color = Colors.white;
                            List<Widget> list = [];

                            int itemCount = config.itemCount;
                            int activeIndex = config.activeIndex;

                            for (int i = 0; i < itemCount; ++i) {
                              bool active = i == activeIndex;
                              list.add(
                                Container(
                                    key: Key("pagination_$i"),
                                    margin: EdgeInsets.symmetric(vertical: 3, horizontal: 2),
                                    child: Container(
                                      width: active ? 8 : 3,
                                      height: 3,
                                      decoration: BoxDecoration(color: active ? activeColor : color, borderRadius: BorderRadius.all(Radius.circular(3))),
                                    )),
                              );
                            }

                            return Container(
                              margin: EdgeInsets.only(top: 186),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: list,
                              ),
                            );
                          })),
                    ),
                  ),
                  SliverPersistentHeader(
                    pinned: true, //是否固定在顶部
                    floating: true,
                    delegate: _SliverAppBarDelegate(
                        minHeight: 60, //收起的高度
                        maxHeight: 60, //展开的最大高度
                        child: InkWell(
                            onTap: () {
                              Navigator.push(context, CupertinoPageRoute(builder: (context) => SelectRoom()));
                            },
                            child: Container(
                              color: Color(0xFF2E3049),
                              height: 60,
                              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                              child: Container(
                                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(4))),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: 10,
                                    ),
                                    ImageIcon(
                                      AssetImage('images/home_icon_sousuo.png'),
                                      color: Color(0xFF727785),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(Radius.circular(100)),
                                        ),
                                        child: Text('搜索竞赛房间', style: TextStyle(color: Color(0xFF9BA0AE), fontSize: 13)),
                                      ),
                                    ),
                                    Container(
                                      width: 1,
                                      height: 10,
                                      color: Color(0xFFB1B5C0),
                                    ),
                                    Container(
                                        width: 99,
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Expanded(
                                              flex: 1,
                                              child: Container(
                                                padding: EdgeInsets.only(left: 5),
                                                alignment: Alignment.center,
                                                child: Text(
                                                  gameName,
                                                  style: TextStyle(color: Color(0xFFB1B5C0)),
                                                  overflow: TextOverflow.ellipsis,
                                                ),
                                              ),
                                            ),
                                            Image.asset('images/icon_zhankai_huise.png'),
                                            Container(
                                              width: 5,
                                            )
                                          ],
                                        ))
                                  ],
                                ),
                              ),
                            ))),
                  ),
                  SliverFixedExtentList(
                    itemExtent: houseList.isEmpty ? 300 : 90,
                    delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                      if (houseList.isEmpty) {
                        return InkWell(
                          child: Container(
                            padding: EdgeInsets.only(top: 105),
                            child: Column(
                              children: <Widget>[
                                Image.asset('images/icon_kong.png'),
                                Text('暂时没有此房间哦～', style: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor.withOpacity(0.3)))
                              ],
                            ),
                          ),
                          onTap: () {
                            _focusNode.unfocus();
                          },
                        );
                      } else if (index == houseList.length) {
                        return Text(isFinish ? '更多房间敬请期待...' : '加载中...',
                            style: TextStyle(color: Colors.grey, fontSize: 13, height: 3), textAlign: TextAlign.center);
                      }
                      return HouseItem(houseList[index], houseList[index].gameInfo, isHome: true, isNext: !_focusNode.hasFocus, onTapHomeMenu: () {
                        setState(() {
                          _focusNode.unfocus();
                        });
                      }, onBack: () {
                        getUnreadMsg();
                        if (timer != null) {
                          timer.cancel();
                        }
                        timer = Timer.periodic(Duration(seconds: 2), (timer) {
                          getUnreadMsg();
                        });
                      }, onNext: () {
                        if (timer != null) {
                          timer.cancel();
                        }
                      });
                    }, childCount: (houseList.length != 0 && (houseList.length < 5 || !showMoreRoom)) ? houseList.length : houseList.length + 1),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      height: 30,
                    ),
                  )
                ],
              ),
            ),
          )),
      onTap: () {
        _focusNode.unfocus();
      },
    );
  }

  List<Widget> _houseList(houselist) {
    List<Widget> list = [];
    for (var i = 0; i < houselist.length; i++) {
      list.add(HouseItem(houselist[i], houselist[i].gameInfo));
    }

    return list;
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight || minHeight != oldDelegate.minHeight || child != oldDelegate.child;
  }
}

typedef OnTapHomeMenu = void Function();
