package com.rdiot.yx485.util

/**
 *
 * @author mR2hao
 * @date 2022/12/19
 */

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.*
import androidx.core.app.ActivityCompat
import com.drake.net.utils.withMain
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.*


/**
 * 定位工具 返回市级精度位置
 * @author mR2hao
 * @date 2022/12/19
 */
object LocationUtils {
    private var job: Job? = null
    fun getLocations(context: Context): String {
        var strLocation = ""
        try {
            //获取系统的服务，
            val locationManager =
                context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
            //创建一个criteria对象
            val criteria = Criteria()
            criteria.accuracy = Criteria.ACCURACY_COARSE
            //设置不需要获取海拔方向数据
            criteria.isAltitudeRequired = false
            criteria.isBearingRequired = false
            //设置允许产生资费
            criteria.isCostAllowed = true
            //要求低耗电
            criteria.powerRequirement = Criteria.POWER_LOW

            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return strLocation
            }

            if (job == null) {
                job = GlobalScope.launch {
                    withMain {
                        locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            1000,
                            0.1f
                        ) {
                        }
                        delay(1000)
                    }
                }
            }

            //获取定位
            val location = getLastKnownLocation(locationManager)
            //第一次获得设备的位置
            if (location != null) {
                // 耗时操作
                strLocation += convertAddress(context, location.latitude, location.longitude)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return strLocation
    }


    @SuppressLint("MissingPermission")
    private fun getLastKnownLocation(locationManager: LocationManager): Location? {
        val providers = locationManager.getProviders(true)
        var bestLocation: Location? = null
        for (provider in providers) {
            val l = locationManager.getLastKnownLocation(provider) ?: continue

            if (bestLocation == null || l.accuracy < bestLocation.accuracy) {
                // Found best last known location: %s", l);
                bestLocation = l
            }
        }
        return bestLocation
    }


    /**
     * @param latitude  经度
     * @param longitude 纬度
     * @return 详细位置信息 GeoCoder是基于后台backend的服务，因此这个方法不是对每台设备都适用。
     */
    private fun convertAddress(context: Context?, latitude: Double, longitude: Double): String {
        val mGeocoder = Geocoder(context, Locale.getDefault())
        val mStringBuilder = StringBuilder()
        try {
            val mAddresses = mGeocoder.getFromLocation(latitude, longitude, 1)
            if (mAddresses.isNotEmpty()) {
                val address = mAddresses[0]
                mStringBuilder
//                    .append(address.countryName)
//                    .append(address.adminArea)
                    .append(address.locality)
//                    .append(address.subLocality)
//                    .append(address.featureName)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return mStringBuilder.toString()
    }

}

