package com.base.scanqrclear.ui.webview

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.view.View
import android.webkit.CookieManager
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.lifecycleScope
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.databinding.ActivityWebBrowserBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random


class WebBrowserActivity : BaseActivity<ActivityWebBrowserBinding>(ActivityWebBrowserBinding::inflate) {

    override fun initView() {
        super.initView()
        initWebSettings()

        binding.webView.loadUrl("https://www.horoscope.com/us/index.aspx")
    }

    override fun initListener() {
        super.initListener()

        binding.refreshLayout.setOnRefreshListener {
            lifecycleScope.launch {
                binding.refreshLayout.isRefreshing = true
                delay(Random.nextLong(1500, 2500))
                binding.refreshLayout.isRefreshing = false
            }
            binding.webView.reload()
        }
    }

    @SuppressLint("JavascriptInterface")
    private fun initWebSettings() {

        val webSettings = binding.webView.settings
        webSettings.allowFileAccess = true// 设置允许访问文件数据
        webSettings.setSupportZoom(false)
        webSettings.builtInZoomControls = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true
        @Suppress("DEPRECATION")
        webSettings.allowFileAccessFromFileURLs = true
        WebStorage.getInstance().deleteAllData()

        // 关键性代码，这里要给webView添加这行代码，才可以点击之后正常播放音频。记录一下。
        webSettings.mediaPlaybackRequiresUserGesture = false

        //设置WebView属性，能够执行Javascript脚本
        webSettings.javaScriptEnabled = true

        //设置混合内容模式：对于HTTPS和HTTP混合内容的加载，需要设置WebView以允许混合内容：
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        //使用CookieManager设置允许跨域Cookie
        CookieManager.getInstance().setAcceptThirdPartyCookies(binding.webView, true)

        //适应屏幕设置
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true

        //网页使用localStorage等Web存储API，需要启用DOM存储
        webSettings.domStorageEnabled = true
        webSettings.setUseWideViewPort(false)
        webSettings.setLoadsImagesAutomatically(true) // 确保自动加载图片

        //设置WebChromeClient
        binding.webView.webChromeClient = object : WebChromeClient() {

            override fun onProgressChanged(view: WebView, newProgress: Int) {

                binding.progressBar.progress = newProgress
                if (binding.progressBar.progress >= 100) {
                    binding.progressBar.visibility = View.GONE
                }
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
            }

            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>,
                fileChooserParams: FileChooserParams?
            ): Boolean {
                return true
            }

            override fun onJsAlert(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean = true
        }

        binding.webView.webViewClient = object : WebViewClient() {


            override fun onLoadResource(view: WebView?, url: String?) {
                super.onLoadResource(view, url)
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                if (request != null) {
                    val uri = request.url
                    val scheme = uri.scheme
                    // 检查 URL 是否是 scheme 类型
                    if (scheme != null && (scheme == "http" || scheme == "https")) {
                    } else {
                        val intent = Intent(Intent.ACTION_VIEW, uri)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        if (packageManager != null && intent.resolveActivity(packageManager) != null) {
                            startActivity(intent)
                        }
                        return true // 返回 true，表示 URL 已经被处理
                    }
                    return super.shouldOverrideUrlLoading(view, request)
                }
                return false
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
            }

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

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

        //设置Cookie
        val instance = CookieManager.getInstance()
        instance.setAcceptThirdPartyCookies(binding.webView, true)
        binding.webView.addJavascriptInterface(this, "android")

    }

}