import 'package:flutter/material.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 '../model/UserInfo.dart';
import '../styles/totast.dart';
import '../net/Result.dart';
import '../model/UserLevel.dart';

class MyTeam extends StatefulWidget {
  @override
  MyTeamState createState() => MyTeamState();
}

class MyTeamState extends State<MyTeam> {
  List<UserInfo> teamList = [];
  bool isShow = false;
  num _topHeight;
  int currentPage = 1;
  bool canNext = true;
  List<UserLevel> levelList = [];

  ScrollController _controller;

  UserInfo higherLevel = UserInfo.empty();

  Future<void> getHigh() async {
    Result res = await HttpManager.get('userInfo/getUserInfo', data: {
      "id": StoreProvider.of<AppState>(context).state.userInfo.recommender
    });
    if (res.success) {
      setState(() {
        higherLevel = UserInfo.fromJson(res.data);
      });
    }
  }

  Future<void> getLevel() async {
    Result res = await HttpManager.get('userLevel/all', data: {});
    if (res.success) {
      setState(() {
        for (var item in res.data) {
          UserLevel _l = UserLevel.fromJson(item);
          levelList.add(_l);
        }
      });
    }
  }

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

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

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      if (StoreProvider.of<AppState>(context).state.userInfo.recommender !=
          null) {
        getHigh();
      }
      getLevelList();
      getLevel();
    });

    _controller = ScrollController();

    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent &&
          canNext) {
        currentPage++;
        getLevelList();
      }
    });
  }

  @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('我的团队'),
              centerTitle: true,
            ),
            body: Container(
              color: Color(0xFF2B2B42),
              height: double.infinity,
              child: SingleChildScrollView(
                controller: _controller,
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 128,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage('images/img_tuandui.png'),
                              fit: BoxFit.cover)),
                      child: Center(
                        child: Image.asset('images/text_01.png'),
                      ),
                    ),
                    higherLevel.id != null
                        ? Container(
                            padding: EdgeInsets.symmetric(vertical: 10),
                            color: Color(0xFF27273B),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 12, horizontal: 15),
                              color: Color(0xFF2B2B42),
                              child: Row(
                                children: <Widget>[
                                  Text(
                                    '我的上级',
                                    style: TextStyle(
                                        color: Theme.of(context).primaryColor,
                                        fontSize: 14,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(),
                                  ),
                                  CircleAvatar(
                                    backgroundImage:
                                        NetworkImage(higherLevel.icon),
                                  ),
                                  Container(
                                    width: 12,
                                  ),
                                  Text(higherLevel.nickname,
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 14,
                                          fontWeight: FontWeight.w500))
                                ],
                              ),
                            ),
                          )
                        : Container(
                            color: Color(0xFF27273B),
                            height: 10,
                          ),
                    Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 15, vertical: 20),
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                        width: 1,
                        color: Color(0xFF27273B),
                      ))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            '我的下级',
                            style: TextStyle(
                                color:Theme.of(context).primaryColor,
                                fontSize: 14,
                                fontWeight: FontWeight.w500),
                          ),
                          Text(
                            teamList.length.toString() + '位',
                            style: TextStyle(
                                color: Color(0xFF727785), fontSize: 13),
                          )
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: ListView(
                        shrinkWrap: true,
                        children: _widgetList(),
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  List<Widget> _widgetList() {
    List<Widget> list = [];
    if (teamList.isEmpty) {
      list.add(Padding(
        child: Center(
          child: Text('暂无数据', style: TextStyle(color: Colors.white24)),
        ),
        padding: EdgeInsets.symmetric(vertical: 10),
      ));
    } else {
      for (var item in teamList) {
        var _widget = Container(
          height: 60,
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
            width: 1,
            color: Color(0xFF27273B),
          ))),
          child: Row(
            children: <Widget>[
              CircleAvatar(
                backgroundImage: NetworkImage(item.icon),
              ),
              Container(
                width: 12,
              ),
              Expanded(
                  flex: 1,
                  child: Text(
                    item.nickname,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  )),
              backLevel(item.levelId)
            ],
          ),
        );
        list.add(_widget);
      }
    }
    return list;
  }

  Widget backLevel(int id) {
    Widget _w = Container();
    String name = '';
    for (var item in levelList) {
      if (id == item.id && id > 1) {
        name = item.name;
      }
    }
    if (name != '') {
      _w = Container(
        child: Text(
          name,
          style: TextStyle(fontSize: 12, color: Theme.of(context).primaryColor),
        ),
        padding: EdgeInsets.symmetric(vertical: 4, horizontal: 5),
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Theme.of(context).primaryColor)),
      );
    }

    return _w;
  }
}
