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.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.AdScanBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityWebBrowserBinding
import com.base.scanqrclear.utils.LogEx
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")
        AdsMgr.showNative(binding.flNative, R.layout.layout_ad_native_exit)
    }

    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()
        }
        onBackPressedDispatcher.addCallback {
            if (binding.webView.canGoBack()) {
                binding.webView.goBack()
            } else {
                if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                    AdsMgr.showInsert(this@WebBrowserActivity, false, object : AdsShowCallBack() {
                        override fun close(where: Int) {
                            finishToMainTop()
                        }

                        override fun failed(where: Int) {
                            finishToMainTop()
                        }

                        override fun googleFailed(where: Int) {
                            finishToMainTop()
                        }
                    })
                }
            }

        }
    }

    @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 shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
                val url = request?.url.toString()
                LogEx.logDebug(TAG, "shouldInterceptRequest url=$url")
                if (url.contains("//ads.") || url.contains("https://play.google.com")) {
                    return WebResourceResponse(null, null, null) // 拦截广告请
                }
                return super.shouldInterceptRequest(view, request)
            }


            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?) {
                val jsCode = "javascript:" +
                        "var ads = document.querySelectorAll('.ad-container');" +  // 替换为广告的CSS选择器
                        "for (var i = 0; i < ads.length; i++) {" +
                        "   ads[i].parentNode.removeChild(ads[i]);" +
                        "}"
                view?.loadUrl(jsCode)
            }

            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")
        binding.webView.swipeRefreshLayout = binding.refreshLayout
    }

}