package com.rc.core.util

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ProgressBar
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.sdk.*

/**
 * WebView + ProgressBar帮助类
 *
 * @author ReiChin_
 */
class WebViewHelper(private val webView: WebView,
                    private val progressBar: ProgressBar) {

    private val mProgressHelper by lazy { ProgressHelper(progressBar) }

    @SuppressLint("SetJavaScriptEnabled")
    fun initWebView(webViewClientProxy: WebViewClient? = null,
                    webChromeClientProxy: WebChromeClient? = null) {
        webView.settings.apply {
            // 为拍照而加
            allowContentAccess = true
            allowFileAccess = true
            setAllowFileAccessFromFileURLs(true)
            setAllowUniversalAccessFromFileURLs(true)
            loadWithOverviewMode = true

            defaultTextEncodingName = "utf-8"

            setSupportZoom(true)

            // 设置是否支持执行JS，如果设置为true会存在XSS攻击风险
            javaScriptEnabled = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                safeBrowsingEnabled = false
            }

            useWideViewPort = true
            // 安全考虑，防止密码泄漏，尤其是root过的手机
            savePassword = false
            userAgentString = "${userAgentString}; MYAPP"
            layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
            // 最重要的方法，一定要设置，这就是出不来的主要原因
            domStorageEnabled = true

//            databaseEnabled = true
//            setGeolocationEnabled(true)
//            javaScriptCanOpenWindowsAutomatically = true
            cacheMode = WebSettings.LOAD_NO_CACHE
        }

        webView.apply {
            scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
            // 水平不显示
            isHorizontalScrollBarEnabled = false
            // 垂直不显示
            isVerticalScrollBarEnabled = false
            webViewClient = MyWebViewClient(progressBar, webView, webViewClientProxy)
            webChromeClient = MyWebChromeClient(mProgressHelper, webChromeClientProxy)
        }
    }

    private class ProgressHelper(val progressBar: ProgressBar) {

        private val animator: ValueAnimator = ValueAnimator()

        init {
            animator.duration = 500
            animator.interpolator = AccelerateDecelerateInterpolator()
            animator.addUpdateListener { animation ->
                val value = animation.animatedValue as Int
                progressBar.progress = value
                if (value >= 99)
                    progressBar.visibility = View.GONE
                else
                    progressBar.visibility = View.VISIBLE
            }
        }

        fun setProgress(progress: Int) {
            if (progressBar.progress > progress) {
                animator.cancel()
                progressBar.progress = 0
            }
            if (!animator.isRunning) {
                animator.setIntValues(progressBar.progress, progress)
                animator.start()
            } else {
                val value = animator.animatedValue as Int
                animator.cancel()
                animator.setIntValues(value, progress)
                animator.start()
            }
        }
    }

    private class MyWebViewClient(val progressBar: ProgressBar,
                                  val webView: WebView,
                                  val proxy: WebViewClient? = null) : WebViewClient() {

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

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            return proxy?.shouldOverrideUrlLoading(view, request?.url.toString())
                    ?: super.shouldOverrideUrlLoading(view, request)
        }

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
            handler?.proceed()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                webView.settings.mixedContentMode = 0/*android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW*/
            }
        }

    }

    private class MyWebChromeClient(val progressHelper: ProgressHelper,
                                    val proxy: WebChromeClient? = null) : WebChromeClient() {

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            progressHelper.setProgress(newProgress)
        }

        override fun onShowCustomView(view: View?, callback: IX5WebChromeClient.CustomViewCallback?) {
            super.onShowCustomView(view, callback)
            proxy?.onShowCustomView(view, callback)
        }

        override fun onHideCustomView() {
            super.onHideCustomView()
            proxy?.onHideCustomView()
        }

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

}