import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/Logger.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:jcs_airport/services/api.dart';

import './../../consts/url_const.dart';
import './disaster/edit_assembley_point.dart';
import './disaster/map_car.dart';
import './disaster/map_disaster.dart';
import './disaster/map_power.dart';
import './disaster/map_tools.dart';
import './entity/alarm_disaster.dart';
import './entity/assembley_point.dart';
import './event_bus.dart';
import './h5_base_map.dart';
import 'statistics/dispatch_alarm_list.dart';

/// 作战地图
class DispatchMainMap extends StatefulWidget {
  const DispatchMainMap({Key key}) : super(key: key);

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

class _DispatchMainMapState extends State<DispatchMainMap> {
  AMapFlutterLocation aMapFlutterLocation = AMapFlutterLocation();
  WebViewController webViewController;

  /// 当前警情
  AlarmDisaster alarmDisaster;

  /// 当前要编辑的集结区
  AssembleyPoint assembleyPoint;

  LngLat currentLngLat;

  /// 存储当前 token
  String token;

  /// SharedPreferences 存储用户信息
  SPTools _sp;

  /// h5 url
  String h5Url;

  dynamic carInfo = {};

  ///carId
  String carId = '';

  /// 其它页面跳转时，传入的 alarmId，可以采用 GetX 进行传参
  String alarmId = '';

  List plans = []; //救援预案
  List powerInfo = []; //力量信息
  Map helpInfo = {'scenePicture': [], 'planePicture': [], 'facadePicture': [], 'orgUsrzhDto': {}}; //救援对象信息
  List keySiteBuildTree = []; //重点部位树


  @override
  void initState() {
    super.initState();
    if (Get.arguments is String) {
      alarmId = Get.arguments;
    } else if (Get.arguments is Map) {
      alarmId = Get.arguments['id'];
    }
    token = LoginCacheInfo.token;
    queryCarInfo();
    DispatchEvents.on(onEventMessage, DispatchTagNames.MAIN_MAP);
    _initSPInfo();
    getLocation();
  }

  Future<void> getLocation() async {
    if (await Permission.location.request().isGranted) {
      AMapLocationOption aMapLocationOption = AMapLocationOption();
      aMapFlutterLocation.setLocationOption(aMapLocationOption);
      aMapFlutterLocation.onLocationChanged().listen((Map<String, Object> result) {
        if (result != null) {
          Logger.warn('已定位:${result['address']}');
          FlutterToast.toastBottom('已定位:${result['address']}');
          double latitude = result['latitude'];
          double longitude = result['longitude'];
          currentLngLat = LngLat(longitude, latitude);
          aMapFlutterLocation.stopLocation();
        }
      });
      aMapFlutterLocation.startLocation();
    }
  }

  Future<void> onEventMessage(event) async {
    if (event is EventData) {
      if (event.type == EventDataType.AlarmDisaster) {
        AlarmDisaster alarm = AlarmDisaster.fromJson(event.content);
        setState(() {
          alarmDisaster = alarm;
        });
       



        _getPlan(alarm.sequenceNbr);
        _getPowerInfo(alarm.sequenceNbr);
        _getOrgUsrzhDto(alarm.sequenceNbr);
        _getKeySiteBuildTree(alarm.sequenceNbr);





         Future.wait(<Future>[
          API.getAlarmDetails(alarm.sequenceNbr),
          API.getAlarmPersonCount(alarm.sequenceNbr),
          API.getAlarmRescueObject(alarm.sequenceNbr),
          API.getAlarmStrengthCount(alarm.sequenceNbr)
        ]).then((value) {
          // 灾情详情
          var details = value[0];
          try {
            alarm.alarmDetails = details ?? {};
          } catch (e) {
            ToastUtils.showToast('灾情详情获取失败');
          }
          // 灾情统计数据
          var alarmPerson = value[1];
          try {
            if (alarmPerson.isNotEmpty) {
              alarm.trappedNum = alarmPerson[0]['value'];
              alarm.casualtiesNum = alarmPerson[1]['value'];
            }
          } catch (e) {
            ToastUtils.showToast('灾情统计数据获取失败');
          }
          // 救援对象
          var rescueObject = value[2];
          try {
            alarm.rescueObject = rescueObject ?? [];
          } catch (e) {
            ToastUtils.showToast('救援对象数据获取失败');
          }
          // 到场力量数据
          var strengthData = value[3];
          try {
            alarm.strengthCount = strengthData ?? [];
          } catch (e) {
            ToastUtils.showToast('到场力量数据获取失败');
          }
          setState(() {
            alarmDisaster = alarm;
          });
        });
      } else if (event.type == EventDataType.EditAssemblyPoint) {
        setState(() {
          assembleyPoint = AssembleyPoint.fromJson(event.content);
        });
      } else if (event.type == EventDataType.MapClickEmpty) {
        setState(() {
          assembleyPoint = null;
        });
      } else if (event.type == EventDataType.Self2AlarmDistance) {
        setState(() {
          alarmDisaster.distance = event.content;
        });
      }
    }
  }

  /// 初始化 SharedPreferences 数据
  Future<void> _initSPInfo() async {
    _sp = await SPTools.instance;
    String $token = _sp.getString(GlobalConst.token);

    /// 异步获取 token 会导致子组件的 url 无法实时更新
    // setState(() {
    //   token = $token;
    // });
    String _h5Url = await APIUrlManager.getH5Url();
    setState(() {
      h5Url = _h5Url ?? URLConst.MAP_H5_URL;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('作战地图'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(
              Icons.message_outlined,
              color: Colors.white,
            ),
            onPressed: () async {
              String carId = await Get.to(CurrentAlarmList(
                needOpenMap: false,
                callJSMethod: executeJs,
              ));
              if (carId != null) {
                setState(() {
                  this.carId = carId;
                });
              }
            },
          )
        ],
      ),
      backgroundColor: Colors.grey,

      ///页面主体使用层叠布局
      body: Stack(
        children: <Widget>[buildDrawerWidget()],
      ),
    );
  }

  Widget buildBody() {
    List<Widget> bodyList = [];
    bodyList.addAll([
      H5MapBase(
          h5Url: h5Url != null ? '$h5Url?token=$token&alarmId=$alarmId' : '', onCreated: (wvc) => {webViewController = wvc}),
      MapTools(
        callJSMethod: executeJs,
        token: token,
        h5Url: h5Url,
        currentLngLat: currentLngLat != null ? currentLngLat.toJson() : {},
        alarmId: alarmDisaster?.sequenceNbr ?? '',
      ),
      PowerInfo(
        alarmDisaster?.sequenceNbr,
        alarmDisaster?.latitude,
        alarmDisaster?.longitude,
      )
    ]);
    if (carInfo != null && carInfo['isDriver'] == true) {
      bodyList.add(CarInfo(alarmDisaster?.sequenceNbr, carInfo));
    }
    return Stack(
      children: bodyList,
    );
  }

  Widget buildDrawerWidget() {
    final double _panelHeightOpen = MediaQuery.of(context).size.height * 0.80;
    return AmosDrawer(
      maxHeight: assembleyPoint != null ? 100 : _panelHeightOpen,
      minHeight: alarmDisaster != null ? (assembleyPoint == null ? 160.0 : 100) : 0.0,
      panelBuilder: (sc) => alarmDisaster != null
          ? (assembleyPoint == null
              ? DisasterInfo(
                  callJSMethod: executeJs,
                  controller: sc,
                  alarmDisaster: alarmDisaster,
                  isCar: carInfo['isDriver'] ?? false,
                  currentLngLat: currentLngLat != null ? currentLngLat.toJson() : {},
                  plans :plans, //救援预案
                  powerInfo: powerInfo, //力量信息
                  helpInfo:helpInfo,//救援对象信息
                  keySiteBuildTree:keySiteBuildTree , //重点部位树
                )
              : EditAssembleyPoint(
                  callJSMethod: executeJs,
                  alarmDisaster: alarmDisaster,
                  controller: sc,
                  h5Url: h5Url,
                  currentLngLat: currentLngLat != null ? currentLngLat.toJson() : {},
                  assembleyPoint: assembleyPoint,
                  token: token))
          : Container(),
      body: buildBody(),
    );
  }

  void executeJs(String method, {dynamic data}) {
    webViewController.evaluateJavascript('$method()');
  }

  @override
  void dispose() {
    super.dispose();
    DispatchEvents.cancel(DispatchTagNames.MAIN_MAP);
    aMapFlutterLocation.destroy();
  }

  void queryCarInfo() {
    API.carPersonPost().then((resp) {
      if (resp != null) {
        setState(() {
          carInfo = resp;
        });
      }
    });
  }


///获取救援预案
  void _getPlan(String sequenceNbr) {
    API.getSituation(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          plans=value;
        });
      }else{
        setState(() {
          plans=[];
        });
      }
    });
  }

  ///获取力量信息
  void _getPowerInfo(String sequenceNbr) {
    API.getPowerInfo(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          powerInfo=value;
        });
      }else{
        setState(() {
          powerInfo=[];
        });
      }
    });
  }

  ///获取救援对象
  void _getOrgUsrzhDto(String sequenceNbr) {
    API.getOrgUsrzhDto(sequenceNbr).then((value) {
      if (value != null) {

        setState(() {
          // helpInfo.addAll(value);
          helpInfo=value;
        });
      }
    });
  }

  ///获取重点部位树
  void _getKeySiteBuildTree(String sequenceNbr) {
    API.getKeySiteBuildTree(sequenceNbr).then((value) {
      if (value != null) {
        setState(() {
          keySiteBuildTree=value;
        });
      }else{
        setState(() {
          keySiteBuildTree=[];
        });
      }
    });
  }



  
}
