package cn.yyxx.eyuangame.core.impl.center

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl
import cn.yyxx.support.AndroidBug5497Workaround
import cn.yyxx.support.ResUtils
import cn.yyxx.support.device.DeviceInfoUtils

/**
 * @author #Suyghur.
 * Created on 2021/07/02
 */
class HybridActivity : Activity() {

    private lateinit var ivReturn: ImageView
    private lateinit var tvTitle: TextView
    private lateinit var webView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
        initWebView()
    }

    private fun initView() {
        if (SdkBridgeImpl.isLand) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        }
        setContentView(ResUtils.getResId(this, "yyxx_hybrid", "layout"))

        if (!SdkBridgeImpl.isLand) {
            AndroidBug5497Workaround.assistActivity(this)
        }

        tvTitle = findViewById(ResUtils.getResId(this, "yyxx_tv_title", "id"))
        ivReturn = findViewById(ResUtils.getResId(this, "yyxx_iv_return", "id"))
    }


    private fun initWebView() {
        webView = WebView(this)
        webView.isVerticalScrollBarEnabled = true
        webView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
//        webView.addJavascriptInterface(SdkJsImpl(this, callback), "FlyFunSdk")
        val container = findViewById<FrameLayout>(ResUtils.getResId(this, "yyxx_webview_container", "id"))
        container.addView(webView)

//        webView.viewTreeObserver.addOnGlobalLayoutListener {
//            if (isSoftShowing()) {
//                view.visibility = View.GONE
//            } else {
//                view.visibility = View.VISIBLE
//            }
//        }

        val webSetting = webView.settings
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.saveFormData = true
        webSetting.savePassword = true
        webSetting.builtInZoomControls = false
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(false)
        webSetting.setAppCacheEnabled(false)
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        webSetting.setAppCachePath(getDir("appcache", 0).path)
        webSetting.databasePath = getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(getDir("geolocation", 0).path)
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()

        if (DeviceInfoUtils.isNetworkConnected(this)) {
            webView.loadUrl(url)
            //webView.loadUrl("file:///android_asset/test.html");
        } else {
            //这种写法可以正确解码
            webView.loadData("网络异常,请检查重试", "text/html; charset=UTF-8", null)
        }

        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
//                if (view.canGoBack() && Uri.parse(url).path != "/index.html") {
//                    ivReturn.visibility = View.VISIBLE
//                } else {
//                    ivReturn.visibility = View.GONE
//                }
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                val hitTestResult = view.hitTestResult
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    //解决重定向加载的问题 return false
                    if (!view.canGoBack()) {
                        return false
                    }
                    //解决重定向加载的问题 return false
                    if (hitTestResult.type == WebView.HitTestResult.UNKNOWN_TYPE) {
                        return false
                    }
                    view.loadUrl(url)
                }
                return false
            }

            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                //部分手机浏览器不支持https，所以此处需要接受证书
//                handler.proceed()
//                showSslErrorDialog(handler)

            }
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                //progressWebView.setProgressBarProgress(newProgress);
//                if (newProgress == 100 && loadingDialog != null && loadingDialog!!.isShowing) {
//                    //加载完成,关闭loading
//                    loadingDialog!!.dismiss()
//                }
            }

            //For Android > 5.0
            override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
//                openFileChooserImplForAndroid5(filePathCallback)
                return true
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                if (!DeviceInfoUtils.isNetworkConnected(view.context)) {
                    tvTitle.text = "网络异常"
                    return
                }
                if (!TextUtils.isEmpty(view.title)) {
                    var viewtitle = view.title
                    if (viewtitle!!.length > 10) {
                        viewtitle = viewtitle.substring(0, 10)
                        viewtitle = "$viewtitle..."
                    }
                    tvTitle.text = viewtitle
                }
            }
        }
    }

    companion object {

        private var url = ""

        fun start(activity: Activity, url: String) {
            Companion.url = url
            activity.startActivity(Intent(activity, HybridActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }


    }
}