// ignore_for_file: depend_on_referenced_packages

import 'dart:async';
import 'dart:io';

import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show BMFMapSDK, BMF_COORD_TYPE;
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:permission_handler/permission_handler.dart';

//坐标系 GCJ02
class BaiduLocationUtil {
  StreamSubscription<Map<String, Object>>? _locationListener;
  late final LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();
  PermissionStatus? status;

  initBaiduLocation() {
    _locationPlugin.setAgreePrivacy(true);
    BMFMapSDK.setAgreePrivacy(true);
    if (Platform.isIOS) {
      /// 设置ios端ak, android端ak可以直接在清单文件中配置
      _locationPlugin.authAK('Sewh5Pa7oYE68aX8L1xaGVqRoriRtplp');
      BMFMapSDK.setApiKeyAndCoordType(
          'Sewh5Pa7oYE68aX8L1xaGVqRoriRtplp', BMF_COORD_TYPE.BD09LL);
    } else if (Platform.isAndroid) {
      /// Android 目前不支持接口设置Apikey,
      /// 请在主工程的Manifest文件里设置，详细配置方法请参考官网(https://lbsyun.baidu.com/)demo
      BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
    }

    /// iOS端鉴权结果
    _locationPlugin.getApiKeyCallback(callback: (String result) {
      String str = result;
      print('鉴权结果：=========================================$str');
    });
  }

  /// 动态申请定位权限
  Future<bool> _requestPermission() async {
    status = await Permission.location.status;

    if (status == PermissionStatus.granted) {
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  Future<void> getCurrentLocation(
      Function(BaiduLocation baiduLocation) onLocationChanged,
      {once = true}) async {
    bool isPermitted = await _requestPermission();
    print('isPermitted=$isPermitted');
    if (!isPermitted) {
      throw ('(当前您已关闭定位权限，请在手机设置中开启位置权限)');
    }

    if (isPermitted) {
      ///注册定位结果监听
      _locationPlugin.seriesLocationCallback(
          callback: (BaiduLocation baiduLocation) {
        // Map result = {};
        // result['longitude'] = baiduLocation.longitude;
        // result['latitude'] = baiduLocation.latitude;
        // result['address'] = baiduLocation.address;
        onLocationChanged(baiduLocation);
        if (baiduLocation.latitude != null) {
          //print("当前位置：$result");
          if (once) _stopLocation();
        }
      });
      _startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    BaiduLocationIOSOption iosOptions = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        desiredAccuracy: BMFDesiredAccuracy.best,
        // allowsBackgroundLocationUpdates: true,
        pausesLocationUpdatesAutomatically: false);

    BaiduLocationAndroidOption androidOptions = BaiduLocationAndroidOption(
        coordType: BMFLocationCoordType.bd09ll,
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        scanspan: 2000);

    // BaiduLocationIOSOption iosOptions = BaiduLocationIOSOption(
    //   coordType: BMFLocationCoordType.gcj02,
    //   locationTimeout: 10,
    //   reGeocodeTimeout: 10,
    //   activityType: BMFActivityType.automotiveNavigation,
    //   desiredAccuracy: BMFDesiredAccuracy.best,
    //   isNeedNewVersionRgc: true,
    //   pausesLocationUpdatesAutomatically: false,
    //   allowsBackgroundLocationUpdates: true,
    //   distanceFilter: 10,
    // );

    //// 设置Android定位参数
    // BaiduLocationAndroidOption _initAndroidOptions() {
    //   BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
    //       coorType: 'bd09ll',
    //       locationMode: BMFLocationMode.hightAccuracy,
    //       isNeedAddress: true,
    //       isNeedAltitude: true,
    //       isNeedLocationPoiList: true,
    //       isNeedNewVersionRgc: true,
    //       isNeedLocationDescribe: true,
    //       openGps: true,
    //       scanspan: 2000,
    //       locationPurpose: BMFLocationPurpose.sport,
    //       coordType: BMFLocationCoordType.bd09ll);
    //   return options;
    // }

    _locationPlugin.prepareLoc(androidOptions.getMap(), iosOptions.getMap());
  }

  ///开始定位
  void _startLocation() {
    _setLocationOption();
    _locationPlugin.startLocation();
    print('开始连续定位');
  }

  ///停止定位
  void _stopLocation() {
    _locationPlugin.stopLocation();
    print('停止连续定位');
  }

  ///建议在dispose中调用，以免占用内存
  void destroy() {
    _stopLocation();
    if (null != _locationListener) {
      _locationListener?.cancel(); // 停止定位
    }
  }
}
