package com.swiftcleaner.chovey.view.function.constellation

import android.annotation.SuppressLint
import android.app.Activity
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.OnBackPressedCallback
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.ads.nativead.NativeAd
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.business.admob.AdmobManager
import com.swiftcleaner.chovey.databinding.ActivityWebBrowserBinding
import com.swiftcleaner.chovey.model.util.FinishMain
import com.swiftcleaner.chovey.view.BaseActivityKotlin
import com.swiftcleaner.chovey.view.dialog.CustomScoreDialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class WebBrowserActivity : BaseActivityKotlin<ActivityWebBrowserBinding>() {
    override val binding: ActivityWebBrowserBinding by lazy {
        ActivityWebBrowserBinding.inflate(layoutInflater)
    }

    override fun initView() {
        initWebSettings()
        binding.webView.loadUrl("https://www.horoscope.com/us/index.aspx")
        AdmobManager.showNativeAd(this@WebBrowserActivity, { nativeAd: NativeAd? ->
            binding.idFlNative.removeAllViews()
            nativeAd?.let { binding.idFlNative.setNativeAd(it, R.layout.layout_ad_native) }
            null
        }, null, null)
    }

    override fun initListener() {
        super.initListener()
        binding.idBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.refreshLayout.setOnRefreshListener {
            lifecycleScope.launch {
                binding.refreshLayout.isRefreshing = true
                delay(Random.nextLong(1500, 2500))
                binding.refreshLayout.isRefreshing = false
            }
            binding.webView.reload()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                initCustDialog()
            }
        })
    }
    private fun initCustDialog() {
        val activity: Activity = this
        val customScoreDialog = CustomScoreDialog(this)
        customScoreDialog.setOnDialogClickListener(object :
            CustomScoreDialog.OnDialogClickListener {
            override fun onCancel() {
                customScoreDialog.dismiss()
            }

            override fun onSubmit() {
                if (AdmobManager.isShowAdBackInter()) {
                    AdmobManager.showInterstitialAd(
                        this@WebBrowserActivity, {
                            FinishMain.finishToMain(activity)
                            null
                        },
                        { null },
                        {
                            FinishMain.finishToMain(activity)
                            null
                        }, false
                    )
                } else {
                    FinishMain.finishToMain(activity)
                }
            }
        })
        customScoreDialog.show()
    }
    @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
    }

}