import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.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/CheckPoint.dart';
import '../../model/name_value.dart';
import '../../services/check_point_service.dart';
import '../../services/route_list_services.dart';
import '../../view/CheckExecute/checkexec_spot_detail.dart';

class InspectionSpotScreen extends StatefulWidget {
  @override
  _InspectionSpotScreenState createState() => _InspectionSpotScreenState();
}

class _InspectionSpotScreenState extends State<InspectionSpotScreen> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  bool isAnimating = false;

  // 线路数据
  List<Map<String, dynamic>> routeList = [];

  // 当前选择的线路数据
  NameValue selectRoute = NameValue('全部',-1);

  // 根据线路查询点列表数据
  List<CheckPoint> pointList = [];

  // 当前页码
  int pageIndex = 0;

  // 每页条数
  int pageSize = 10;

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

  bool _isFooter = true;

  String theme = 'blue';
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final EasyRefreshController _controllers = EasyRefreshController();

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

  void getInitInfo() async {
    // 获取线路数据
    await getRouteList().then((data) {
      setState(() {
        data.forEach((f) {
          Map<String, dynamic> _map = {};
          _map['title'] = f.name;
          _map['id'] = f.value;
          routeList.add(_map);
        });
        Map<String, dynamic> _allMap = {};
        _allMap['title'] = '全部';
        _allMap['id'] = -1;
        routeList.insert(0, _allMap);

        if (null != data && data.isNotEmpty) {
          setState(() {
            selectRoute = NameValue('全部', -1); //data[0];
          });
          loadData();
        }
      });
    });
  }

  void loadData() async {
    setState(() {
      isAnimating = true;
    });
    // 根据routeid，查询点列表
    await queryPointPage(selectRoute.value, pageIndex, pageSize, keywords: _controller.text).then((data) {
      setState(() {
        for (dynamic p in data.content) {
          pointList.add(CheckPoint.fromJson(p));
        }

        hasNext = !data.last;
        _controllers.finishLoad(noMore: data.last);
        isAnimating = false;
      });
    });
  }

  void loadingBottomControl() {
    Future.delayed(const Duration(milliseconds: 1000), () {
      setState(() {
        _isFooter = false;
        Future.delayed(const Duration(milliseconds: 1000), () {
          setState(() {
            _isFooter = true;
          });
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (null == routeList || routeList.isEmpty) {
      return Scaffold(
          appBar: AppBar(
        title: Container(
            height: 30,
            width: MediaQuery.of(context).size.width - 130,
            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,
                  ),
                ),
                Container(
                  width: MediaQuery.of(context).size.width - 190,
                  child: TextField(
                      controller: _controller,
                      focusNode: _focusNode,
                      style: const TextStyle(
                        fontSize: 18.0,
                        color: Colors.black,
                      ),
                      decoration:
                          const InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.only(top: -15))),
                )
              ],
            )),
        actions: <Widget>[
          Align(
              child: Padding(
            padding: const EdgeInsets.only(right: 8),
            child: GestureDetector(
              onTap: () {},
              child: const Text(
                '搜索',
              ),
            ),
          ))
        ],
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ));
    }

    else{
      return Scaffold(
        appBar: AppBar(
          title: Container(
              height: 30,
              width: MediaQuery.of(context).size.width - 130,
              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,
                    ),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width - 190,
                    child: TextField(
                        controller: _controller,
                        focusNode: _focusNode,
                        style: const TextStyle(fontSize: 16.0, color: Colors.black),
                        decoration:
                        const InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.only(top: -15))),
                  )
                ],
              )),
          actions: <Widget>[
            Align(
                child: Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: GestureDetector(
                    onTap: () {
                      pageIndex = 0;
                      pointList = [];
                      loadData();
                    },
                    child: const Text(
                      '搜索',
                    ),
                  ),
                ))
          ],
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
        ),
        body: ModalProgressHUD(
          child: _getWidget(),
          inAsyncCall: isAnimating,
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ),
        resizeToAvoidBottomPadding: false,
      );
    }
  }

  Widget _getWidget() {
    return buildInnerListHeaderDropdownMenu();
  }

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

  Widget buildInnerListHeaderDropdownMenu() {
    return DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          setState(() {
            selectRoute.name = data['title'];
            selectRoute.value = data['id'];
            pageIndex = 0;
            pointList = [];
          });
          loadData();
        },
        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: routeList.length)),
            ]),
            Padding(
                padding: const EdgeInsets.only(top: 46.0),
                child: Stack(children: <Widget>[
                  Column(
                    children: <Widget>[
                      Expanded(
                          child: Container(
                        child: GestureDetector(
                          child: Center(
                            child: EasyRefresh(
                              enableControlFinishRefresh: false,
                              enableControlFinishLoad: true,
                              controller: _controllers,
                              footer: MaterialFooter(),
                              header: MaterialHeader(),
                              child: ListView.builder(
                                //ListView的Item
                                itemCount: pointList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    margin: const EdgeInsets.only(left: 15, right: 15),
                                    child: Card(
                                        elevation: 0.2,
                                        child: ListTile(
                                            isThreeLine: true,
                                            dense: false,
                                            subtitle: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text(
                                                  (index + 1).toString() + '.' + pointList[index].name,
                                                  style: const TextStyle(fontSize: 18.0, fontWeight: FontWeight.w600),
                                                ),
                                                const Padding(
                                                  padding: EdgeInsets.only(top: 5),
                                                ),
                                                Text(
                                                  '编号:' + pointList[index].pointNo,
                                                  style: const TextStyle(fontSize: 14.0, color: Colors.grey),
                                                ),
                                              ],
                                            ),
                                            trailing: Padding(
                                              child: Icon(
                                                Icons.keyboard_arrow_right,
                                                color: Theme.of(context).primaryColor,
                                              ),
                                              padding: const EdgeInsets.only(top: 15),
                                            ),
                                            onTap: () {
                                              Navigator.push(context, MaterialPageRoute(builder: (context) {
                                                return CheckExecSpotDetail(pointList[index].id, true);
                                              })).then((value) {
                                                setState(() {
                                                  pageIndex = 0;
                                                  pointList = [];
                                                });
                                                loadData();
                                              });
                                            })),
                                  );
                                },
                              ),
                              onRefresh: () async {
                                await Future.delayed(const Duration(seconds: 1), () {
                                  setState(() {
                                    pageIndex = 0;
                                    pointList = [];
                                  });
                                  _controllers.resetLoadState();
                                  loadData();
                                });
                              },
                              onLoad: () async {
                                await Future.delayed(const Duration(seconds: 1), () {
                                  if (hasNext) {
                                    setState(() {
                                      pageIndex = pageIndex + 1;
                                    });
                                    loadData();
                                  }
                                });
                              },
                            ),
                          ),
                        ),
                      ))
                    ],
                  ),
                  buildDropdownMenu(),
                ])),
          ],
        ));
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller = DefaultDropdownMenuController.of(globalKey2.currentContext);

    scrollController
        .animateTo(scrollController.offset + renderObject.semanticBounds.height,
            duration: const Duration(milliseconds: 150), curve: Curves.ease)
        .whenComplete(() {
      controller.show(index);
    });
  }

  static const int TYPE_INDEX = 0;

  DropdownHeader buildDropdownHeader({DropdownMenuHeadTapCallback onTap}) {
    return DropdownHeader(
      onTap: onTap,
      fontSize: 13,
      titles:  [selectRoute.name],
    );
  }

  DropdownMenu buildDropdownMenu() {
    return DropdownMenu(maxMenuHeight: kDropdownMenuItemHeight * 10, blur: 0.0, menus: [
      DropdownMenuBuilder(
          builder: (BuildContext context) {
            return DropdownListMenu(
              selectedIndex: TYPE_INDEX,
              data: routeList,
              itemBuilder: (BuildContext context, dynamic data, bool selected) {
                return Padding(
                    padding: const 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)
                              : const TextStyle(fontSize: 14.0),
                        ),
                        Expanded(
                            child: Align(
                          alignment: Alignment.centerRight,
                          child: selected
                              ? Icon(
                                  Icons.check,
                                  color: Theme.of(context).primaryColor,
                                )
                              : null,
                        )),
                      ],
                    ));
              },
            );
          },
          height: kDropdownMenuItemHeight * routeList.length),
    ]);
  }
}
