import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../styles/colors.dart';
import '../widget/RoomItem.dart';
import '../widget/PopupButton.dart';
import 'dart:ui';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../model/HouseInfo.dart';
import '../widget/ITextInput.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';

class RoomList extends StatefulWidget {
  @override
  RoomListState createState() => RoomListState();
}

class RoomListState extends State<RoomList> {
  List<HouseInfo> roomList = [];
  int currentPage = 1;
  ScrollController _controller;
  bool scrollFlag = true;
  bool _showSearch = false;

  String gameId = '';
  String houseLevel = '';
  String houseType = '';
  String statusFlag = '';
  String searchKey = '';
  FocusNode _contentFocusNode = FocusNode();

  List gameList = [
    {'id': '', 'gameName': '全部游戏'}
  ];
  List levelList = [
    {'levelName': '全部等级', 'id': ''}
  ];
  List typeList = [
    {'name': '全部房间', 'val': ''},
    {'name': '普通房间', 'val': '0'},
    {'name': '官方房间', 'val': '1'}
  ];
  List statusList = [
    {'name': '不限状态', 'val': ''},
    {'name': '等待中', 'val': '0'},
    // {'name': '准备中', 'val': '1'},
    // {'name': '已经开始', 'val': '2'},
    // {'name': '正在结算', 'val': '3'},
    {'name': '结算完成', 'val': '4'}
  ];

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

  @override
  void initState() {
    super.initState();

    _controller = ScrollController();
    _controller.addListener(() {
      // print('1111111');
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
      
        if (scrollFlag) {
          setState(() {
            currentPage++;
          });
          getRoomInfo();
        }
      }
    });
    Future.delayed(Duration.zero, () {
      getRoomInfo();
      getInfo();
    });
  }

  Future<void> getInfo() async {
    Result res = await HttpManager.get('gameInfo/all');
    if (res.success) {
      setState(() {
        gameList.addAll(res.data);
      });
    }

    Result res2 = await HttpManager.get('houseLevel/all');
    if (res2.success) {
      setState(() {
        levelList.addAll(res2.data);
      });
    }
  }

  Future<void> changeGame(BuildContext context) async {
    String sex = await showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return CupertinoActionSheet(
            title: Text('选择性别'),
            actions: <Widget>[
              CupertinoActionSheetAction(
                child: Text('男'),
                onPressed: () {
                  Navigator.pop(context, '男');
                },
              ),
              CupertinoActionSheetAction(
                child: Text('女'),
                onPressed: () {
                  Navigator.pop(context, '女');
                },
              )
            ],
            cancelButton: CupertinoDialogAction(
              child: const Text('取消'),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          );
        });
  }

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

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);

    return Scaffold(
        appBar: !_showSearch
            ? AppBar(
                title: Text('房间列表'),
                centerTitle: true,
                elevation: 0,
                actions: <Widget>[
                  GestureDetector(
                    child: Image.asset('images/icon_sousuo.png'),
                    onTap: () async {
                      setState(() {
                        _showSearch = true;
                      });
                      // String result = await 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 searchInput();
                      //         }));
                      // if (result != '' || searchKey != '') {
                      //   search(result);
                      // }
                    },
                  )
                ],
              )
            : null,
        body: RefreshIndicator(
          color: PRIMARY_COLOR,
          backgroundColor: Colors.white,
          onRefresh: () async {
            await Future.delayed(const Duration(seconds: 1));
            setState(() {
              currentPage = 1;
            });
            getRoomInfo();
          },
          child: Container(
            color: Color(0xFF363759),
            child: Stack(
              children: <Widget>[
                CustomScrollView(
                  controller: _controller,
                  physics: AlwaysScrollableScrollPhysics(),
                  slivers: <Widget>[
                    SliverToBoxAdapter(
                      child: Container(
                        height: _showSearch ? MediaQueryData.fromWindow(window).padding.top + 100 : 44,
                      ),
                    ),
                    SliverFixedExtentList(
                      itemExtent: roomList.isEmpty ? 300 : ScreenUtil().setWidth(78),
                      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                        if (roomList.isEmpty) {
                          return 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)))
                              ],
                            ),
                          );
                        } else if (index == roomList.length) {
                          return Text('更多房间敬请期待...', style: TextStyle(color: Colors.grey, fontSize: 13, height: 3), textAlign: TextAlign.center);
                        }
                        return HouseItem(roomInfo: roomList[index], gameInfo: roomList[index].gameInfo);
                      }, childCount: roomList.length + 1),
                    )
                  ],
                ),
                // _topWidget(),
                _filifter(context),
                _showSearch ? _searchInput() : Container()
              ],
            ),
          ),
        ));
  }

  Widget _filifter(BuildContext context) {
    Map gameInfo = {};
    for (var item in gameList) {
      if (item['id'].toString() == gameId.toString()) {
        gameInfo = item;
      }
    }
    return Positioned(
      top: _showSearch ? MediaQueryData.fromWindow(window).padding.top + 56 : 0,
      width: 375,
      height: 44,
      child: Container(
        color: Color(0xFF2B2B42),
        padding: EdgeInsets.only(left: 22, right: 20),
        child: Row(
          children: <Widget>[Text('筛选游戏', style: TextStyle(fontSize: 12, color: Colors.white54)), _chooseGame()],
        ),
      ),
    );
  }

  Widget _topWidget() {
    return Positioned(
      top: _showSearch ? MediaQueryData.fromWindow(window).padding.top + 56 : 0,
      width: ScreenUtil().setWidth(375),
      height: 44,
      child: Container(
        padding: EdgeInsets.all(14),
        color: Color(0xFF2B2B42),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[_chooseGame(), _chooseHouseType(), _chooseLevel(), _chooseStatus()],
        ),
      ),
    );
  }

//选择游戏
  Widget _chooseGame() {
    Map gameInfo = {};
    for (var item in gameList) {
      if (item['id'].toString() == gameId.toString()) {
        gameInfo = item;
      }
    }
    return Expanded(
      flex: 1,
      child: MyPopupMenuButton(
          initialValue: gameId,
          padding: EdgeInsets.all(0.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Text(
                  gameInfo['gameName'],
                  style: TextStyle(color: gameId != '' ? PRIMARY_COLOR : Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.right,
                ),
              ),
              Icon(
                Icons.keyboard_arrow_down,
                color: gameId != '' ? PRIMARY_COLOR : Colors.white,
                size: 18,
              ),
            ],
          ),
          onSelected: (value) {
            setState(() {
              gameId = value;
            });
            currentPage = 1;
            getRoomInfo();
          },
          itemBuilder: (BuildContext context) {
            return gameList.map((choice) {
              return MyPopupMenuItem(
                  child: Text(
                    choice['gameName'],
                    style: TextStyle(fontSize: 14),
                  ),
                  value: choice['id'].toString());
            }).toList();
          }),
    );
  }

//选择等级
  Widget _chooseLevel() {
    Map levelInfo = {};
    for (var item in levelList) {
      if (item['id'].toString() == houseLevel.toString()) {
        levelInfo = item;
      }
    }
    return Expanded(
      flex: 1,
      child: MyPopupMenuButton(
          initialValue: houseLevel,
          padding: EdgeInsets.all(0.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Text(
                  levelInfo['levelName'],
                  style: TextStyle(color: houseLevel != '' ? PRIMARY_COLOR : Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
              Icon(
                Icons.keyboard_arrow_down,
                color: houseLevel != '' ? PRIMARY_COLOR : Colors.white,
                size: 18,
              ),
            ],
          ),
          onSelected: (value) {
            setState(() {
              houseLevel = value;
            });
            currentPage = 1;
            getRoomInfo();
          },
          itemBuilder: (BuildContext context) {
            return levelList.map((choice) {
              return MyPopupMenuItem(
                  child: Text(
                    choice['levelName'],
                    style: TextStyle(fontSize: 14),
                  ),
                  value: choice['id'].toString());
            }).toList();
          }),
    );
  }

  //选择房间状态
  Widget _chooseHouseType() {
    Map typeInfo = {};
    for (var item in typeList) {
      if (item['val'] == houseType) {
        typeInfo = item;
      }
    }
    return Expanded(
      flex: 1,
      child: MyPopupMenuButton(
          initialValue: houseType,
          padding: EdgeInsets.all(0.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Text(
                  typeInfo['name'],
                  style: TextStyle(color: houseType != '' ? PRIMARY_COLOR : Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
              Icon(
                Icons.keyboard_arrow_down,
                color: houseType != '' ? PRIMARY_COLOR : Colors.white,
                size: 18,
              ),
            ],
          ),
          onSelected: (value) {
            setState(() {
              houseType = value;
            });
            currentPage = 1;
            getRoomInfo();
          },
          itemBuilder: (BuildContext context) {
            return typeList.map((choice) {
              return MyPopupMenuItem(
                  child: Text(
                    choice['name'],
                    style: TextStyle(fontSize: 14),
                  ),
                  value: choice['val']);
            }).toList();
          }),
    );
  }

  //选择状态
  Widget _chooseStatus() {
    Map statusInfo = {};
    for (var item in statusList) {
      if (item['val'] == statusFlag) {
        statusInfo = item;
      }
    }
    return Expanded(
      flex: 1,
      child: MyPopupMenuButton(
          initialValue: statusFlag,
          padding: EdgeInsets.all(0.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Text(
                  statusInfo['name'],
                  style: TextStyle(color: statusFlag != '' ? PRIMARY_COLOR : Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
              Icon(
                Icons.keyboard_arrow_down,
                color: statusFlag != '' ? PRIMARY_COLOR : Colors.white,
                size: 18,
              ),
            ],
          ),
          onSelected: (value) {
            setState(() {
              statusFlag = value;
            });
            currentPage = 1;
            getRoomInfo();
          },
          itemBuilder: (BuildContext context) {
            return statusList.map((choice) {
              return MyPopupMenuItem(
                  child: Text(
                    choice['name'],
                    style: TextStyle(fontSize: 14),
                  ),
                  value: choice['val']);
            }).toList();
          }),
    );
  }

  Future<void> getRoomInfo() async {
    Map<String, dynamic> data = {'currentPage': currentPage, 'pageNumber': 20, 'myUserId': StoreProvider.of<AppState>(context).state.userInfo.id};
    data['advancedQuery'] = '';
    if (gameId != '') {
      data['gameId'] += gameId;
    }
    // if (houseLevel != '') {
    //   data['advancedQuery'] += 'AND_,houseLevel_,=_,' + houseLevel + '_;';
    // }
    // if (houseType != '') {
    //   data['advancedQuery'] += 'AND_,houseType_,=_,' + houseType + '_;';
    // }
    // if (statusFlag != '') {
    //   data['advancedQuery'] += 'AND_,statusFlag_,=_,' + statusFlag + '_;';
    // } else {
    //   data['statusStr'] = '0,4';
    // }
    data['searchKey'] = searchKey;
    List<HouseInfo> _allList = roomList;
    if (currentPage == 1) {
      _allList = [];
    }

    if (StoreProvider.of<AppState>(context).state.userInfo.recommender != null) {
      data['recommender'] = StoreProvider.of<AppState>(context).state.userInfo.recommender;
    }

    print(data);

    // myUserId=84705&recommender=84702
    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(() {
      roomList = _allList;
    });

    // final response = await Dio().get(domain + 'houseInfo/page', data: data);
    // final res = json.decode(response.toString());
    // if (res['success']) {
    //   for (var item in res['data']['pp']) {
    //     setState(() {
    //       roomList.add(item);
    //     });
    //   }
    //   if (res['data']['page']['currentPage'] <
    //       res['data']['page']['totalPage']) {
    //     scrollFlag = true;
    //   } else {
    //     scrollFlag = false;
    //   }
    // }
  }

  Widget _searchInput() {
    return Positioned(
      child: Container(
          padding: EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top, left: 15),
         color:Theme.of(context).primaryColor,
          height: MediaQueryData.fromWindow(window).padding.top + 56,
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  height: 34,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(100)),
                  ),
                  child: ITextField(
                      focusNode: _contentFocusNode,
                      autofocus: true,
                      hintText: '输入房间名称/房间号/创建人Code',
                      inputBorder: InputBorder.none,
                      hintStyle: TextStyle(
                        fontSize: 16,
                        color: Color(0xFF727785),
                      ),
                      textStyle: TextStyle(color: Colors.black),
                      contentPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 19),
                      fieldCallBack: (content) {
                        search(content);
                      },
                      counterStyle: TextStyle(color: BG_SUB_COLOR, fontSize: 0),
                      textInputAction: TextInputAction.search),
                ),
              ),
              InkWell(
                child: Container(
                  padding: EdgeInsets.fromLTRB(16, 0, 15, 4),
                  child: Text('取消', style: TextStyle(color: Colors.white, fontSize: 16)),
                ),
                onTap: () {
                  setState(() {
                    _showSearch = false;
                    currentPage = 1;
                    searchKey = '';
                    statusFlag = '';
                    houseLevel = '';
                    houseType = '';
                    getRoomInfo();
                  });
                },
              )
            ],
          )),
    );
  }
}
