package com.yidian.common.webview

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

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)
        }
      }
    }
  }

//  override fun onDestroy() {
//    super.onDestroy()
//    binding.webView.destroy()
//  }
}
