package com.zxhl.cms.common

import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.util.Log
import android.view.View
import android.webkit.SslErrorHandler
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.zxhl.cms.R
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.utils.FileUtils
import kotlinx.android.synthetic.main.activity_h5.*
import kotlinx.android.synthetic.main.activity_web.*
import kotlinx.android.synthetic.main.activity_web.id_activity_web_title
import kotlinx.android.synthetic.main.activity_web.id_activity_web_toolbar
import kotlinx.android.synthetic.main.activity_web.id_activity_web_view


class WebActivity : BaseActivity() {
    private var chromeClient: PaxWebChromeClient? = null

    override fun onClick(p0: View?) {

    }

    override fun layoutID(): Int = R.layout.activity_web

    override fun init() {
        id_activity_web_toolbar?.setNavigationOnClickListener { finish() }
        val title = intent?.data?.getQueryParameter("title") ?: ""
        val url = intent?.data?.getQueryParameter("url") ?: ""
        Log.e("MXL", "url" + url)

        initWebView()
        id_activity_web_title?.text = title

        id_activity_web_view?.loadUrl(url)

    }


    private fun initWebView() {
        val settings = id_activity_web_view?.settings
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings?.mediaPlaybackRequiresUserGesture = true//设置视频不自动播放
        }
        chromeClient = PaxWebChromeClient(this) {
            if(it==100){
                id_web_view_progress_view.visibility = View.GONE
            }else{
                id_web_view_progress_view.visibility = View.VISIBLE
                id_web_view_progress_view.progress = it
            }
        }
        settings?.javaScriptCanOpenWindowsAutomatically = true//支持js自动弹框
        settings?.setSupportZoom(true) //支持缩放
        settings?.setNeedInitialFocus(false)
        settings?.allowFileAccess = true
        settings?.setRenderPriority(WebSettings.RenderPriority.HIGH)
        settings?.builtInZoomControls = true//支持手势缩放
        settings?.displayZoomControls = false //是否显示缩放按钮
        // >= 19(SDK4.4)启动硬件加速，否则启动软件加速
        settings?.loadsImagesAutomatically = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
        settings?.useWideViewPort = true //设置内容自适应屏幕大小
        settings?.loadWithOverviewMode = true
        settings?.saveFormData = true
        settings?.cacheMode = WebSettings.LOAD_NO_CACHE
        settings?.setEnableSmoothTransition(true)
        settings?.setSupportMultipleWindows(false)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings?.mediaPlaybackRequiresUserGesture = false
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true)
        }
        // support android API 7-
        try {
            // API 7, LocalStorage/SessionStorage
            settings?.domStorageEnabled = true
            settings?.databaseEnabled = true
            settings?.databasePath = FileUtils.getWebViewCacheDiectory()
            // API 7， Web SQL Database, 需要重载方法（WebChromeClient）才能生效，无法只通过反射实现
        } catch (e: Exception) {
        }


        try {
            // API 7， Application Storage
            settings?.setAppCacheEnabled(true)
            settings?.setAppCachePath(FileUtils.getWebViewCacheDiectory())
            settings?.setAppCacheMaxSize(5 * 1024 * 1024)
        } catch (e: Exception) {
        }
        try {
            // API 5， Geolocation
            settings?.setGeolocationEnabled(true)
            settings?.setGeolocationDatabasePath(FileUtils.getWebViewCacheDiectory())
        } catch (e: Exception) {
        }



        id_activity_web_view?.isHorizontalScrollBarEnabled = false
        id_activity_web_view?.overScrollMode = View.OVER_SCROLL_NEVER // 取消WebView中滚动或拖动到顶部、底部时的阴影
        id_activity_web_view?.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
//        settings.userAgentString = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; zh-tw) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16"
        //注意：以下两项是必须设置，其他设置选项根据自身项目需求进行配置
        settings?.javaScriptEnabled = true


        id_activity_web_view?.webChromeClient = chromeClient


        id_activity_web_view?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(wv: WebView, url: String?): Boolean {
                Log.e("MXL","AURL"+url)
                if (url == null) return false
                try {
                    if (url.startsWith("weixin://") //微信
                        || url.startsWith("alipays://") //支付宝
                        || url.startsWith("mailto://") //邮件
                        || url.startsWith("tel://") //电话
                        || url.startsWith("dianping://") //大众点评
                        || url.startsWith("tbopen://") //淘宝
                        || url.startsWith("openapp.jdmobile://") //京东
                        || url.startsWith("tmast://") //淘宝
                        || url.startsWith("pinduoduo://") //拼多多
                        || url.startsWith("imeituan://") //美团
                    //其他自定义的scheme
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                        return true
                    }
                } catch (e: java.lang.Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true //没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }

                //处理http和https开头的url
                wv.loadUrl(url)
                return true
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler,
                error: SslError?
            ) {
                handler.proceed()
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        chromeClient?.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data)
    }


}
