package com.sd.geelyhmiweb

import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.ConsoleMessage
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.webkit.WebResourceErrorCompat
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewClientCompat
import com.sd.geelyhmiweb.databinding.ActivityMainBinding
import com.sd.geelyhmiweb.dsbridge.OnReturnValue
import com.sd.geelyhmiweb.utils.MyContants
import com.sd.geelyhmiweb.viewmodels.AMapLoc
import com.sd.geelyhmiweb.viewmodels.MainVM
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    override fun onStart() {
        super.onStart()
//        aMapLoc.startLocation()
    }

    override fun onStop() {
        super.onStop()
        //停止定位
        aMapLoc.stopLocation()
    }

    override fun onDestroy() {
        super.onDestroy()
        aMapLoc.destroyLocation()
        binding.dwebview.destroy()
    }

    private lateinit var binding: ActivityMainBinding

    private val mainVM: MainVM by viewModels()

    private lateinit var assetLoader: WebViewAssetLoader

    private val jsApi = JsApi()

    //    private val myLocVM: MyLocVM by viewModels()
    private val aMapLoc: AMapLoc by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        aMapLoc.initLocation()
        jsApi.mainVM = mainVM
        jsApi.aMapLoc = aMapLoc
        initWeb()
        initLis()
    }

    private fun initWeb() {
        assetLoader = WebViewAssetLoader.Builder()
            .setHttpAllowed(true)
            .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
            .build()

        binding.dwebview.clearCache(true)
        binding.dwebview.clearHistory()
        binding.dwebview.addJavascriptObject(jsApi, null)
//        DWebView.setWebContentsDebuggingEnabled(true)
        binding.dwebview.settings.run {
//            userAgentString="Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Mobile Safari/537.36"
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            loadWithOverviewMode = true

            cacheMode = WebSettings.LOAD_DEFAULT
            domStorageEnabled = true
            databaseEnabled = true
            // 关键：禁用文件访问，强制走 AssetLoader 路由
            if (MyContants.LOAD_WEB_FILE == 1) {
                setAllowFileAccess(true)
                setAllowContentAccess(true)
                setAllowFileAccessFromFileURLs(true)
                setAllowUniversalAccessFromFileURLs(true)
            } else if (MyContants.LOAD_WEB_FILE == 2) {
                setAllowFileAccess(false)
                setAllowContentAccess(false)
                setAllowFileAccessFromFileURLs(false)
                setAllowUniversalAccessFromFileURLs(false)
            }
            // 混合内容模式（若前端有 HTTP 资源，需配置；正式环境建议仅 HTTPS）
            setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW)
            // 禁用网络加载（仅加载本地资产）
//            blockNetworkLoads = true
        }
//        val url = "http://192.168.60.155:5173/"
        val websiteUrl = "http://appassets.androidplatform.net/assets/dist/index.html"

        var url = if (MyContants.LOAD_WEB_FILE == 1) {
            "file:///android_asset/dist/index.html"
//            "http://192.168.60.155:5100/#/login"
        } else {
            websiteUrl
        }

        binding.dwebview.loadUrl(url)

        binding.dwebview.webViewClient = object : WebViewClientCompat() {
            override fun shouldInterceptRequest(
                view: WebView,
                request: WebResourceRequest
            ): WebResourceResponse? {
//                var headers=request.requestHeaders
//                headers.put("Referer", "https://www.tianditu.gov.cn/")
//                headers.put("sec-ch-ua-platform", "")
//                headers.put("","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0")
                // 优先拦截虚拟域名请求
                if (MyContants.LOAD_WEB_FILE == 1) {
                    return super.shouldInterceptRequest(view, request)
                } else if (MyContants.LOAD_WEB_FILE == 2) {
                    return assetLoader.shouldInterceptRequest(request.url)
                } else {
                    return assetLoader.shouldInterceptRequest(request.url)
                }
            }

            override fun onReceivedHttpError(
                view: WebView,
                request: WebResourceRequest,
                errorResponse: WebResourceResponse
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
            }

            override fun onReceivedError(
                view: WebView,
                request: WebResourceRequest,
                error: WebResourceErrorCompat
            ) {
                super.onReceivedError(view, request, error)
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
//                super.onReceivedSslError(view, handler, error)
                handler?.cancel()
            }
        }

        binding.dwebview.webChromeClient = object : WebChromeClient() {

            override fun onConsoleMessage(message: ConsoleMessage?): Boolean {
                /*  Log.d(
                      "---onConsoleMessage ",
                      "${message?.message()} -- From line " + "${message?.lineNumber()} of ${message?.sourceId()}"
                  )*/
                return true
            }
        }

    }

    private fun initLis() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                jsApi.jsStartLoc.collect {
                    println("--------开始定位 js 调用 Android 获取位置")
                    aMapLoc.startLocation()
                }
            }
        }
        aMapLoc.myLocValue.observe(this) { myLoc ->
            var locStr =
                "${myLoc.lng} ${myLoc.lat} ${myLoc.bearing} ${myLoc.altitude}"
            println("------传给前端的： ${locStr}")
            binding.dwebview.callHandler(
                "retLoc", arrayOf<String>(locStr),
                OnReturnValue<String> { retValue ->
                    Log.d(
                        "---jsbridge",
                        "call succeed,return value is $retValue"
                    )
                })
        }

    }


/*    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) || event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
            val webView = binding.dwebview
            // 优先让WebView返回
            if (webView.canGoBack()) {
                webView.goBack()
                return true
            } else {
                return super.dispatchKeyEvent(event)
            }
        } else {
            return super.dispatchKeyEvent(event)
        }
    }*/

}