import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/utils/GetConfig.dart';
import 'package:jcs_airport/view/Home/iot_monitor.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/viewmodel/facility_filter.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'FilterPage.dart';
/// 物联设施
class FixedMemu extends StatefulWidget {
  const FixedMemu({Key key}) : super(key: key);

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

class _FixedMemuState extends State<FixedMemu> {
  GlobalKey globalKey2 = GlobalKey();
  ScrollController scrollController = ScrollController();
  Map<String, dynamic> selectedData = <String, dynamic>{};
  FacilityFilter facilityFilter = FacilityFilter();
  final EasyRefreshController _controllers = EasyRefreshController();

  List<FacilityFilter> initData = [];

  // 当前页码
  int pageIndex = 1;

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

  // 分页所需控件
  bool isAnimating = false;

  String theme = '';

  List<dynamic> buildList = [
    {'title': '全部', 'id': null, 'key': 'warehouseStructureName'},
  ];
  List<Map<String, dynamic>> STATUS = [
    {'title': '全部', 'id': 'all', 'key': 'status'},
    {'title': '正常', 'id': '0', 'key': 'status'},
    {'title': '异常', 'id': '1', 'key': 'status'},
  ];
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  var data = [
    {'color': Colors.white, 'title': '火灾报警系统报修', 'content': '我是内容'},
  ];
  int buildListIndex = 0;
  int statusIndex = 0;
/// 图片服务器前缀
  String imagePrefix = '';

  DropdownMenu buildDropdownMenu() {
    return DropdownMenu(maxMenuHeight: kDropdownMenuItemHeight * 10, blur: 0.0, menus: [
      DropdownMenuBuilder(
          builder: (BuildContext context) {
            return DropdownListMenu(
                selectedIndex: buildListIndex,
                data: buildList,
                itemBuilder: (BuildContext context, dynamic data, bool selected) {
                  return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(children: <Widget>[
                        Expanded(
                            child: Text(
                          defaultGetItemLabel(data['title']),
                          textAlign: TextAlign.center,
                          style: selected
                              ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                              : const TextStyle(fontSize: 14.0),
                        ))
                      ]));
                });
          },
          height: kDropdownMenuItemHeight * buildList.length),
      DropdownMenuBuilder(
          builder: (BuildContext context) {
            return DropdownListMenu(
              selectedIndex: statusIndex,
              data: STATUS,
              itemBuilder: (BuildContext context, dynamic data, bool selected) {
                return Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            defaultGetItemLabel(data),
                            textAlign: TextAlign.center,
                            style: selected
                                ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                : const TextStyle(fontSize: 14.0),
                          ),
                        ),
                      ],
                    ));
              },
            );
          },
          height: kDropdownMenuItemHeight * STATUS.length),
      DropdownMenuBuilder(
          builder: (BuildContext context) {
            return DropdownListMenu(
              selectedIndex: 0,
              data: STATUS,
              itemBuilder: (BuildContext context, dynamic data, bool selected) {
                return Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            defaultGetItemLabel(data),
                            textAlign: TextAlign.center,
                            style: selected
                                ? TextStyle(fontSize: 14.0, color: GetConfig.getColor(theme), fontWeight: FontWeight.w400)
                                : const TextStyle(fontSize: 14.0),
                          ),
                        ),
                      ],
                    ));
              },
            );
          },
          height: kDropdownMenuItemHeight * STATUS.length)
    ]);
  }

  List<Widget> _buildFacilitieItem(FacilityFilter item) {
    List<Widget> widgetList = [];
    widgetList.addAll([
      Row(
        children: [
          Expanded(
            flex: 3,
            child: Text(item.fireEquipmentName ?? ''),
          ),
          Expanded(
              flex: 1,
              child: Text(
                item.status,
                style: const TextStyle(color: Colors.red),
              )),
        ],
      ),
      const SizedBox(
        height: 5,
      ),
      Row(
        children: [
          const Text('编号：'),
          const SizedBox(
            width: 5,
          ),
          Text(item.fireEquipmentCode ?? ''),
        ],
      ),
      const SizedBox(
        height: 5,
      ),
      Row(
        
        children: [
          const Text('位置：'),
          const SizedBox(
            width: 5,
          ),

          Expanded(
            child: Text(
             item.warehouseStructureName ?? '',
             softWrap: true
          // overflow: TextOverflow.ellipsis,
        ))
       
        ],
      )
    ]);
    return widgetList;
  }


                                      


  @override
  void initState() {
    super.initState();
     APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imagePrefix = value;
      });
    });
    getInitInfo();

  }

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      }
    }).then((data) {
      PlatformMenu platformMenu = Get.arguments;
      if (platformMenu != null && platformMenu.frontComponent == IotMonitor.iotMonitorIotWarning) {
        setState(() {
          selectedData['status'] = '1';
        });
      }
      loadData();
    });
    loadBuild();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          if (menuIndex == 0) {
            selectedData[data['key']] = data['title'];
            buildListIndex = index;
          } else if (menuIndex == 1) {
            selectedData[data['key']] = data['id'];
            statusIndex = index;
          }
          setState(() {});
          print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$selectedData');
          initData.clear();
          resetLoadData(facilityFilter);
        },
        child: Column(
          children: <Widget>[
            Expanded(
                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());
                    }),
                    pinned: true,
                    floating: true,
                  )
                ]),
                Padding(
                    padding: const EdgeInsets.only(top: 46.0),
                    child: Column(
                      children: <Widget>[
                        Expanded(
                            child: Stack(
                          children: <Widget>[
                            Center(
                                child: initData.isNotEmpty
                                    ? EasyRefresh(
                                        controller: _controllers,
                                        footer: MaterialFooter(),
                                        header: MaterialHeader(),
                                        child: ListView.builder(
                                          itemCount: initData.length,
                                          shrinkWrap: true,
                                          itemBuilder: (BuildContext context, int index) {
                                            if (initData.isEmpty) {
                                              return null;
                                            }
                                            var item = initData[index];
                                            ListViewItemModel listViewItemModel =
                                                ListViewItemModel(hasTitle: false, hasState: false);
                                            return ListViewItem(
                                              listViewItemModel: listViewItemModel,
                                              contentWidget: Padding(
                                                padding: const EdgeInsets.all(5.0),
                                                child: InkWell(
                                                  onTap: () {
                                                    Get.toNamed(JCSRoutes.iotFacilityDetail, arguments: item);
                                                  },
                                                  child: Column(
                                                    children: [
                                                      Row(
                                                        children: [
                                                          Expanded(
                                                            flex: 2,
                                                            child: item.eqimg != null
                                                                ? Image.network(
                                                                   Utils.completeUrl(imagePrefix, item.eqimg),
                                                                    width: 60,
                                                                    height: 60,
                                                                    errorBuilder: ( BuildContext context,Object error,StackTrace stackTrace){
                                                                      return Image.asset(
                                                                    'assets/images/no_data.png',
                                                                    width: 60,
                                                                    height: 60,
                                                                  );
                                                                    },
                                                                  )
                                                                : Image.asset(
                                                                    'assets/images/no_data.png',
                                                                    width: 60,
                                                                    height: 60,
                                                                  ),
                                                          ),
                                                          Expanded(
                                                              flex: 7,
                                                              child: Column(
                                                                children: _buildFacilitieItem(item),
                                                              )),
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            );
                                          },
                                        ),
                                        onRefresh: () async {
                                          setState(() {
                                            pageIndex = 1;
                                            initData.clear();
                                          });
                                          _controllers.resetLoadState();
                                          loadData();
                                          /* await Future.delayed(const Duration(seconds: 1), () {
                                  setState(() {
                                    pageIndex = 1;
                                    initData = [];
                                  });
                                  _controllers.resetLoadState();
                                  loadData();
                                });*/
                                        },
                                        onLoad: () async {
                                          if (hasNext) {
                                            setState(() {
                                              pageIndex = pageIndex + 1;
                                            });
                                            loadData();
                                          }
                                          /* await Future.delayed(const Duration(seconds: 1), () {
                                  if (hasNext) {
                                    setState(() {
                                      pageIndex = pageIndex + 1;
                                    });
                                    loadData();
                                  }
                                });*/
                                        },
                                      )
                                    : const EmptyData()),
                            buildDropdownMenu()
                          ],
                        ))
                      ],
                    )),
              ],
            ))
          ],
        ));
  }

  DropdownHeader buildDropdownHeader() {
    PlatformMenu platformMenu = Get.arguments;
    if (platformMenu != null && platformMenu.frontComponent == IotMonitor.iotMonitorIotWarning) {
      statusIndex = 2;
    }
    return DropdownHeader(
      onTap: _onTapHead,
      fontSize: 13,
      titles: [buildList[buildListIndex]['title'], STATUS[statusIndex]['title'], '筛选'],
    );
  }

  Future<void> loadData() async {
    _searchData(facilityFilter);
  }

  Future<void> loadBuild() async {
    List data = await API.getBuildingTree();
    if (initData != null) {
      setState(() {
        var temp = data[0]['children'];
        temp.forEach((element) {
          dynamic item = {};
          item['title'] = element['instanceName'] ?? '';
          item['id'] = element['instanceId'] ?? '';
          item['key'] = 'warehouseStructureName';
          buildList.add(item);
        });
      });
    }
  }

  Future<void> resetLoadData(facilityFilter) async {
    pageIndex = 1;
    initData.clear();
    _searchData(facilityFilter);
  }

  Future<void> _searchData(FacilityFilter facilityFilter) async {
    setState(() {
      isAnimating = true;
    });

    dynamic query = {
      'pageNum': pageIndex,
      'pageSize': 20,
      'status': selectedData['status'],
      'fireEquipmentCode': facilityFilter.fireEquipmentCode ?? '',
      'fireEquipmentName': facilityFilter.fireEquipmentName ?? '',
      'fireFightingSystem': facilityFilter.fireFightingSystem ?? '',
      'warehouseStructureName': selectedData['warehouseStructureName']
    };

    var data = await API.getIOTEquipmentTree(query);
    if (initData != null) {
      setState(() {
        if (data != null && data['records'].length > 0) {
          for (final dynamic p in data['records']) {
            initData.add(FacilityFilter.fromJson2(p));
          }
          isAnimating = false;
          if ((int.parse(data['total'])/int.parse(data['size'])- int.parse(data['current'])) > 0) {
            hasNext = true;
          }
        }
      });
    }
  }

  void _onTapHead(int index) {
    RenderObject renderObject = globalKey2.currentContext.findRenderObject();
    DropdownMenuController controller = DefaultDropdownMenuController.of(globalKey2.currentContext);
    if (index == 2) {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return FilterPage(facilityFilter, callback: (val) => resetLoadData(val));
        }));
      });
    } else {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        controller.show(index);
      });
    }
  }
}
