package com.mints.library.widgets

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.mints.goodmoney.R

class BrowserLayout : LinearLayout {
    private var mContext: Context? = null
    private var mWebView: WebView? = null
    private var mWebTitle: TextView? = null
    private val mBarHeight = 5
    private var mProgressBar: ProgressBar? = null

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        init(context)
    }

    private fun init(context: Context) {
        mContext = context
        orientation = VERTICAL
        mProgressBar = LayoutInflater.from(context)
            .inflate(R.layout.progress_horizontal, null) as ProgressBar
        mProgressBar!!.max = 100
        mProgressBar!!.progress = 0
        addView(
            mProgressBar,
            LayoutParams.MATCH_PARENT,
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_PX,
                mBarHeight.toFloat(),
                resources.displayMetrics
            ).toInt()
        )
        mWebView = WebView(context)
        mWebView!!.settings.javaScriptEnabled = true
        mWebView!!.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        mWebView!!.settings.defaultTextEncodingName = "UTF-8"
        mWebView!!.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        mWebView!!.settings.builtInZoomControls = true
        mWebView!!.settings.setSupportMultipleWindows(true)
        //将图片调整到适合webview的大小
        mWebView!!.settings.useWideViewPort = false
        mWebView!!.settings.loadWithOverviewMode = true
        mWebView!!.settings.setSupportZoom(true)
        mWebView!!.settings.pluginState = WebSettings.PluginState.ON
        mWebView!!.settings.domStorageEnabled = true
        mWebView!!.settings.loadsImagesAutomatically = true
        mWebView!!.settings.displayZoomControls = false
        // 支持打开新窗口
        mWebView!!.settings.javaScriptCanOpenWindowsAutomatically = true
        try {
            mWebView!!.setLayerType(View.LAYER_TYPE_NONE, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //支持自动加载图片
        mWebView!!.settings.loadsImagesAutomatically = true

        //解决5.0后https地址中图片不显示的问题（图片地址为http）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView!!.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        //允许webview对文件的操作
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mWebView!!.settings.allowUniversalAccessFromFileURLs = true
            mWebView!!.settings.allowFileAccessFromFileURLs = true
        }
        mWebView!!.settings.allowFileAccess = true
        val lps =
            LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)
        addView(mWebView, lps)
        mWebView!!.setWebChromeClient(object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                if (mWebTitle != null) {
                    mWebTitle!!.text = title
                }
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    mProgressBar!!.visibility = View.GONE
                } else {
                    mProgressBar!!.visibility = View.VISIBLE
                    mProgressBar!!.progress = newProgress
                }
            }
        })
        mWebView!!.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView,
                url: String
            ): Boolean {
                if (url.startsWith("tel:")) {
                    try {
                        val intent = Intent(Intent.ACTION_DIAL, Uri.parse(url))
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        mContext!!.startActivity(intent)
                    } catch (e: Exception) {
                    }
                    return true
                }
                return super.shouldOverrideUrlLoading(view, url)
            }

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

    fun loadUrl(url: String?) {
        mWebView!!.loadUrl(url)
    }

    fun canGoBack(): Boolean {
        return if (null != mWebView) mWebView!!.canGoBack() else false
    }

    fun canGoForward(): Boolean {
        return if (null != mWebView) mWebView!!.canGoForward() else false
    }

    fun goBack() {
        if (null != mWebView) {
            mWebView!!.goBack()
        }
    }

    fun goForward() {
        if (null != mWebView) {
            mWebView!!.goForward()
        }
    }

    val webView: WebView?
        get() = if (mWebView != null) mWebView else null

    fun setWebTitle(mWebTitle: TextView?) {
        this.mWebTitle = mWebTitle
    }

    fun clearWebView() {
        if (mWebView != null) {
            val parent = mWebView!!.parent as ViewGroup
            parent?.removeView(mWebView)
            mWebView!!.removeAllViews()
            mWebView!!.destroy()
            mWebView = null
        }
    }
}