package com.base.browserwhite.ui.fragment

import android.annotation.SuppressLint
import android.net.Uri
import android.webkit.CookieManager
import android.webkit.JsResult
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewClient
import com.base.browserwhite.databinding.FragmentWebViewBinding

class WebViewFragment(val uri: String) : BaseFragment<FragmentWebViewBinding>() {


    override val binding: FragmentWebViewBinding by lazy {
        FragmentWebViewBinding.inflate(layoutInflater)
    }

    var onPageFinished: ((uri:String?) -> Unit)? = null


    override fun setView() {
        initWebSettings()
        binding.webView.loadUrl(uri)
    }

    override fun setListener() {
        super.setListener()


    }

    @SuppressLint("SetJavaScriptEnabled")
    fun initWebSettings() {
//        binding.webView.isFocusableInTouchMode = true
//        binding.webView.isFocusable = true

        val webSettings = binding.webView.settings
        webSettings.allowFileAccess = true// 设置允许访问文件数据
        webSettings.setSupportZoom(true)
        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
//        Android13后不支持
//        webSettings.setAppCacheEnabled(false)

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

        //设置WebChromeClient
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
            }

            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 shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                val url = request?.url.toString()
                view?.loadUrl(url)
                return true
            }

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

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

    }


    fun canGoBack(): Boolean {
        return binding.webView.canGoBack()
    }

    fun canGoForward(): Boolean {
        return binding.webView.canGoForward()
    }

    fun goBack() {
        return binding.webView.goBack()
    }

    fun goForward() {
        return binding.webView.goForward()
    }


    fun javascriptBack() {
        binding.webView.evaluateJavascript("window.history.back();", null)
    }

}