package com.casic.dcms.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.casic.dcms.utils.callback.ICommunityListener;
import com.casic.dcms.utils.callback.ILocationListener;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.layers.FeatureLayer;

import org.jetbrains.annotations.NotNull;

import java.util.Iterator;

public class LocationHelper {

    private static final String TAG = "LocationHelper";

    /**
     * 高德sdk定位
     */
    public static void obtainCurrentLocationByGD(Context context, ILocationListener listener, boolean isOnce) {
        AMapLocationClient mLocationClient = new AMapLocationClient(context);
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，AMapLocationMode.Battery_Saving为低功耗模式，AMapLocationMode.Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setOnceLocation(isOnce);//设置是否只定位一次,默认为false
        mLocationOption.setWifiActiveScan(true);//设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setMockEnable(false);//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setInterval(15000);//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        listener.onAMapLocationGet(aMapLocation);
//                        mLocationClient.stopLocation();//停止定位
                    } else {
                        listener.onAMapLocationGet(null);
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e(TAG, "location Error, ErrCode:" + aMapLocation.getErrorCode()
                                + ", errInfo:" + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 原生GSP获取当前定位
     */
    public static void obtainCurrentLocation(Context context, ILocationListener listener, boolean isOnce) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (isOnce) {
            Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            listener.onLocationGet(location);
        } else {
            //位置变化时更新位置
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 10, new LocationListener() {
                @Override
                public void onLocationChanged(@NotNull Location location) {
                    listener.onLocationGet(location);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(@NotNull String provider) {

                }

                @Override
                public void onProviderDisabled(@NotNull String provider) {

                }
            });
        }
    }

    /**
     * 查询社区信息
     */
    public static void obtainCurrentCommunity(FeatureLayer communityLayer, QueryParameters queryParameters, ICommunityListener listener) {
        ListenableFuture<FeatureQueryResult> communityFeatureResult = communityLayer.getFeatureTable().queryFeaturesAsync(queryParameters);
        communityFeatureResult.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    FeatureQueryResult result = communityFeatureResult.get();
                    Iterator<Feature> iterator = result.iterator();
                    Feature feature = iterator.next();
                    //{FID=7, GBID=361024100011001, Note=中大社区、子正社区}
                    if (feature == null) {
                        listener.onCommunityFeatureGet(null);
                    } else {
                        listener.onCommunityFeatureGet(feature);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
