import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:amos_iot_login_tpl/utils/check.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/view/Home/iot_monitor.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/viewmodel/monitor_event.dart';
import './config.dart';
import './create_menu.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();

  //final EasyRefreshController _controllers = EasyRefreshController();
  final RefreshController refreshController = RefreshController();
  Map<String, dynamic> selectedData = <String, dynamic>{};
  MonitorEvent monitorEvent = MonitorEvent();
  List<MonitorEvent> baseInfoData = [];

  // 当前页码
  int pageIndex = 1;

  // 是否有下一页
  bool hasNext = true;
  var data = [
    {'color': Colors.yellow, 'title': '火灾报警系统报修', 'content': '我是内容'},
  ];
  String theme = '';

  Future<void> getInitInfo() async {
    await SharedPreferences.getInstance().then((data) {
      if (data != null) {
        theme = data.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      }
    }).then((data) {});
  }

  /// 构建列表
  Widget buildFixHeaderDropdownMenu() {
    return DefaultDropdownMenuController(
        onSelected: ({int menuIndex, int index, int subIndex, dynamic data}) {
          /// 列表条件查询选择回调
          selectedData[data['key']] = data['id'];
          if (menuIndex == 0) {
            monitorEvent = getStartDateAndEndDate(monitorEvent, data['id']);
          }
          if (menuIndex == 1) {
            monitorEvent.eventState = data['id'];
          }

          if (menuIndex == 2) {
            monitorEvent.eventType = data['id'];
          }
          _getData();
        },
        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(onTap: _onTapHead));
                    }),
                    pinned: true,
                    floating: true,
                  )
                ]),
                Padding(
                    padding: const EdgeInsets.only(top: 46.0),
                    child: Column(
                      children: <Widget>[
                        Expanded(
                            child: Stack(
                          children: <Widget>[
                            Center(
                                child: baseInfoData.isNotEmpty
                                    ? SmartRefresher(
                                        controller: refreshController,
                                        enablePullDown: true,
                                        enablePullUp: true,
                                        header: const WaterDropMaterialHeader(),
                                        footer: const ClassicFooter(),
                                        child: ListView.builder(
                                            itemCount: baseInfoData.length,
                                            shrinkWrap: true,
                                            itemBuilder: (BuildContext context, int index) {
                                              if (baseInfoData.isEmpty) {
                                                return null;
                                              }
                                              var item = baseInfoData[index];
                                              ListViewItemModel listViewItemModel = ListViewItemModel(
                                                  hasState: true,
                                                  stateColor: item.eventType == null ? Colors.yellow : Colors.red,
                                                  title: '${item.videoName}');
                                              return ListViewItem(
                                                  listViewItemModel: listViewItemModel,
                                                  contentWidget: Padding(
                                                      padding: const EdgeInsets.all(5.0),
                                                      child: InkWell(
                                                          onTap: () {
                                                            /// 列表Item点击查看详情
                                                            Get.toNamed(JCSRoutes.monitorEventDetail, arguments: item);
                                                          },
                                                          child: Column(children: [
                                                            Row(children: [
                                                              const Text('设备：'),
                                                              const SizedBox(
                                                                width: 5,
                                                              ),
                                                              Expanded(
                                                                  flex: 3,
                                                                  child: Text(
                                                                    item.videoName,
                                                                    overflow: TextOverflow.ellipsis,
                                                                  )),
                                                              Expanded(
                                                                  child: Text(item.eventType,
                                                                      style: const TextStyle(color: Colors.red)))
                                                            ]),
                                                            const SizedBox(
                                                              height: 5,
                                                            ),
                                                            Row(
                                                              children: [
                                                                const Text('位置：'),
                                                                const SizedBox(
                                                                  width: 5,
                                                                ),
                                                                Expanded(child: Text(textContent(item.videoPosition))),
                                                              ],
                                                            ),
                                                            const SizedBox(
                                                              height: 5,
                                                            ),
                                                            Row(children: [
                                                              const Text('时间：'),
                                                              const SizedBox(
                                                                width: 5,
                                                              ),
                                                              Expanded(flex: 3, child: Text(item.createDate)),
                                                              Expanded(
                                                                  child: Text(
                                                                item.eventState == '已处理' ? '已处理' : '未处理',
                                                                style: const TextStyle(color: Colors.blue),
                                                              ))
                                                            ])
                                                          ]))));
                                            }),
                                        onRefresh: () async {
                                          setState(() {
                                            pageIndex = 1;
                                            baseInfoData.clear();
                                          });
                                          _getData();
                                        },
                                        onLoading: () async {
                                          if (hasNext) {
                                            setState(() {
                                              pageIndex++;
                                            });
                                            _loadMore();
                                          } else {
                                            refreshController.loadNoData();
                                          }
                                        },
                                      )
                                    : const EmptyData()),
                            buildDropdownMenu(theme)
                          ],
                        ))
                      ],
                    )),
              ],
            ))
          ],
        ));
  }

  Future<void> _loadMore() async {
    Map<String, dynamic> query = {'current': pageIndex, 'size': 10};

    if (monitorEvent.startDate != null) {
      query['startDate'] = monitorEvent.startDate;
    }

    if (monitorEvent.videoName != null) {
      query['videoName'] = monitorEvent.videoName;
    }

    if (monitorEvent.endDate != null) {
      query['endDate'] = monitorEvent.endDate;
    }

    if (monitorEvent.eventState != null) {
      query['eventState'] = monitorEvent.eventState;
    }

    if (monitorEvent.eventType != null) {
      query['eventType'] = monitorEvent.eventType;
    }

    if (monitorEvent.createDate != null) {
      query['createDate'] = monitorEvent.createDate;
    }
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.getMonitorEventPage(query);
      Get.back();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      if (baseInfoData != null) {
        setState(() {
          if (data != null && data['records'].length > 0) {
            for (final dynamic p in data['records']) {
              baseInfoData.add(MonitorEvent.fromJson(p));
            }
            if (data['current'] == data['pages']) {
              hasNext = false;
            }
          }
        });
      }
    });
  }

  /// 查询列表数据
  Future<void> _getData() async {
    setState(() {
      pageIndex = 1;
      baseInfoData = [];
    });
    _loadMore();
  }

  Future<void> _getNewData(val) async {
    setState(() {
      pageIndex = 1;
      baseInfoData = [];
      monitorEvent = val;
    });
    _loadMore();
  }

  @override
  void initState() {
    super.initState();
    PlatformMenu platformMenu = Get.arguments;
    if (platformMenu != null) {
      String type = platformMenu.frontComponent;
      int i = 0;
      for (i = 0; i < EVENT_TYPE.length; i++) {
        if (type == EVENT_TYPE[i]['id']) {
          monitorEvent.eventType = type;
        }
      }

      if (monitorEvent.eventType == null) {
        for (i = 0; i < PROCESS_STATUS.length; i++) {
          if (type == PROCESS_STATUS[i]['id']) {
            monitorEvent.eventState = type;
          }
        }
      }
      if (platformMenu.frontComponent == IotMonitor.onGuardWarning) {
        setState(() {
          monitorEvent.eventState = '未处理';
        });
      }
    }

    getInitInfo();
    _getData();
    print(Get.arguments);
  }

  @override
  Widget build(BuildContext context) {
    return buildFixHeaderDropdownMenu();
  }

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