import 'package:flutter/material.dart';
import '../styles/colors.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/UserInfo.dart';
import '../net/HttpManager.dart';
import '../styles/totast.dart';
import '../net/Result.dart';
import '../model/MemberHouseCard.dart';
import 'dart:ui';
import '../widget/LinearButton.dart';
import '../widget/Dialog.dart';

class RoomCardList extends StatefulWidget {
  @override
  RoomCardListState createState() => RoomCardListState();
}

class RoomCardListState extends State<RoomCardList> {
  bool topshowCard = false;
  ScrollController _controller;
  int currentPage = 0;
  bool canNext = false;
  List<MemberHouseCard> list = [];

  Future<void> getList() async {
    canNext = false;
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('memberHouseCard/page', data: {
      'userId': StoreProvider.of<AppState>(context).state.userInfo.id,
      'currentPage': currentPage,
      'pageNumber': 20
    });
    Toast.hide();
    if (res.success) {
      if (currentPage == 1) {
        list = [];
      }
      setState(() {
        for (var item in res.data['pp']) {
          MemberHouseCard jsonp = MemberHouseCard.fromJson(item);
          list.add(jsonp);
        }
      });

      if (res.data['page']['totalNumber'] > currentPage) {
        canNext = true;
      }
    } else {}
  }

  Future<void> showDialog(id) async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('alertMessage/getOne', data: {'id': id});
    Toast.hide();
    if (res.success) {
      MyDialog.showDialog(context, res.data['remark']);
    }
  }

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

    Future.delayed(Duration.zero, () {
      getList();
    });
    _controller = new ScrollController();
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent &&
          canNext) {
        currentPage++;
        getList();
      }
      if (_controller.position.pixels >= 135) {
        setState(() {
          topshowCard = true;
        });
      } else {
        setState(() {
          topshowCard = false;
        });
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          return Scaffold(
            appBar: AppBar(
              title: Text.rich(TextSpan(children: [
                TextSpan(text: "房卡人数"),
                TextSpan(
                  text:
                      topshowCard ? ("：" + userInfo.houseCard.toString()) : '',
                  style: TextStyle(fontSize: 16),
                ),
              ])),
              centerTitle: true,
            ),
            body: RefreshIndicator(
              color: PRIMARY_COLOR,
              backgroundColor: Colors.white,
              onRefresh: () async {
                await Future.delayed(const Duration(seconds: 1));
                setState(() {
                  list = [];
                  currentPage = 1;
                });
                getList();
              },
              child: Container(
                color: BG_COLOR,
                child: CustomScrollView(
                    physics: AlwaysScrollableScrollPhysics(),
                    controller: _controller,
                    slivers: <Widget>[
                      SliverToBoxAdapter(
                        child: Container(
                          height: 135,
                          color: Color(0xFF27273B),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(userInfo.houseCard.toString(),
                                  style: TextStyle(
                                      color: PRIMARY_COLOR,
                                      fontSize: 38,
                                      fontWeight: FontWeight.w500,
                                      height: 1.4)),
                              Text('剩余人数名额',
                                  style: TextStyle(
                                      color: PRIMARY_COLOR,
                                      fontSize: 12,
                                      height: 1.4))
                            ],
                          ),
                        ),
                      ),
                      SliverList(
                        delegate: new SliverChildBuilderDelegate(
                            (BuildContext context, int index) {
                          if (index == 0) {
                            return Padding(
                              padding: EdgeInsets.fromLTRB(15, 20, 15, 15),
                              child: Text('名额明细',
                                  style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w500)),
                            );
                          }
                          //创建列表项
                          return new Container(
                            padding: EdgeInsets.all(15),
                            decoration: BoxDecoration(
                                border: Border(
                                    top: BorderSide(
                                        width: 1,
                                        color: Color(0xFF27273B),
                                        style: BorderStyle.solid))),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: 93,
                                  constraints: BoxConstraints(
                                      maxWidth: 93, minWidth: 93),
                                  // color: PRIMARY_COLOR,
                                  child: Text(list[index - 1].money.toString(),
                                      style: TextStyle(
                                          fontSize: 20,
                                          color: Colors.white,
                                          fontWeight: FontWeight.w500)),
                                ),
                                Expanded(
                                  flex: 1,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(list[index - 1].remark,
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.white)),
                                      Text(
                                        readTimestamp(
                                            list[index - 1].createTime,
                                            'yyyy.MM.dd HH:mm'),
                                        style: TextStyle(
                                            color: Color(0xFF727785),
                                            fontSize: 12,
                                            fontWeight: FontWeight.w400),
                                      )
                                    ],
                                  ),
                                )
                              ],
                            ),
                          );
                        }, childCount: list.length + 1),
                      ),
                      SliverToBoxAdapter(
                        child: list.length == 0
                            ? Container(
                                child: Column(
                                  children: <Widget>[
                                    Container(
                                      decoration: BoxDecoration(
                                          border: Border(
                                              top: BorderSide(
                                                  width: 1,
                                                  color: Color(0xFF27273B)))),
                                      height: 66,
                                    ),
                                    Image.asset('images/icon_kongbai.png'),
                                    Container(
                                      height: 20,
                                    ),
                                    Text('暂无相关明细',
                                        style: TextStyle(
                                            color: Color(0xFF575B7D),
                                            fontSize: 14))
                                  ],
                                ),
                              )
                            : Container(),
                      )
                    ]),
              ),
            ),
            floatingActionButton: Padding(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
              child: LinearButton(
                btntext: '增加房卡人数',
                onTapHomeMenu: () {
                  showDialog(4);
                },
              ),
            ),
            floatingActionButtonLocation:
                FloatingActionButtonLocation.centerDocked,
          );
        });
  }
}
