package com.yeejoin.amos.csfas_station

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.amap.api.location.AMapLocationClient
import com.google.zxing.integration.android.IntentIntegrator
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import org.json.JSONObject
import java.util.concurrent.TimeUnit

class MainActivity: FlutterActivity() {

    companion object {
        const val locationChannel: String = "amosMethodChannel"
    }

    private lateinit var methodChannel: MethodChannel
    private lateinit var result: MethodChannel.Result
    private var hasResult = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AMapLocationClient.updatePrivacyShow(this.context, true, true)
        AMapLocationClient.updatePrivacyAgree(this.context, true)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        methodChannel = MethodChannel(flutterEngine.dartExecutor, locationChannel)
        methodChannel.setMethodCallHandler { call, result ->
            hasResult = false
            this@MainActivity.result = result
            when (call.method) {
                "getLocation" -> {
                    checkPermission()
                }
                "scan" -> {
                    IntentIntegrator(this).apply {
                        setPrompt("请将二维码置于取景框内扫描")
                        setCameraId(0) //0 后置摄像头  1 前置摄像头
                        setBeepEnabled(true)//开启成功声音
                        setTimeout(20000)//设置超时时间
                        setBarcodeImageEnabled(true)//是否
                        setTorchEnabled(true)//闪光灯开启
                        initiateScan()
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val it = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if(it!=null) {
            if (it.contents == null) {
                if (!hasResult) {
                    hasResult = true
                    result.success("")
                }
            } else {
                if (!hasResult) {
                    hasResult = true
                    result.success(it.contents)
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun checkPermission() {
        val accessFineLocation = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val accessCoarseLocation = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
        if (accessFineLocation == PackageManager.PERMISSION_DENIED || accessCoarseLocation == PackageManager
                .PERMISSION_DENIED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ), 1
            )
        } else {
            getLocation()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            var permission = true
            repeat(grantResults.size) {
                if (it != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "未授权无法定位", Toast.LENGTH_SHORT).show()
                    permission = false
                }
            }
            if (permission) getLocation()
        }
    }

    @SuppressLint("MissingPermission")
    private fun getLocation() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val providers = locationManager.getProviders(true)
        var locationProvider = ""
        //GPS 定位的精准度比较高，但是非常耗电。
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            locationProvider = LocationManager.GPS_PROVIDER
            //网络定位的精准度稍差，但耗电量比较少。
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            locationProvider = LocationManager.NETWORK_PROVIDER
        } else {
            Toast.makeText(this, "没有可用的服务", Toast.LENGTH_SHORT).show()
            val jsonObject = JSONObject().apply {
                put("latitude", "0")
                put("longitude", "0")
            }
            if (!hasResult) {
                hasResult = true
                result.success(jsonObject.toString())
            }
            return
        }
        val myLocationListener: LocationListener = MyLocationListener()
        locationManager.requestLocationUpdates(locationProvider, 1000L, 1f, myLocationListener)
        var times = 0
        while (true) {
            val lastKnownLocation = locationManager.getLastKnownLocation(locationProvider)
            if (lastKnownLocation != null) {
                val jsonObject = JSONObject().apply {
                    put("latitude", lastKnownLocation.latitude)
                    put("longitude", lastKnownLocation.longitude)
                }
                if (!hasResult) {
                    hasResult = true
                    result.success(jsonObject.toString())
                }
                locationManager.removeUpdates(myLocationListener)
                break
            } else {
                times++
                if (times > 10) {
                    break
                }
                TimeUnit.SECONDS.sleep(1)
            }
        }
    }

    class MyLocationListener : LocationListener {
        override fun onLocationChanged(location: Location?) {}

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}

        override fun onProviderEnabled(provider: String?) {}

        override fun onProviderDisabled(provider: String?) {}
    }
}
