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/services/api.dart';
import 'package:jcs_airport/view/dispatch/statistics/dispatch_alarm_list.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:amos_flutter_utils/extension/int_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/planCheck/add_hidden_danger.dart';
import 'CurrentDanger.dart';
import 'HomeMenuCard.dart';
import 'HomeMessageCard.dart';
import 'iot_monitor.dart';
import 'dart:async';

///@Description     领导首页
///@author          helinlin
///@create          2021-10-25 9:57
class HomeLeader extends StatefulWidget {
  const HomeLeader({Key key}) : super(key: key);

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

class _HomeLeaderState extends State<HomeLeader> {
  final List _countList = [
    {
      'description': '当前警情',
      'count': 0,
      'countColor': Colors.cyanAccent,
      'onClick': () {
        Get.to(const CurrentAlarmList(), arguments: 'fromHome');
      }
    },
    {
      'description': '物联监测',
      'count': 0,
      'countColor': Colors.redAccent,
      'onClick': () {
        Get.to(const IotMonitor());
      }
    },
    {
      'description': '当前隐患',
      'count': 0,
      'countColor': Colors.lightGreenAccent,
      'onClick': () {
        Get.to(const CurrentDanger());
      }
    }
  ];
  int allCount = 0;
  double latitude;
  double longitude;
  final AMapFlutterLocation aMapFlutterLocation = AMapFlutterLocation();

  @override
  void initState() {
    super.initState();
    getCurrentAlert();
    getFireAlarmFirstRecord();
    getFaultAlarmFirstRecord();
    getIotMonitorEventFirstRecord();
    getAlarmGiveStatistics();
    _timerLocation();
  }

  /// 高德定位
  Future<void> _timerLocation() async {
    var timer = null;
    var result = await API.getuserBJ();
    if(result != null){
      aMapFlutterLocation.onLocationChanged().listen((Map<String, Object> res) {
        if (res != null) {
          latitude = res['latitude'];
          longitude = res['longitude'];
          // aMapFlutterLocation.stopLocation();
        }
      });
      aMapFlutterLocation.startLocation();
      timer=Timer.periodic(
          const Duration(milliseconds: 60000),(timer) async{
        var data = {
          'carNum':result['carNum'],
          'sequenceNbr':result['carId'],
          'longitude': longitude,
          'latitude':  latitude,
        };
        // longitude = longitude + 0.0003;
        // var data = {
        //   'carNum':'机场·消0014',
        //   'sequenceNbr':'1438718392776286210',
        //   'longitude': longitude,
        //   'latitude':  latitude,
        // };
        if(longitude != null && latitude != null){
          API.addESCar(data).then((value){
            print(value);
            if (value == true) {}
            else{
              aMapFlutterLocation.stopLocation();
              timer.cancel();
            }
          }).catchError((Object obj) {
            print('报错了！！！！！！！！！！');
            print(obj);
            aMapFlutterLocation.stopLocation();
            timer.cancel();
          });
        }
        // timer.cancel();//取消定时器
      });
    }else{
      aMapFlutterLocation.stopLocation();
      timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('首页'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Container(
            color: const Color.fromARGB(255, 245, 250, 245),
            child: Stack(
              children: [
                Container(
                  height: 300,
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                          begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Colors.blue, Colors.blue])),
                  child: Container(),
                ),
                Column(
                  children: [
                    Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(top: 15, bottom: 0),
                          child: CircularPercentIndicator(
                            curve: Curves.easeInOut,
                            circularStrokeCap: CircularStrokeCap.round,
                            animation: false,
                            radius: 130.0,
                            lineWidth: 15.0,
                            percent: 1.0,
                            center: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  allCount.toString() + '个',
                                  style: const TextStyle(color: Colors.white, fontSize: 25, fontWeight: FontWeight.bold),
                                ),
                              ],
                            ),
                            progressColor: Colors.greenAccent,
                            backgroundColor: Colors.white,
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 20, bottom: 20),
                          child: Row(
                            children: _countList
                                .map((element) => buildCountItem(element['count'].toString(), element['countColor'],
                                    element['description'], element['onClick']))
                                .toList()
                                .cast<Widget>()
                                  ..insert(1, buildCountDivider())
                                  ..insert(3, buildCountDivider()),
                          ),
                        )
                      ],
                    ),
                    const HomeMenuCard(),
                    const HomeMessageCard(MessageType.Task),
                    const HomeMessageCard(MessageType.Message)
                  ],
                ),
              ],
            ),
          ),
        ));
  }

  Container buildCountDivider() {
    return Container(
      height: 30,
      child: const Opacity(
        opacity: 0.4,
        child: VerticalDivider(
          color: Colors.white,
          thickness: 1,
        ),
      ),
    );
  }

  Widget buildCountItem(String count, Color countColor, String description, Function onClick) {
    return Expanded(
      child: InkWell(
        onTap: onClick,
        child: Column(
          children: [
            Text(
              count,
              style: TextStyle(color: countColor, fontWeight: FontWeight.bold, fontSize: 25.px),
            ),
            Opacity(
              opacity: 0.9,
              child: Text(
                description,
                style: TextStyle(color: Colors.white, fontSize: 16.px),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///获取统计信息
  void getAlarmGiveStatistics() {
    API.getAlarmGiveStatistics().then((value) {
      if (value != null) {
        setState(() {
          _countList[2]['count'] = value['currentHiddenDanger'] ?? 0;
          allCount += value['currentHiddenDanger'] ?? 0;
        });
      }
    });
  }

  ///当前警情
  Future<void> getCurrentAlert() async {
    var data = await API.commandHistoryList({'status': '0', 'orderTime': '1', 'pageNum': 1, 'pageSize': 1});
    if (data != null) {
      setState(() {
        int count = int.parse(data['total'] ?? '0');
        _countList[0]['count'] = count;
        allCount += count;
      });
    }
  }

  ///消防报警
  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(() {
        int total = int.parse(data['total'] ?? '0');
        _countList[1]['count'] += total;
        allCount += total;
      });
    }
  }

  ///故障告警
  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(() {
        int total = int.parse(data['total'] ?? '0');
        _countList[1]['count'] += total;
        allCount += total;
      });
    }
  }

  ///在岗监测
  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(() {
        int total = int.parse(data['total'] ?? '0');
        _countList[1]['count'] += total;
        allCount += total;
      });
    }
  }
}
