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 '../model/GameInfo.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;

  String gameId = '';
  String houseLevel = '';
  String houseType = '';
  String statusFlag = '0';

  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'}
  ];

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

    _controller = ScrollController();
    _controller.addListener(() {
      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);
      });
    }
  }

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

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

    return Scaffold(
        appBar: AppBar(
          backgroundColor: PRIMARY_COLOR,
          title: Text('房间列表'),
          centerTitle: true,
          elevation: 0,
        ),
        body: RefreshIndicator(
          color: PRIMARY_COLOR,
          backgroundColor: Colors.white,
          onRefresh: () async {
            await Future.delayed(const Duration(seconds: 1));
            setState(() {
              currentPage = 1;
            });
            getRoomInfo();
          },
          child: Container(
            color: BG_COLOR,
            child: Stack(
              children: <Widget>[
                CustomScrollView(
                  controller: _controller,
                  physics: AlwaysScrollableScrollPhysics(),
                  slivers: <Widget>[
                    SliverToBoxAdapter(
                      child: Container(
                        height: 44,
                      ),
                    ),
                    SliverFixedExtentList(
                      itemExtent: ScreenUtil().setWidth(78),
                      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
                        if(roomList.isEmpty){
                          return Text('暂无数据',style: TextStyle(
                            color: Colors.grey,
                            fontSize: 13,
                            height:3
                          ),textAlign: TextAlign.center);
                        }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()
              ],
            ),
          ),
        ));
  }

  Widget _topWidget() {
    return Positioned(
      width: ScreenUtil().setWidth(375),
      height: 44,
      child: Container(
        padding: EdgeInsets.all(14),
        color: Color(0xFF3A3D5C),
        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.center,
                ),
              ),
              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,
    };
    data['advancedQuery'] = '';
    if (gameId != '') {
      data['advancedQuery'] += 'AND_,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';
    }
    List<HouseInfo> _allList=roomList;
    if(currentPage==1){
      _allList=[];
    }
    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;
    //   }
    // }
  }
}
