package com.xty.common.aMapUtils

import android.app.Application
import android.content.Context
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.xty.common.LogUtils
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*


/**
 * 高德地图定位
 */

object  AmapInit{

    //val queue: Queue<String> = LinkedList()
    val mainScope= MainScope()
    private lateinit var funs:(map:AMapLocation)->Unit  //传入监听方法
    private val mLocationOption by lazy { AMapLocationClientOption() }

    private var mLocationClient: AMapLocationClient? = null

    private val locationListener by lazy {
        AMapLocationListener {
            if (it.getErrorCode() == 0) {
                LogUtils.d("定位成功")

                funs.invoke(it)

            } else {
                    mainScope.launch {
                        delay(3000)
                        mLocationClient?.startLocation()
                    }
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                LogUtils.e("location Error, ErrCode:"
                            + it.getErrorCode() + ", errInfo:"
                            + it.getErrorInfo()
                );
            }

        }
    }

    private fun init(context: Context) {
        //隐私政策合规
        AMapLocationClient.updatePrivacyShow(context,true,true)
        AMapLocationClient.updatePrivacyAgree(context,true)

        mLocationClient = AMapLocationClient(context)
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption.isOnceLocation = true  // 单次定位结果true  该方法默认为false
        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.isOnceLocationLatest = true;
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.isNeedAddress = true
        //给定位客户端对象设置定位参数
        mLocationClient?.setLocationOption(mLocationOption);
        mLocationClient?.setLocationListener(locationListener)  //设置监听

    }

    //开启监听
    fun startLocation(context: Context, back:(listener:AMapLocation)->Unit) {

        funs=back
        if (mLocationClient == null) {
            init(context)
        }
        mLocationClient?.let {
            it.startLocation()
        }
    }

    /**
     * 停止
     */
    fun stopLocation(){
        mainScope.cancel()
        mLocationClient?.let {
            it.stopLocation()
            it.onDestroy()
        }
    }



}