import 'dart:async';

import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:permission_handler/permission_handler.dart';

enum MapPageType { Look, Check }

class LiftMapPage extends StatefulWidget {
  LiftMapPage({this.type = MapPageType.Check, this.coordinate});

  final MapPageType type;
  final String coordinate;

  @override
  State<StatefulWidget> createState() {
    return LiftMapPageState();
  }
}

final _assetsIcon = Uri.parse('assets/images/work/icon_location.png');
final _assetsIcon2 = Uri.parse('assets/images/work/icon_location2.png');

class LiftMapPageState extends State<LiftMapPage> {
  LatLng latLng = LatLng(0, 0);
  List<MarkerOption> _markers = [];
  BuildContext mContext;
  AmapController _controller;

  Map<String, Object> _locationResult;
  StreamSubscription<Map<String, Object>> _locationListener;
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();

  @override
  void initState() {
    super.initState();
    mContext = context;
    if (widget.type == MapPageType.Look) {
      var arr = widget.coordinate.split(",");
      if (arr.length != 2) {
        toasts("坐标出错");
        return;
      }
      latLng.latitude = double.parse(arr[1]);
      latLng.longitude = double.parse(arr[0]);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    mContext.dependOnInheritedWidgetOfExactType();
    if (widget.type == MapPageType.Look) {
      _markers = [
        MarkerOption(
            title: "电梯位置",
            latLng: latLng,
            iconUri: _assetsIcon2,
            imageConfig: createLocalImageConfiguration(context),
            width: 28,
            height: 28)
      ];
    }
  }

  Future<LatLng> getLocation() async {
    if (await requestPermission()) {
//      if (null != _locationPlugin) {
//        ///开始定位之前设置定位参数
//        _setLocationOption();
//        _locationPlugin.startLocation();
//      }
    }
    return latLng;
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
//      toasts("已经定位.");
      return true;
    } else {
      toasts('请开启定位权限!');
      return false;
    }
  }

  saveLatLng() async {
    NavigatorUtils.goBackWithParams(
        context, "${latLng.longitude},${latLng.latitude}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "位置",
        actions: <Widget>[
          widget.type == MapPageType.Check
              ? FlatButton(
                  child: Text("确定"),
                  textColor: Colours.dark_text,
                  highlightColor: Colors.transparent,
                  onPressed: () {
                    saveLatLng();
                  },
                )
              : Container()
        ],
      ),
      body: Container(
          child: AmapView(
        // 地图类型
        mapType: MapType.Standard,
        // 是否显示缩放控件
        showZoomControl: false,
        // 是否显示指南针控件
        showCompass: false,
        // 是否显示比例尺控件
        showScaleControl: false,
        // 是否使能缩放手势
        zoomGesturesEnabled: true,
        // 是否使能滚动手势
        scrollGesturesEnabled: true,
        // 是否使能旋转手势
        rotateGestureEnabled: true,
        // 是否使能倾斜手势
        tiltGestureEnabled: true,
        // 缩放级别
        zoomLevel: 17,
        maskDelay: Duration(milliseconds: 500),
        markers: _markers,
        // 中心点坐标
        centerCoordinate: latLng,
        // 标记

        onMapCreated: (controller) async {
          _controller = controller;
          if (widget.type == MapPageType.Check){
//            await getLocation();
            await _controller?.showMyLocation(MyLocationOption(
              myLocationType: MyLocationType.Locate,
            ));
          }

        },

//          onMapCreated: (controller) async {
//
//            _controller = controller;
//            if(widget.type == MapPageType.Look){
//              _controller.addMarker(MarkerOption(latLng: latLng,title: "电梯位置",));
//            }
//            // requestPermission是权限请求方法, 需要你自己实现
//            // 如果不知道怎么处理, 可以参考example工程的实现, example过程依赖了`permission_handler`插件.
//            if (await requestPermission() && widget.type == MapPageType.Check) {
//              await controller.showMyLocation(MyLocationOption());
//            }
//          },
//          onMapMoveEnd: (controller) async{
//            if(widget.type == MapPageType.Check){
//              latLng = await _controller?.getLocation();
//            }
//          },
      )),
    );
  }
}
