import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/model/ContactInfo.dart';
import 'package:base/services/company_services.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/name_value.dart';

class Contact extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _ContactState();
  }
}

class _ContactState extends State<Contact> {
  bool isAnimating = false;
  int pageIndex = 1;
  bool hasNext = true;
  List<ContractInfo> pageData = List();
  List<ContractInfo> tmpData = List();

  //GlobalKey<EasyRefreshState> _easyRefreshKey = new GlobalKey<EasyRefreshState>();
  //GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();
  //GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();
  FocusNode _focusNode = new FocusNode();
  final TextEditingController _controller = new TextEditingController();
  EasyRefreshController _controllers = EasyRefreshController();
  String theme = "";

  @override
  Widget build(BuildContext context) {
    if (this.theme.isEmpty) {
      return Scaffold(body: Text(""));
    }
    return Scaffold(
        appBar: AppBar(
          elevation: 0.3,
          brightness: Brightness.light,
          backgroundColor: KColorConstant.topBarColor,
          leading: new Container(
            child: GestureDetector(
              onTap: () {
                _focusNode.unfocus();
                Navigator.pop(context);
              },
              child: Icon(Icons.keyboard_arrow_left,
                  color: GetConfig.getColor(theme), size: 32),
            ),
          ),
          title: new Container(
              height: 30,
              width: MediaQuery.of(context).size.width - 130,
              //color: Colors.blue,
              padding: EdgeInsets.only(bottom: 5),
              decoration: new BoxDecoration(
                color: Colors.grey[100],
                borderRadius: new BorderRadius.all(Radius.circular(25.0)),
              ),
              child: Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left: 5, right: 5, top: 6),
                    child: Image.asset("assets/images/search_red.png",package: ExternalAssetsPackageKey.BASE,
                        width: 20, color: GetConfig.getColor(theme)),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width - 180,
                    // color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: TextField(
                        controller: _controller,
                        autofocus: false,
                        focusNode: _focusNode,
                        style: TextStyle(fontSize: 16.0, color: Colors.black),
                        decoration: new InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.only(top: -15))),
                  )
                ],
              )),
          actions: <Widget>[
            Align(
                child: Padding(
              padding: EdgeInsets.only(right: 8),
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    if (this._controller.text.isEmpty) {
                      pageData = tmpData;
                    } else {
//                          pageData = tmpData.where((f)=>f.children..indexOf(this._controller.text) != -1).toList();
                      pageData = [];
                      tmpData.forEach((f) {
                        ContractInfo _contractInfo = ContractInfo.fromParams(
                            id: f.id, name: f.name, depId: f.depId);
                        _contractInfo.children = f.children != null &&
                                f.children.length > 0
                            ? f.children
                                .where((d) =>
                                    d.label.indexOf(this._controller.text) !=
                                    -1)
                                .toList()
                            : List();
                        pageData.add(_contractInfo);
                      });
                    }
                  });
                },
                child: Text(
                  "搜索",
                  style: TextStyle(
                      color: GetConfig.getColor(theme), fontSize: 16.0),
                ),
              ),
            ))
          ],
        ),
        body: ModalProgressHUD(
          child: Container(
            color: Colors.white,
            child: EasyRefresh(
              enableControlFinishRefresh: false,
              enableControlFinishLoad: true,
              controller: _controllers,
              footer: MaterialFooter(),
              header: MaterialHeader(),
              child: new ListView.builder(
                //ListView的Item
                itemCount: 1,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                      children: pageData.map((data) {
                    return Column(
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          color: Colors.white,
                          height: 40,
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.only(left: 15),
                          child: Row(
                            children: <Widget>[
                              Text(
                                data.name,
                                style: TextStyle(
                                    color: Color.fromRGBO(153, 153, 153, 1)),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          color: Colors.grey[100],
                          height: 1,
                        ),
                        Column(
                          children: data.children.map((child) {
                            return Column(
                              children: <Widget>[
                                new Container(
                                    color: Colors.white,
                                    height: 50.0,
                                    margin: EdgeInsets.only(
                                        top: 10, left: 10, right: 10),
                                    child: new ListTile(
                                        isThreeLine: false,
                                        dense: false,
                                        subtitle: new Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: <Widget>[
                                            new CircleAvatar(
                                                child: Text(child.label
                                                    .substring(0, 1))),
                                            Padding(
                                              padding:
                                                  EdgeInsets.only(right: 5),
                                            ),
                                            new Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.center,
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              children: <Widget>[
                                                Padding(
                                                  padding:
                                                      EdgeInsets.only(top: 5),
                                                ),
                                                new Text(
                                                  child.label,
                                                  style: new TextStyle(
                                                      fontSize: 17.0,
                                                      fontWeight:
                                                          FontWeight.w500),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
//                                          trailing: new Icon(Icons.keyboard_arrow_right),
                                        onTap: () {
                                          Navigator.pop(
                                              context,
                                              NameValue2(
                                                  child.label,
                                                  num.tryParse(child.id),
                                                  num.parse(child.depId)));
                                        })),
                                Divider(
                                  height: 1,
                                ),
                              ],
                            );
                          }).toList(),
                        )
                      ],
                    );
                  }).toList());
                },
              ),
              onRefresh: () async {
                await new Future.delayed(const Duration(seconds: 1), () {
                  setState(() {
//                  pageIndex = 1;
//                  initData = [];
                  });
//                getData();
                });
              },
              onLoad: () async {
                await new Future.delayed(const Duration(seconds: 1), () {
                  if (hasNext) {
                    _controllers.finishLoad(success: true, noMore: true);
                    // setState(() {
                    //   pageIndex = pageIndex + 1;
                    // });
                    // getData().then(_controllers.resetLoadState());
                  }
                });
              },
            ),
          ),
          inAsyncCall: isAnimating,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: CircularProgressIndicator(),
//          content: '加载中...',
        ));
  }

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

    getData();

    initConfig();
  }

  getData() async {
    await getContractInfo('').then((data) {
      setState(() {
        pageData = data;
        tmpData = data;
      });
    });
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme =
            preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }
}
