import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/BannerInfo.dart';
import '../widget/ITextInput.dart';
import '../widget/HouseItem.dart';
import '../model/HouseInfo.dart';
import 'package:flutter_picker/flutter_picker.dart';
import '../model/GameInfo.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'dart:math';

class SelectRoom extends StatefulWidget {
  @override
  _SelectRoomState createState() => _SelectRoomState();
}

class _SelectRoomState extends State<SelectRoom> 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 = '全部游戏';
  bool isFirst = true;
  FocusNode _focusNode = new FocusNode();

  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, '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 {
        scrollFlag = false;
      }
    } else {}

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

  Future<void> search(String text) async {
    if (text != searchKey) {
      currentPage = 1;
      setState(() {
        searchKey = text;
      });
      if (searchKey == '') {
        houseList = [];
      } else {
        getRoomInfo();
      }
    }
  }

  @override
  void initState() {
    super.initState();
    bannerList = [];
    _controller = ScrollController();
    // gameList.add(GameInfo.fromJson({"id": 0, "gameName": '全部游戏'}));
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        if (scrollFlag) {
          setState(() {
            currentPage++;
          });
          getRoomInfo();
        }
      }
      print('aaaaaaa');
      setState(() {
        _focusNode.unfocus();
      });
    });
    Future.delayed(Duration.zero, () {
      getGame();
      // getRoomInfo();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Scaffold(
          backgroundColor: Color(0xFF23253C),
          body: SafeArea(
            child: 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 = '';
                  getGame();
                },
                child: CustomScrollView(
                  physics: AlwaysScrollableScrollPhysics(),
                  controller: _controller,
                  slivers: <Widget>[
                    SliverPersistentHeader(
                      pinned: true, //是否固定在顶部
                      floating: true,
                      delegate: _SliverAppBarDelegate(
                          minHeight: 100, //收起的高度
                          maxHeight: 100, //展开的最大高度
                          child: Container(
                            color: Color(0xFF23253C),
                            height: 60,
                            padding: EdgeInsets.fromLTRB(15, 5, 0, 0),
                            margin: EdgeInsets.fromLTRB(0, 0, 0, 15),
                            child: Column(
                              // decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(4))),
                              children: [
                                ITextField(
                                    hintText: '房间标题/房间号/房主ID号',
                                    inputBorder: InputBorder.none,
                                    hintStyle: TextStyle(fontSize: 13, color: Color(0xFFB1B5C0), height: 1.2),
                                    textStyle: TextStyle(color: Colors.black),
                                    contentPadding: EdgeInsets.symmetric(vertical: 4),
                                    inputText: searchKey,
                                    fieldCallBack: (content) {
                                      search(content);
                                      // _focusNode.unfocus();
                                    },
                                    focusNode: _focusNode,
                                    counterStyle: TextStyle(color: Color(0xFF9BA0AE), fontSize: 0),
                                    textInputAction: TextInputAction.search,
                                    fileOnTap: () {
                                      // print('选择input');
                                      // if (_controller.position.pixels < 200) {
                                      //   _controller.animateTo(200, duration: Duration(milliseconds: 300), curve: Curves.ease);
                                      // }
                                    },
                                    hasCancel: true),
                                Container(
                                    width: double.infinity,
                                    height: 40,
                                    padding: EdgeInsets.symmetric(horizontal: 20),
                                    child: InkWell(
                                        onTap: () {
                                          showPicker(context);
                                        },
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Text(
                                              '筛选游戏',
                                              style: TextStyle(color: Colors.white54, fontSize: 12),
                                            ),
                                            Expanded(
                                              flex: 1,
                                              child: Container(),
                                            ),
                                            Container(
                                              padding: EdgeInsets.only(left: 5),
                                              alignment: Alignment.center,
                                              child: Text(
                                                gameName,
                                                style: TextStyle(color: Colors.white, fontSize: 12),
                                                overflow: TextOverflow.ellipsis,
                                                textAlign: TextAlign.right,
                                              ),
                                            ),
                                            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) {
                          if (searchKey != '') {
                            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 {
                            return Container();
                          }
                        } else if (index == houseList.length) {
                          return Text('更多房间敬请期待...', style: TextStyle(color: Colors.grey, fontSize: 13, height: 3), textAlign: TextAlign.center);
                        }
                        return HouseItem(
                          houseList[index],
                          houseList[index].gameInfo,
                          isNext: !_focusNode.hasFocus,
                          onTapHomeMenu: () {
                            setState(() {
                              _focusNode.unfocus();
                            });
                          },
                        );
                      }, childCount: houseList.length + 1),
                    )
                  ],
                ),
              ),
            ),
          )),
      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;
  }
}
