/*
 * @Author: WuXiangNan
 * @Date: 2021-02-19 09:44:57
 * @LastEditTime: 2021-07-23 09:15:01
 * @LastEditors: WuXiangNan
 * @Description: 高德定位
 */

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
// import 'package:amap_flutter_location/amap_location_option.dart';
import '../models/location_info_model.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class LocationPosition extends StatefulWidget {
  @override
  _LocationPositionState createState() => new _LocationPositionState();
}

class _LocationPositionState extends State<LocationPosition> {
  Map<String, Object>? _locationResult;

  StreamSubscription<Map<String, Object>>? _locationListener;

  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
  GeolocatorPlatform get _locationPlugin => _geolocatorPlatform;
  LocationInfo? locationInfo;

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

    /// 动态申请定位权限
    requestPermission();

    ///设置Android和iOS的apiKey<br>
    ///
    /// 定位Flutter插件提供了单独的设置ApiKey的接口，
    /// 使用接口的优先级高于通过Native配置ApiKey的优先级（通过Api接口配置后，通过Native配置文件设置的key将不生效），
    /// 使用时可根据实际情况决定使用哪种方式
    ///
    ///key的申请请参考高德开放平台官网说明<br>
    ///
    ///Android: https://lbs.amap.com/api/android-location-sdk/guide/create-project/get-key
    ///
    ///iOS: https://lbs.amap.com/api/ios-location-sdk/guide/create-project/get-key
    // AMapFlutterLocation.setApiKey(
    //     "anroid ApiKey", "ios ApiKey");

    ///iOS 获取native精度类型
    // if (Platform.isIOS) {
    //   requestAccuracyAuthorization();
    // }

    // ///注册定位结果监听
    // _locationListener = _locationPlugin
    //     .onLocationChanged()
    //     .listen((Map<String, Object> result) {
    //   setState(() {
    //     _locationResult = result;
    //   });
    // });
  }

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

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener!.cancel();
    }

    ///销毁定位
    // _locationPlugin.destroy();
  }

  ///设置定位参数
  // void _setLocationOption() {
  //   if (null != _locationPlugin) {
  //     AMapLocationOption locationOption = new AMapLocationOption();

  //     ///是否单次定位
  //     locationOption.onceLocation = false;

  //     ///是否需要返回逆地理信息
  //     locationOption.needAddress = true;

  //     ///逆地理信息的语言类型
  //     locationOption.geoLanguage = GeoLanguage.DEFAULT;

  //     locationOption.desiredLocationAccuracyAuthorizationMode =
  //         AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

  //     locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

  //     ///设置Android端连续定位的定位间隔
  //     locationOption.locationInterval = 2000;

  //     ///设置Android端的定位模式<br>
  //     ///可选值：<br>
  //     ///<li>[AMapLocationMode.Battery_Saving]</li>
  //     ///<li>[AMapLocationMode.Device_Sensors]</li>
  //     ///<li>[AMapLocationMode.Hight_Accuracy]</li>
  //     locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

  //     ///设置iOS端的定位最小更新距离<br>
  //     locationOption.distanceFilter = -1;

  //     ///设置iOS端期望的定位精度
  //     /// 可选值：<br>
  //     /// <li>[DesiredAccuracy.Best] 最高精度</li>
  //     /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
  //     /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
  //     /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
  //     /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
  //     locationOption.desiredAccuracy = DesiredAccuracy.Best;

  //     ///设置iOS端是否允许系统暂停定位
  //     locationOption.pausesLocationUpdatesAutomatically = false;

  //     ///将定位参数设置给定位插件
  //     _locationPlugin.setLocationOption(locationOption);
  //   }
  // }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    // _setLocationOption();
    _locationPlugin.getCurrentPosition(
        locationSettings: LocationSettings(
      accuracy: LocationAccuracy.best,
    ));
  }

  ///停止定位
  void _stopLocation() {
    // if (null != _locationPlugin) {
      // _locationPlugin.stop();
    // }
  }

  Container _createButtonContainer() {
    return new Container(
        alignment: Alignment.center,
        child: Wisdom.row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          margin: EdgeInsets.symmetric(vertical: 20.pt),
          children: <Widget>[
            new TextButton(
              onPressed: _startLocation,
              child: new Text('开始定位'),
              style: TextButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Color(0XFF0F67F8),
              ),
              // color: Color(0XFF0F67F8),
              // textColor: Colors.white,
            ),
            new Container(width: 20.0),
            new TextButton(
              onPressed: _stopLocation,
              child: new Text('停止定位'),
              style: TextButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Color(0XFF0F67F8),
              ),
              // color: Color(0XFF0F67F8),
              // textColor: Colors.white,
            )
          ],
        ));
  }

  Widget _resultWidget(key, value) {
    return new Container(
      child: new Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          new Container(
            alignment: Alignment.centerRight,
            width: 100.0,
            child: new Text('$key :'),
          ),
          new Container(width: 5.0),
          new Flexible(child: new Text('$value', softWrap: true)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgets = [];
    widgets.add(_createButtonContainer());

    if (_locationResult != null) {
      locationInfo = LocationInfo.fromJson(_locationResult);
      // debugPrint(locationInfo.address);
      _locationResult!.forEach((key, value) {
        widgets.add(_resultWidget(key, value));
      });
    }
    final colorScheme = WTheme.of(context).colorScheme;
    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        title: new Text('高德定位'),
      ),
      body: new Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: widgets,
      ),
    );
  }

  ///获取iOS native的accuracyAuthorization类型
  // void requestAccuracyAuthorization() async {
  //   await _locationPlugin.getSystemAccuracyAuthorization();
  // }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    await requestLocationPermission();
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    bool locationServiceEnabled = true;
    //获取当前的权限
    LocationPermission status = await Geolocator.checkPermission();
    switch (status) {
      case LocationPermission.denied:
        locationServiceEnabled = false;
        break;
      case LocationPermission.deniedForever:
        locationServiceEnabled = false;
        break;
      case LocationPermission.unableToDetermine:
        locationServiceEnabled = false;
        break;
      default:
        break;
    }
    print("GeoUtil - isReady - $locationServiceEnabled");
    return locationServiceEnabled;
  }
}
