import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/CheckItem.dart';
import '../../model/ExtClass.dart';
import '../../services/catalog_list_services.dart';
import '../../services/check_item_services.dart';

class CheckItemList extends StatefulWidget {
  // 选择数据
  List<CheckItem> selectedData;

  CheckItemList(this.selectedData);

  @override
  _CheckItemListState createState() => _CheckItemListState(this.selectedData);
}

class _CheckItemListState extends State<CheckItemList>
    with AutomaticKeepAliveClientMixin {
  _CheckItemListState(this.selectedData);

  List<CheckItem> selectedData;

  // 当前页码
  int pageIndex = 0;

  bool isAnimating = false;

  int totalElements = 0;

  // 是否有下一页
  bool hasNext = true;

  final EasyRefreshController _controllers = EasyRefreshController();
  final TextEditingController _searchController =  TextEditingController();

  // 页面数据
  List<CheckItem> listData =  [];

  // 模糊搜索文字
  String keywords = "";

  // 检查项类型
  String itemType = "";

  // 检查项分类id
  int itemCagetoryId = 0;

  String titleType = '检查项类型';
  String titleClass = '检查项分类';

  static const int TYPE_INDEX = 0;

  static const List<Map<String, dynamic>> TITLE_TYPE_CONTENT = [
    {"title": "所有", "id": ""},
    {"title": "选择", "id": "选择"},
    {"title": "文本", "id": "文本"},
    {"title": "数字", "id": "数字"},
  ];

  // 扩展分类数据
  List<ExtClass> extClassList = [];

  String theme = "";

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    initExtClassList();
    initConfig();
  }

  initExtClassList() async {
    await queryCatalogList().then((data) {
      setState(() {
        this.extClassList = data;
        this.extClassList.insert(0, ExtClass({"id": 0, "name": "所有"}));
      });
      // 查询列表数据
      initData();
    });
  }

  initData() async {
    await queryItemByPage(
            this.keywords, this.itemType, this.itemCagetoryId, this.pageIndex)
        .then((data) {
      setState(() {
        if (null != data) {
          for (var p in data.content) {
            CheckItem item = CheckItem.fromJson(p);
            for (var i in selectedData) {
              if (item.id == i.id) {
                item.isChecked = true;
                break;
              }
            }
            listData.add(item);
          }
        }
        // 总条数
        totalElements = data.totalElements;
        isAnimating = false;
        // 是否有下一页
        hasNext = !data.last;
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    return Scaffold(
      backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
      appBar: AppBar(
        title: const Text(
          '检查项列表',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        actions: <Widget>[
          FlatButton(
            child:  const Text(
              '确定',
              style: TextStyle(fontSize: 16),
            ),
            textColor: Colors.white,
            // color: Colors.white,
            onPressed: () {
              setState(() {
                selectedData.clear();
                for (var i in listData) {
                  if (i.isChecked) {
                    selectedData.add(i);
                  }
                }
              });
              Navigator.pop(context, selectedData);
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        child: _getWidget(),
        inAsyncCall: isAnimating,
        opacity: 0.2,
        progressIndicator: const CircularProgressIndicator(),
      ),
    );
  }

  Widget _getWidget() {
    return buildInnerListHeaderDropdownMenu();
  }

  ScrollController scrollController =  ScrollController();
  GlobalKey globalKey2 =  GlobalKey();

  Widget buildInnerListHeaderDropdownMenu() {
    return  DefaultDropdownMenuController(
        // 下拉框选择事件
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          if (menuIndex == 0) {
            setState(() {
              itemType = data["id"] as String;
              pageIndex = 0;
              listData = [];
            });
            initData();
          } else if (menuIndex == 1) {
            setState(() {
              itemCagetoryId = data.id as int;
              titleClass = data.name.toString();
              pageIndex = 0;
              listData = [];
            });
            initData();
          }
        },
        child:  Stack(
          children: <Widget>[
             CustomScrollView(
                controller: scrollController,
                slivers: <Widget>[
                   SliverList(
                      key: globalKey2,
                      delegate:  SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                        return  Container(
                          color: Colors.black26,
                        );
                      }, childCount: 1)),
                   SliverPersistentHeader(
                    delegate:  DropdownSliverChildBuilderDelegate(
                        builder: (BuildContext context) {
                      return  Container(
                          color: Colors.white,
                          child: buildDropdownHeader(onTap: _onTapHead));
                    }),
                    pinned: true,
                    floating: true,
                  ),
                   SliverList(
                      delegate:  SliverChildBuilderDelegate(
                          (BuildContext context, int index) {},
                          childCount: 10)),
                ]),
             Padding(
                padding:  const EdgeInsets.only(top: 46.0),
                child:  Stack(children: <Widget>[
                  // Padding(padding:  EdgeInsets.only(top: 46.0)),
                  Container(
                      height: 45,
                      width: double.infinity,
                      margin: const EdgeInsets.only(top: 3, left: 10, right: 10),
                      decoration:  BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius:
                             const BorderRadius.all(Radius.circular(6.0)),
                      ),
                      child:  Container(
                        padding: const EdgeInsets.only(left: 5),
                        child: TextField(
                          controller: _searchController,
                          autofocus: false,
                          style: const TextStyle(fontSize: 18.0, color: Colors.black),
                          decoration:  InputDecoration(
                              suffixIcon: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      pageIndex = 0;
                                      listData = [];
                                    });
                                    initData();
                                  },
                                  child:  const Icon(
                                    Icons.search,
                                    color: Colors.black26,
                                  )),
                              border: InputBorder.none,
                              hintText: "已有检索项" +
                                  this.totalElements.toString() +
                                  "个"),
                          onChanged: (val) {
                            setState(() {
                              this.keywords = val;
                            });
                          },
                        ),
                      )),
                  Container(
                    child: EasyRefresh(
                      enableControlFinishRefresh: false,
                      enableControlFinishLoad: true,
                      controller: _controllers,
                      footer: MaterialFooter(),
                      header: MaterialHeader(),
                      child:  ListView.builder(
                        //ListView的Item
                        itemCount: 1,
                        itemBuilder: (BuildContext context, int index) {
                          return Column(
                            children: <Widget>[
                              Column(
                                children: listData.map((f) {
                                  return Card(
                                    elevation: 0.2,
                                    margin: const EdgeInsets.only(
                                        top: 5, left: 10, right: 10),
                                    child:  Container(
                                        child: Row(
                                      children: <Widget>[
                                        Container(
                                          padding: const EdgeInsets.only(
                                              left: 10, top: 5, right: 10),
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Container(
                                                width: MediaQuery.of(context)
                                                        .size
                                                        .width -
                                                    40,
                                                child:  Text(
                                                  f.name,
                                                  style:  const TextStyle(
                                                      fontSize: 16.0,
                                                      fontWeight:
                                                          FontWeight.w500),
                                                  maxLines: 10,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                              const Padding(
                                                padding:
                                                    EdgeInsets.only(top: 1),
                                              ),
                                              Row(
                                                children: <Widget>[
                                                  Text(f.itemType + "检查项"),
                                                  const Padding(
                                                    padding: EdgeInsets.only(
                                                        left: 5),
                                                  ),
                                                  Text(f.isMust == "是"
                                                      ? "必填"
                                                      : "非必填"),
                                                  const Padding(
                                                    padding: EdgeInsets.only(
                                                        left: 50),
                                                  ),
                                                   Checkbox(
                                                    value: f.isChecked,
                                                    activeColor: Theme.of(context).primaryColor,
                                                    onChanged: (val) {
                                                      setState(() {
                                                        f.isChecked = val;
                                                      });
                                                      print(listData);
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                        )
                                      ],
                                    )),
                                  );
                                }).toList(),
                              )
                            ],
                          );
                        },
                      ),
                      onRefresh: () async {
                        await  Future.delayed(const Duration(seconds: 1),
                            () {
                          setState(() {
                            pageIndex = 0;
                            listData = [];
                          });
                          initData();
                        });
                      },
                      onLoad: () async {
                        await  Future.delayed(const Duration(seconds: 1),
                            () {
                          if (hasNext) {
                            setState(() {
                              pageIndex = pageIndex + 1;
                            });
                            initData();
                          }
                        });
                      },
                    ),
                    padding: EdgeInsets.only(top: 46),
                  ),
                  buildDropdownMenu(),
                ])),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller =
        DefaultDropdownMenuController.of(globalKey2.currentContext);
    // if(index == 1){
    //   setState(() {
    //     titleClass='12';
    //   });
    // }else {
    scrollController
        .animateTo(scrollController.offset + renderObject.semanticBounds.height,
            duration:  Duration(milliseconds: 150), curve: Curves.ease)
        .whenComplete(() {
      controller.show(index);
    });
    //  }
  }

  DropdownHeader buildDropdownHeader({DropdownMenuHeadTapCallback onTap}) {
    return  DropdownHeader(
      onTap: onTap,
      fontSize: 13,
      titles: [titleType, titleClass],
    );
  }

  DropdownMenu buildDropdownMenu() {
    return  DropdownMenu(
        maxMenuHeight: kDropdownMenuItemHeight * 10,
        blur: 0.0,
        menus: [
           DropdownMenuBuilder(
              builder: (BuildContext context) {
                return  DropdownListMenu(
                  selectedIndex: TYPE_INDEX,
                  data: TITLE_TYPE_CONTENT,
                  itemBuilder:
                      (BuildContext context, dynamic data, bool selected) {
                    return  Padding(
                        padding:  EdgeInsets.all(10.0),
                        child:  Row(
                          children: <Widget>[
                             Text(
                              defaultGetItemLabel(data),
                              style: selected
                                  ?  TextStyle(
                                      fontSize: 14.0,
                                      color: Theme.of(context).primaryColor,
                                      fontWeight: FontWeight.w400)
                                  :  TextStyle(fontSize: 14.0),
                            ),
                             Expanded(
                                child:  Align(
                              alignment: Alignment.centerRight,
                              child: selected
                                  ?  Icon(
                                      Icons.check,
                                      color: Theme.of(context).primaryColor,
                                    )
                                  : null,
                            )),
                          ],
                        ));
                  },
                );
              },
              height: kDropdownMenuItemHeight * TITLE_TYPE_CONTENT.length),
           DropdownMenuBuilder(
              builder: (BuildContext context) {
                return  DropdownListMenu(
                  selectedIndex: TYPE_INDEX,
                  data: extClassList,
                  itemBuilder:
                      (BuildContext context, dynamic data, bool selected) {
                    return  Padding(
                        padding:  EdgeInsets.all(10.0),
                        child:  Row(
                          children: <Widget>[
                             Text(
                              data.title,
                              style: selected
                                  ?  TextStyle(
                                      fontSize: 14.0,
                                      color: Theme.of(context).primaryColor,
                                      fontWeight: FontWeight.w400)
                                  :  TextStyle(fontSize: 14.0),
                            ),
                             Expanded(
                                child:  Align(
                              alignment: Alignment.centerRight,
                              child: selected
                                  ?  Icon(
                                      Icons.check,
                                      color: Theme.of(context).primaryColor,
                                    )
                                  : null,
                            )),
                          ],
                        ));
                  },
                );
              },
              height: kDropdownMenuItemHeight * extClassList.length),
        ]);
  }
}
