import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/Home/iot_monitor.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/viewmodel/alarm_info.dart';
import 'package:pull_to_refresh/pull_to_refresh.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 RefreshController refreshController = RefreshController();
  Map<String, dynamic> selectedData = <String, dynamic>{};
  AlarmInfo alarmInfo = AlarmInfo();
  List<AlarmInfo> baseInfoData = [];

  // 当前页码
  int pageIndex = 1;

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

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

          if (menuIndex == 2) {
            alarmInfo.type = 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.type != null ? 
                                                  item.type =='故障'? Colors.yellow:
                                                  item.type =='屏蔽'? Colors.blue:
                                                  item.type =='火警'? Colors.red:
                                                  Colors.yellow:Colors.white,

                                                  title: '${item.fireEquipmentName}${item.type}');
                                              return ListViewItem(
                                                  listViewItemModel: listViewItemModel,
                                                  contentWidget: Padding(
                                                      padding: const EdgeInsets.all(5.0),
                                                      child: InkWell(
                                                          onTap: () async {
                                                            /// 列表Item点击查看详情
                                                            await Get.toNamed(JCSRoutes.alarmInfoDetail,
                                                                arguments: item.toJson());
                                                            onRefresh();
                                                          },
                                                          child: Column(children: [
                                                            Row(children: [
                                                              const Text('设备：'),
                                                              const SizedBox(
                                                                width: 5,
                                                              ),
                                                              Expanded(flex: 3, child: Text(item.fireEquipmentName)),
                                                              Expanded(
                                                                  child:
                                                                      Text(item.type, style: const TextStyle(color: Colors.red)))
                                                            ]),
                                                            const SizedBox(
                                                              height: 5,
                                                            ),
                                                            Row(
                                                              children: [
                                                                const Text('位置：'),
                                                                const SizedBox(
                                                                  width: 5,
                                                                ),
                                                                Expanded(child: Text(item.warehouseStructureName)),
                                                              ],
                                                            ),
                                                            const SizedBox(
                                                              height: 5,
                                                            ),
                                                            Row(children: [
                                                              const Text('时间：'),
                                                              const SizedBox(
                                                                width: 5,
                                                              ),
                                                              Expanded(flex: 3, child: Text(item.createDate)),
                                                              Expanded(
                                                                  child: Text(
                                                                item.isFirm == 'yes' ? '已处理' : '未处理',
                                                                style: const TextStyle(color: Colors.blue),
                                                              ))
                                                            ])
                                                          ]))));
                                            }),
                                        onRefresh: () {
                                          onRefresh();
                                        },
                                        onLoading: () {
                                          onLoading();
                                        },
                                      )
                                    : const EmptyData()),
                            buildDropdownMenu()
                          ],
                        ))
                      ],
                    )),
              ],
            ))
          ],
        ));
  }

  void onLoading() {
    if (hasNext) {
      setState(() {
        pageIndex++;
      });
      _loadMore();
    } else {
      refreshController.loadNoData();
    }
  }

  void onRefresh() {
    setState(() {
      pageIndex = 1;
      baseInfoData = [];
    });
    _getData();
  }

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

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

    if (alarmInfo.fireEquipmentCode != null) {
      query['fireEquipmentCode'] = alarmInfo.fireEquipmentCode;
    }

    if (alarmInfo.fireEquipmentName != null) {
      query['fireEquipmentName'] = alarmInfo.fireEquipmentName;
    }

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

    if (alarmInfo.isFirm != null) {
      query['isFirm'] = alarmInfo.isFirm.toString();
    }

    if (alarmInfo.type != null) {
      query['type'] = alarmInfo.type;
    }

    if (alarmInfo.confirmType != null) {
      query['confirmType'] = alarmInfo.confirmType;
    }

    if (alarmInfo.confirmUserName != null) {
      query['confirmUserName'] = alarmInfo.confirmUserName;
    }

    if (alarmInfo.createDate != null) {
      query['createDate'] = alarmInfo.createDate;
    }
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中,请稍后...');
      var data = await API.getAlarmPage(query);
      Get.back();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      if (baseInfoData != null) {
        setState(() {
          if (data != null && data['records'].length > 0) {
            for (dynamic p in data['records']) {
              baseInfoData.add(AlarmInfo.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 = [];
      alarmInfo = val;
    });
    _loadMore();
  }

  @override
  void initState() {
    super.initState();
    PlatformMenu platformMenu = Get.arguments;
   
    if (platformMenu != null) {
      String type = platformMenu.frontComponent;

      if(type=='jq'){
      alarmInfo.fireEquipmentCode=platformMenu.icon;
      }else{
      int i = 0;
      for (i = 0; i < ALARM_TYPE.length; i++) {
        if (type == ALARM_TYPE[i]['id']) {
          alarmInfo.type = type;
        }
      }
      if (alarmInfo.type == null) {
        for (i = 0; i < PROCESS_STATUS.length; i++) {
          if (type == PROCESS_STATUS[i]['id']) {
            alarmInfo.isFirm = type;
          }
        }
      }
      }

      //处理从首页统计跳转进来的情况
      if (platformMenu.frontComponent == IotMonitor.iotMonitorFireControlWarning) {
        alarmInfo.type = 'FIREALARM';
        alarmInfo.isFirm = 'no';
      } else if (platformMenu.frontComponent == IotMonitor.iotMonitorMalfunctionWarning) {
        alarmInfo.type = 'BREAKDOWN';
        alarmInfo.isFirm = 'no';
      }
    }
    _getData();
  }

  @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(alarmInfo, callback: (val) => _getNewData(val));
        }));
      });
    } else {
      scrollController
          .animateTo(scrollController.offset + renderObject.semanticBounds.height,
              duration: const Duration(milliseconds: 150), curve: Curves.ease)
          .whenComplete(() {
        controller.show(index);
      });
    }
  }
}
