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';
import 'package:safe_control/routes/routes.dart' as safe_control_routes;

///@Description     首页当前隐患
///@author          helinlin
///@create          2021-10-29 9:44
class CurrentDanger extends StatefulWidget {
  static String currentPatrolDangerWaitHandle = 'currentPatrolDangerWaitHandle';
  static String currentSupervisionDangerWaitHandle = 'currentSupervisionDangerWaitHandle';

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

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

class _CurrentDangerState extends State<CurrentDanger> {
  List countData = [
    {
      'type': '消防巡查隐患处理:',
      'image': 'assets/images/fire_warning.png',
      'count': 0,
      'firstRecord': {'title': '', 'subTitle': ''},
      'onClick': () {
        Get.toNamed(safe_control_routes.Routes.waitHandlePage,
            arguments: PlatformMenu(frontComponent: CurrentDanger.currentPatrolDangerWaitHandle));
      }
    },
    {
      'type': '防火监督隐患处理:',
      'image': 'assets/images/danger_audit.png',
      'count': 0,
      'firstRecord': {'title': '', 'subTitle': ''},
      'onClick': () {
        Get.toNamed(JCSRoutes.hiddenDanger,
            arguments: PlatformMenu(frontComponent: CurrentDanger.currentSupervisionDangerWaitHandle));
      }
    },
  ];

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

  @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: [
                                                Text(
                                                  '${countData[index]['firstRecord']['title'] ?? ''}',
                                                  style: const TextStyle(fontSize: 14),
                                                  overflow: TextOverflow.ellipsis,
                                                ),
                                                Expanded(
                                                  child: Text(
                                                    '${countData[index]['firstRecord']['subTitle'] ?? ''}',
                                                    textAlign: TextAlign.end,
                                                    style: const TextStyle(fontSize: 14),
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                )
                                              ],
                                            ),
                                          )
                                        ],
                                      )
                                    : Container(),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
              itemCount: countData.length)
        ],
      ),
    );
  }

  Future<void> getCount() async {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后。。。');
      List<Future> tasks = [];
      tasks.add(getHiddenDangerNum());
      tasks.add(getPatrolFirst());
      tasks.add(getSupervisionFirst());
      Future.wait(tasks).then((value) {}).whenComplete(() => Get.back());
    });
  }

  Future<void> getHiddenDangerNum() async {
    var data = await API.unFinishedDanger();
    if (data != null) {
      setState(() {
        countData[0]['count'] = data['patrol'];
        countData[1]['count'] = data['supervision'];
      });
    }
  }

  Future<void> getPatrolFirst() async {
    Map filterData = {
      'dangerLevel': -1,
      'pageSize': 10,
      'pageNumber': 0,
      'isHandle': false,
      'dangerState': 0,
      'belongType': 0,
      'dangerId': null
    };
    var data = await API.patrolHiddenDangerList(filterData);
    if (data != null && data['content'] is List && data['content'].isNotEmpty) {
      setState(() {
        countData[0]
            ['firstRecord'] = {'title': data['content'].first['dangerName'], 'subTitle': data['content'].first['limitDesc']};
      });
    }
  }

  Future<void> getSupervisionFirst() async {
    Map filterData = {'my': '0', 'dangerState': '', 'dangerLevel': ''};
    var data = await API.dangerAuditList(filterData..addAll({'current': 1, 'size': 1}));
    if (data != null && data['records'] is List && data['records'].isNotEmpty) {
      setState(() {
        countData[1]['firstRecord'] = {
          'title': data['records'].first['dangerName'],
          'subTitle': data['records'].first['reformLimitDate']
        };
      });
    }
  }
}
