package com.xty.base.act

import android.R
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.xty.base.databinding.ActBaseTencentWebviewBinding
import com.xty.base.h5.CloudJSBridge
import com.xty.base.h5.IJsBridge
import com.xty.base.h5.WebUtils
import com.xty.base.utils.ContextUtils
import com.xty.base.vm.BaseVm
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.arouter.ARouterUrl
import org.json.JSONObject


@Route(path = ARouterUrl.H5_ACT)
 class BaseTenCentWebViewActivity: BaseVmAct<BaseVm>(),IJsBridge{

    val binding by lazy { ActBaseTencentWebviewBinding.inflate(layoutInflater) }

    var mWebSetting: WebSettings? = null

    var mUrl:String? = null

   val cloudJSBridge by lazy { CloudJSBridge(this@BaseTenCentWebViewActivity,this) }

    var isShowTitle= false
    var title:String = ""


    companion object{
        val WEB_SITE_URL = "web_site_url"
        val WEB_SITE_TITLE = "web_title"
    }

    override fun initView() {
        super.initView()
        initWebViewSettings()
        ContextUtils.init(this)
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        if (!TextUtils.isEmpty(mUrl)) {
            loadWebView(mUrl!!)
        }

        var data = Bundle()
//true表示标准全屏，false表示X5全屏；不设置默认false，
        //true表示标准全屏，false表示X5全屏；不设置默认false，
        data.putBoolean("standardFullScreen", false)
//false：关闭小窗；true：开启小窗；不设置默认true，
        //false：关闭小窗；true：开启小窗；不设置默认true，
        data.putBoolean("supportLiteWnd", false)
//1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
        //1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
        data.putInt("DefaultVideoScreen", 2)

        if (binding.webView.x5WebViewExtension != null) {
            binding.webView.x5WebViewExtension.invokeMiscMethod("setVideoParams", data)
        }

        binding.webView.addJavascriptInterface(cloudJSBridge,"business")
        val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else { LogUtils.e("CloudJSBridge","str")
            MMkvHelper.getLong(Const.USER_ID).toString()
        }

        if(intent.hasExtra("isShowTitle")){
            isShowTitle = intent.getBooleanExtra("isShowTitle",false)

        }
        if(intent.hasExtra("title")){
            title = intent.getStringExtra("title").toString()
        }
        if(isShowTitle){
            binding.title.root.visibility = View.VISIBLE

            statusBar(binding.title.mView)
            binding.title.mTvTitle.text = title
            binding.title.mIvBack.setOnClickListener {
                finish()
            }
        }else{
            binding.title.root.visibility = View.GONE
        }
    }

     override fun liveObserver() {
     }

     override fun setLayout()= binding.root


     @SuppressLint("SetJavaScriptEnabled")
     open fun initWebViewSettings() {
        mUrl = intent.getStringExtra(WEB_SITE_URL)
         LogUtils.e("BaseTenCentWebViewActivity","mUrlmUrl${mUrl}")
        mWebSetting = binding.webView.settings
        mWebSetting!!.defaultTextEncodingName = "utf-8"

         val ua: String = mWebSetting!!.getUserAgentString()
         mWebSetting!!.userAgentString = ua.replace(
             "Android",
             "Android cswldxiaomi"
         ) //设置webview的浏览器标识


         mWebSetting!!.setJavaScriptEnabled(true) //允许调用js

         mWebSetting!!.allowFileAccess = true //启用webVIew访问文件数据

         mWebSetting!!.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS

         mWebSetting!!.setSupportZoom(true) //设置支持缩放

         mWebSetting!!.builtInZoomControls = true
         mWebSetting!!.useWideViewPort = true //将图片调整到合适的webView大小

         mWebSetting!!.setSupportMultipleWindows(false) //是否支持多窗口

         mWebSetting!!.loadWithOverviewMode = true
         mWebSetting!!.setAppCacheEnabled(true) //设置是否启用缓存

         mWebSetting!!.databaseEnabled = true
         mWebSetting!!.domStorageEnabled = true
         mWebSetting!!.setGeolocationEnabled(true)

         mWebSetting!!.loadsImagesAutomatically = true //设置自动加载图片

         if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
             mWebSetting!!.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
         }
         mWebSetting!!.blockNetworkImage = false //设置是否显示网络图像，false为允许显示

         mWebSetting!!.cacheMode = WebSettings.LOAD_DEFAULT //不缓存，只从网络获取数据

         mWebSetting!!.setAppCacheMaxSize(Long.MAX_VALUE)
        // 复写shouldOverrideUrlLoading()方法，使得打开网页时不调用系统浏览器， 而是在本WebView中显示
         binding.webView.webViewClient = object : WebViewClient() {
             override  fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
                 if (url.startsWith("http:") || url.startsWith("https:")) webView.loadUrl(url) else {
                     try {
                         val uri = Uri.parse(url)
                         val intent = Intent(Intent.ACTION_VIEW, uri)
                         startActivity(intent)
                     } catch (e: Exception) {
                     }
                 }
                 return true
             }
         }

         binding.webView.webChromeClient = object : WebChromeClient() {
             override fun onProgressChanged(
                 view: WebView,
                 newProgress: Int
             ) {
                 super.onProgressChanged(view, newProgress)
             }
         }
    }
    /**
     * 加载webview
     *
     * @param webUrl
     */
    protected open fun loadWebView(webUrl: String) {
        if (webUrl.startsWith("http:") || webUrl.startsWith("https:"))
            binding.webView.loadUrl(webUrl)
        else
            binding.webView.loadUrl(
            "http://$webUrl"
        )
    }

    open fun setJsBridge(jsBridge: CloudJSBridge) {
     //   this.jsBridge = jsBridge
    }


    open fun reload() {
        binding.webView.reload()
    }


    override fun onBackPressed() {
        if (binding.webView != null) {
            if (binding.webView.canGoBack()) {
                binding.webView.goBack()
            } else {
                finish()
            }
        } else {
            finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && binding.webView.canGoBack()) {
            binding.webView.goBack() // 返回前一个webview页面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

     override fun sendDataToJS(functionName: String, data: String) {

         if (functionName.equals("reload")) {
             runOnUiThread { reload() }
         } else {
             runOnUiThread {
                 binding.webView
                     .loadUrl(
                         java.lang.String.format(
                             "javascript:%s('%s')",
                             functionName,
                             data
                         )
                     )
             }
         }
     }

    fun responseToJS(functionName: String?, data: String?) {
        runOnUiThread {
            binding.webView
                .loadUrl(String.format("javascript:%s('%s')", functionName, data))
        }
    }

     override fun switchView(name: String, data: String) {

     }
 }