package com.rdiot.yx485.ui.web

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import com.gyf.immersionbar.ktx.immersionBar
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.databinding.ActWebBinding

/**
 *
 * @author mR2hao
 * @date 2022/12/28
 */
class WebActivity : BaseActivity<ActWebBinding>() {
    private lateinit var webUrl: String
    private lateinit var title: String
    override fun getLayoutId() = R.layout.act_web
    private var isError = false

    companion object {
        private const val WEB_URL = "webUrl"
        private const val TITLE = "title"

        fun getNewWebIntent(context: Context, url: String, title: String): Intent {
            val intent = Intent(context, WebActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            intent.putExtra(WEB_URL, url)
            intent.putExtra(TITLE, title)
            return intent
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarView(binding.v)
            statusBarColor(R.color.white)
            navigationBarColor(R.color.white)
            statusBarDarkFont(true)
        }

        webUrl = intent.getStringExtra(WEB_URL) ?: ""
        title = intent.getStringExtra(TITLE) ?: ""
        binding.nb.setTitle(title)
        binding.nb.setLeftClickListener {
            if (binding.wv.canGoBack()) {
                binding.wv.goBack()
            } else {
                finish()
            }
        }
        initWebView()
    }

    private fun initWebView() {
        binding.wv.apply {
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView?,
                    request: WebResourceRequest
                ): Boolean {
                    return true
                }

                override fun onPageFinished(webView: WebView?, s: String?) {
                    super.onPageFinished(webView, s)
                    //如果有问题，会先执行error，
                    if (isError) {
                        binding.wv.visibility = View.GONE
                        binding.bridgeLayoutMainGif.visibility = View.GONE
                    } else {
                        binding.wv.visibility = View.VISIBLE
                        binding.bridgeLayoutMainGif.visibility = View.GONE
                    }
                }

                override fun onReceivedError(
                    webView: WebView?,
                    webResourceRequest: WebResourceRequest,
                    webResourceError: WebResourceError?
                ) {
                    super.onReceivedError(webView, webResourceRequest, webResourceError)
                    if (webResourceRequest.isForMainFrame) {
                        //加载失败后，需要设置isLoadSuccess为false
                        isError = true
                    }
                }
            }
            webChromeClient = object : WebChromeClient() {
                override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                    LogUtils.d("consoleMessage:${consoleMessage?.message().toString()}")
                    return super.onConsoleMessage(consoleMessage)
                }

                override fun onReceivedTitle(view: WebView?, title: String?) {
                    super.onReceivedTitle(view, title)
                }
            }
            val userAgent = settings.userAgentString

            settings.apply {
                javaScriptEnabled = true
                useWideViewPort = true
                loadWithOverviewMode = false
                userAgentString = "$userAgent yongxulvjian/1.0.0"
                javaScriptCanOpenWindowsAutomatically =
                    true//JavaScript 可以自动打开新窗口，这是通过使用 window.open() 方法实现的
                allowFileAccess = true //当设置为true,就可以 使用file://加载文件
                setSupportMultipleWindows(true)
                allowUniversalAccessFromFileURLs = true//允许跨域
                mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
                pluginState = WebSettings.PluginState.ON
                domStorageEnabled = true
                cacheMode = LOAD_NO_CACHE
            }
            if (BuildConfig.DEBUG) {
                WebView.setWebContentsDebuggingEnabled(true)
            }
        }
        binding.wv.loadUrl(webUrl)
    }


    /**
     * 设置点击返回按钮，跳转到上一个html页面，而不是退出当前activity
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            if (binding.wv.canGoBack()) {
                //获取webView的浏览记录
                val mWebBackForwardList: WebBackForwardList = binding.wv.copyBackForwardList()
                //这里的判断是为了让页面在有上一个页面的情况下，跳转到上一个html页面，而不是退出当前activity
                if (mWebBackForwardList.currentIndex > 0) {
                    val historyUrl: String =
                        mWebBackForwardList.getItemAtIndex(mWebBackForwardList.currentIndex - 1)
                            .url
                    if (historyUrl != webUrl) {
                        binding.wv.goBack()
                        return true
                    }
                }
            } else {
                return super.onKeyDown(keyCode, event)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onBackPressed() {
        if (binding.wv.canGoBack()) {
            binding.wv.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.wv.loadUrl("about:blank")
        binding.wv.destroy()
    }
}