import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/services/api.dart';

///@Description     首页物联监测
///@author          helinlin
///@create          2021-10-29 9:44
class IotMonitor extends StatefulWidget {
  static String iotMonitorFireControlWarning = 'iotMonitorFireControlWarning';
  static String iotMonitorMalfunctionWarning = 'iotMonitorMalfunctionWarning';
  static String iotMonitorIotWarning = 'iotMonitorIotWarning';
  static String onGuardWarning = 'onGuardWarning';

  const IotMonitor({Key key}) : super(key: key);

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

class _IotMonitorState extends State<IotMonitor> {
  List countData = [
    {
      'type': '消防报警:',
      'image': 'assets/images/fire_warning.png',
      'count': 0,
      'firstRecord': {},
      'onClick': () {
        Get.toNamed(JCSRoutes.alarmInfo, arguments: PlatformMenu(frontComponent: IotMonitor.iotMonitorFireControlWarning));
      }
    },
    {
      'type': '故障告警:',
      'image': 'assets/images/fault_warning.png',
      'count': 0,
      'firstRecord': {},
      'onClick': () {
        Get.toNamed(JCSRoutes.alarmInfo, arguments: PlatformMenu(frontComponent: IotMonitor.iotMonitorMalfunctionWarning));
      }
    },
    {
      'type': '在岗监测:',
      'image': 'assets/images/iot_warning.png',
      'count': 0,
      'firstRecord': {},
      'onClick': () {
        Get.toNamed(JCSRoutes.monitorEvent, arguments: PlatformMenu(frontComponent: IotMonitor.onGuardWarning));
      }
    },
  ];

  @override
  void initState() {
    super.initState();
    //getCount();
    getFireAlarmFirstRecord();
    getFaultAlarmFirstRecord();
    getIotMonitorEventFirstRecord();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('物联监测'),
      ),
      body: Column(
        children: [
          ListView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int index) {
                return CommonCard(
                  child: InkWell(
                    onTap: countData[index]['onClick'],
                    child: Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Row(
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(right: 8.0),
                            child: Image.asset(
                              countData[index]['image'],
                              width: 45,
                            ),
                          ),
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Row(
                                  children: [
                                    Text(
                                      countData[index]['type'],
                                      style: const TextStyle(fontSize: 16),
                                    ),
                                    const SizedBox(
                                      width: 5,
                                    ),
                                    Text('${countData[index]['count']}', style: const TextStyle(fontSize: 16)),
                                  ],
                                ),
                                countData[index]['firstRecord'].isNotEmpty
                                    ? Column(
                                        children: [
                                          const SizedBox(
                                            height: 5,
                                          ),
                                          Opacity(
                                            opacity: 0.6,
                                            child: Row(
                                              children: [
                                                Expanded(
                                                  child: Text(
                                                    '${countData[index]['firstRecord']['fireEquipmentName'] ?? countData[index]['firstRecord']['videoName'] ?? ''}',
                                                    style: const TextStyle(fontSize: 14),
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                ),
                                                Expanded(
                                                  child: Text(
                                                    '${countData[index]['firstRecord']['createDate'] ?? ''}',
                                                    style: const TextStyle(fontSize: 14),
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                )
                                              ],
                                            ),
                                          )
                                        ],
                                      )
                                    : Container(),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
              itemCount: countData.length)
        ],
      ),
    );
  }

  Future<void> getCount() async {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后。。。');
      API.getFireAndDutyAndIOT().then((value) {
        if (value != null) {
          setState(() {
            countData[0]['count'] = value['fireNum'];
            countData[1]['count'] = value['faultAlarmNum'];
            countData[2]['count'] = value['iotNum'];
          });
        }
      }).whenComplete(() => Get.back());
    });
  }

  ///消防报警
  Future<void> getFireAlarmFirstRecord() async {
    Map<String, dynamic> query = {'pageNum': 1, 'pageSize': 20, 'isFirm': 'no', 'type': 'FIREALARM'};
    var data = await API.getAlarmPage(query);
    if (data != null && data['records'].isNotEmpty) {
      setState(() {
        countData[0]['firstRecord'] = data['records'].first ?? {};
        countData[0]['count'] = int.parse(data['total'] ?? '0');
      });
    }
  }

  ///故障告警
  Future<void> getFaultAlarmFirstRecord() async {
    Map<String, dynamic> query = {'pageNum': 1, 'pageSize': 20, 'isFirm': 'no', 'type': 'BREAKDOWN'};
    var data = await API.getAlarmPage(query);
    if (data != null && data['records'].isNotEmpty) {
      setState(() {
        countData[1]['firstRecord'] = data['records'].first ?? {};
        countData[1]['count'] = int.parse(data['total'] ?? '0');
      });
    }
  }

  ///在岗监测
  Future<void> getIotMonitorEventFirstRecord() async {
    Map<String, dynamic> query = {
      'current': 1,
      'size': 20,
      'eventState': '未处理',
    };
    var data = await API.getMonitorEventPage(query);
    if (data != null && data['records'].isNotEmpty) {
      setState(() {
        countData[2]['firstRecord'] = data['records'].first ?? {};
        countData[2]['count'] = int.parse(data['total'] ?? '0');
      });
    }
  }
}
