import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../consts/color.dart';
import '../../../consts/share_prefers_key_const.dart';
import '../../../model/CompanyInfo.dart';
import '../../../model/ContactInfo.dart';
import '../../../services/company_services.dart';
import '../../../widgets/loading_dialog.dart';
import 'contact_item.dart';

class ContactPage extends StatefulWidget {
  final String type;

  const ContactPage({this.type});

  @override
  _ContactPageState createState() => _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
  List<ContractInfo> pageData = [];
  List<ContractInfo> tmpData = [];
  CompanyInfos company;

  void getUserInfo() {
    SharedPreferences.getInstance().then((sp) {
      setState(() {
        var companyModel = sp.get(SharePrefersKey.companyModelKey);
        if (companyModel != null) {
          company = CompanyInfos.fromJson(json.decode(companyModel));
        }
        theme = sp.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
      getData();
    });
  }

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

  getData() async {
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    await getContractInfo('').then((data) {
      Navigator.of(context).pop();
      setState(() {
        pageData = data;
        tmpData = data;
      });
    });
  }

  final TextEditingController _controller = TextEditingController();
  String theme = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
        appBar: AppBar(
          elevation: 0.2,
          brightness: Brightness.light,
          title: Container(
            height: 30,
            width: MediaQuery.of(context).size.width - 120,
            padding: const EdgeInsets.only(bottom: 5),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: const BorderRadius.all(Radius.circular(25.0)),
            ),
            child: Row(
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.only(left: 5, right: 5, top: 6),
                  child: Icon(
                    Icons.search,
                    color: Theme.of(context).primaryColor,
                    size: 20,
                  ),
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 180,
                  child: TextField(
                      controller: _controller,
                      style: const TextStyle(fontSize: 16.0, color: Colors.black),
                      decoration:
                          const InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.only(top: -15))),
                )
              ],
            ),
          ),
          centerTitle: true,
          actions: <Widget>[
            Align(
                child: Padding(
              padding: const EdgeInsets.only(right: 8),
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    if (_controller.text.isEmpty) {
                      pageData = tmpData;
                    } else {
                      pageData = [];
                      tmpData.forEach((f) {
                        ContractInfo _contractInfo = ContractInfo.fromParams(id: f.id, name: f.name, depId: f.depId);
                        List<ChildInfo> conlist = [];
                        f.children.forEach((element) {
                          if (element.children.isNotEmpty) {
                            List<ChildInfo> elelist = [];
                            element.children.forEach((e) {
                              if (e.children.isNotEmpty) {
                                List<ChildInfo> elist = [];
                                e.children.forEach((s) {
                                  if (s.label.contains(_controller.text)) {
                                    elist.add(s);
                                  }
                                });
                                if (elist.isNotEmpty) {
                                  e.children = elist;
                                  elelist.add(e);
                                }
                              } else {
                                if (e.label.contains(_controller.text)) {
                                  elelist.add(e);
                                }
                              }
                            });
                            if (elelist.isNotEmpty) {
                              element.children = elelist;
                              conlist.add(element);
                            }
                          } else {
                            if (element.label.contains(_controller.text)) {
                              conlist.add(element);
                            }
                          }
                        });
                        _contractInfo.children = conlist;
                        _contractInfo.isOpen = true;
                        if (_contractInfo.children.isNotEmpty) {
                          pageData.add(_contractInfo);
                        }
                      });
                    }
                  });
                },
                child: const Text(
                  '搜索',
                ),
              ),
            ))
          ],
        ),
        body: SingleChildScrollView(
            child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.only(left: 15.0),
              height: 30.0,
              color: Colors.white,
              child: Row(
                children: <Widget>[
                  Text(
                    company == null ? '' : company.companyName,
                    style: const TextStyle(color: Colors.grey),
                  )
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(left: 15.0, right: 15.0),
              child: Divider(
                height: 0.5,
              ),
            ),
            Container(
              child: ExpansionPanelList(
                expansionCallback: (index, bool) {
                  setState(() {
                    pageData[index].isOpen = !pageData[index].isOpen;
                  });
                },
                children: pageData.map((e) {
                  return ExpansionPanel(
                      headerBuilder: (context, isExpanded) {
                        return ListTile(
                          title: Text(e.name + '(' + e.children.length.toString() + ')'),
                        );
                      },
                      body: ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: e.children.length,
                          shrinkWrap: true,
                          itemBuilder: (BuildContext context, int i) {
                            return Container(
                              color: Colors.white,
                              alignment: Alignment.centerLeft,
                              child: ContactItem(
                                type: widget.type,
                                contexts: context,
                                item: e.children[i],
                                res: e.isOpen,
                              ),
                            );
                          }),
                      isExpanded: e.isOpen);
                }).toList(),
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10.0),
            ),
            Container(),
          ],
        )));
  }
}
