package com.yidian.bcommon.webview

import android.content.Context
import android.content.Intent
import android.os.Build
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.viewModels
import com.yidian.bcommon.R
import com.yidian.bcommon.databinding.ActivityPublicWebViewBinding
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.mvvm.BaseMvvmActivity

/**
 * 公共的WebView
 */
class PublicWebViewActivity : BaseMvvmActivity<ActivityPublicWebViewBinding, PublicWebViewModel>() {

  override val layoutId: Int = R.layout.activity_public_web_view

  override val vm: PublicWebViewModel by viewModels()

  override fun initView() {
    val url = intent?.getStringExtra("url")
    initTitleBar(binding.toolbar, binding.tvTitle, "声明")
    initWebView(binding.webView)
    binding.webView.loadUrl(url)
  }

  private fun initWebView(webView: WebView) {
    // webView设置
    webView.settings.apply {
      // 允许使用js
      javaScriptEnabled = true
      // 支持屏幕缩放
//      setSupportZoom(true)
//      builtInZoomControls = true
      // 缓存模式，不使用缓存
      cacheMode = WebSettings.LOAD_NO_CACHE
      // 支持混合模式
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
      }
    }
    webView.webChromeClient = object : WebChromeClient() {

      override fun onReceivedTitle(view: WebView?, title: String?) {
        super.onReceivedTitle(view, title)
        if (!title.isNullOrBlank()) {
          initTitleBar(binding.toolbar, binding.tvTitle, title)
        }
      }
    }
  }

  companion object {
    fun startWebViewActivity(context: Context, url: String) {
      val intent = Intent(context, PublicWebViewActivity::class.java)
      intent.putExtra("url", url)
      context.startActivity(intent)
    }
  }

}
