/*
 * @Author: WuXiangNan
 * @Date: 2021-02-19 14:19:35
 * @LastEditTime : 2023-05-25 15:09:13
 * @LastEditors  : WuWei
 * @Description: 高德定位
 */
import 'package:attendance_package/src/models/response_model/clock_status/location_clock_model.dart';
import 'package:attendance_package/src/service/impl/location_service_impl.dart';
// import 'package:attendance_package/src/view_models/attendance_store.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../assets.gen.dart';
import '../models/location_info_model.dart';
import 'dart:async';
import 'package:app_settings/app_settings.dart';
import 'dart:math' as math;

class LocationStore with ChangeNotifier {
  final BuildContext context;
  LocationInfo? _myLocation;
  LocationInfo? get myLocation => _myLocation;
  set myLocation(value) => _myLocation = value;
  String? _addr;

  LocationStore(this.context) {
    // startLocation();
  }

  get addr => _addr;

  final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
  GeolocatorPlatform get _locationPlugin => _geolocatorPlatform;
  GeolocatorPlatform get locationPlugin => _geolocatorPlatform;

  Future startLocation() async {
    // // 动态申请定位权限
    await requestLocationPermission();

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

    reStartLocation();
  }

  // 高德地图坐标转百度地图
  aMapToBdMap(LocationInfo locationInfo) {
    if (locationInfo.longitude != null || locationInfo.latitude != null) {
      var xPI = math.pi * 3000.0 / 180.0;
      var x = locationInfo.longitude, y = locationInfo.latitude;
      var z = math.sqrt(x! * x + y! * y) + 0.00002 * math.sin(y * xPI);
      var theta = math.atan2(y, x) + 0.000003 * math.cos(x * xPI);
      locationInfo.longitude = z * math.cos(theta) + 0.0065;
      locationInfo.latitude = z * math.sin(theta) + 0.006;
      return locationInfo;
    }
  }

  // 定位未开启窗口
  showLocationNoOpenDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return Wisdom(
            child: WisDialog(
          title: Text('提示'),
          insetPadding: EdgeInsets.symmetric(vertical: 0),
          content: Wisdom.column(
            height: 250.pt,
            width: 200.pt,
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 20.pt),
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Wisdom.column(
                children: [
                  Image(
                    image: AssetList.$dwsb_png_image,
                    height: 110.pt,
                  ),
                  WisText(
                    '定位未开启',
                    color: Colors.black,
                    size: 18.pt,
                  ),
                  WisText(
                    '请开启定位后再进行签到',
                    color: Colors.grey,
                    size: 14.pt,
                  ),
                ],
              ),
              WisButton(
                constraints: BoxConstraints(minHeight: 44.pt, minWidth: 267.pt),
                child: Text('去开启定位'),
                onPressed: () => AppSettings.openAppSettings(),
              )
            ],
          ),
        ));
      },
    );
  }

  // 定位错误窗口
  showErrorLocationDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return Wisdom(
            child: WisDialog(
          title: Text('提示'),
          insetPadding: EdgeInsets.symmetric(vertical: 0),
          content: Wisdom.column(
            height: 280.pt,
            width: 200.pt,
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 20.pt),
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Wisdom.column(
                children: [
                  Image(
                    image: AssetList.$dwsb_png_image,
                    height: 110.pt,
                  ),
                  WisText(
                    '定位失败',
                    color: Colors.black,
                    size: 18.pt,
                  ),
                  WisText(
                    '信号不好，请重新定位后再进行签到',
                    color: Colors.grey,
                    size: 14.pt,
                  ),
                ],
              ),
              WisButton(
                constraints: BoxConstraints(minHeight: 44.pt, minWidth: 267.pt),
                child: Text('重新定位'),
                onPressed: () {
                  reStartLocation();
                  Navigator.pop(context);
                },
              )
            ],
          ),
        ));
      },
    );
  }

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

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var 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;
      }
    }
  }

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

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

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

  // 逆地理获取地址
  Future onGetLocateName() async {
    var res = await (LocationServiceImpl().getLocationName(
            'output=JSON&location=${_myLocation!.longitude},${_myLocation!.latitude}&poitype=商务写字楼&radius=10&extensions=all&batch=false&roadlevel=0')
        as FutureOr<Map<String, dynamic>>);

    if (_addr != res['formatted_address']) {
      _addr =
          res['formatted_address'] is String ? res['formatted_address'] : '';
      notifyListeners();
    }
  }

  // 计算最小距离
  Map onGetMinDistance(List<LocationClockModel> originsList) {
    int minDistanceIndex = 0;
    double minDistance = 9999;
    for (int i = 0; i < originsList.length; i++) {
      LocationInfo origins = LocationInfo();
      origins.latitude = originsList[i].latitude;
      origins.longitude = originsList[i].longitude;
      double distance = computedDistance(origins, _myLocation!);
      if (minDistance > distance) {
        minDistance = distance;
        minDistanceIndex = i;
      }
    }
    Map map = {
      'minDistance': minDistance,
      'minDistanceIndex': minDistanceIndex
    };

    return map;
  }

  static double pi = 3.14159265358979323846;
  static int earthRadius = 6371393;
  double computedDistance(LocationInfo origins, LocationInfo destination) {
    double orgLng = origins.longitude! / 180 * pi;
    double orgLat = origins.latitude! / 180 * pi;
    double desLng = destination.longitude! / 180 * pi;
    double desLat = destination.latitude! / 180 * pi;

    double cosv =
        math.cos(orgLat) * math.cos(desLat) * math.cos(orgLng - desLng) +
            math.sin(orgLat) * math.sin(desLat);

    double acosv = math.acos(cosv);
    double distance = earthRadius * acosv;
    if (distance.isNaN == true || distance.isInfinite == true) {
      return 0.0;
    }
    return distance;
  }
}
