package com.yidian.shenghuoquan.bxbirdbusiness.ui

import android.content.Intent
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.pingplusplus.android.Pingpp
import com.pingplusplus.android.Pingpp.REQUEST_CODE_PAYMENT
import com.yidian.bcommon.constant.XBirdPageConstants
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.extensions.setBgColor
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.bcommon.widget.CommonHintDialog
import com.yidian.shenghuoquan.bxbirdbusiness.R
import com.yidian.shenghuoquan.bxbirdbusiness.databinding.XbridActivityCommonWebViewBinding
import com.yidian.xarc.xbrid.XBridManager
import com.yidian.xarc.xbrid.XWebView
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.xpage.XPageManager
import com.yidian.xpage.XPageViewProtocol
import timber.log.Timber
import kotlin.isInitialized as isInitialized1


/**
 * 通用的WebView
 */
class CommonWebViewActivity : BaseMvvmActivity<XbridActivityCommonWebViewBinding, CommonWebViewModel>(), XPageViewProtocol {

  private lateinit var webView: XWebView
  private lateinit var url: String

  override val layoutId: Int = R.layout.xbrid_activity_common_web_view

  override val vm: CommonWebViewModel by viewModels()

  override fun getXPageName(): String {
    return XRouterPathConstants.COMMON_WEB_VIEW_ACTIVITY
  }

  override fun initView() {
    val serializableExtra = intent.getSerializableExtra(XRouterPathConstants.ParamsKey)
    if (serializableExtra == null) {
      // 提示页面必须传参才能进入
      ToastUtils.showShortSafe("需要传递pageUrl")
    } else {
      val paramsMap = serializableExtra as HashMap<*, *>
      val webViewUrl = paramsMap[XBirdPageConstants.PAGE_URL] as String?
      if (webViewUrl.isNullOrBlank()) {
        ToastUtils.showShortSafe("pageUrl不能为空")
        return
      }
      url = webViewUrl
      Timber.e("页面的URL ： $webViewUrl")
      initPublishCommodityWebView(webViewUrl)
    }
  }

  /**
   * 初始化发布商品页面
   */
  private fun initPublishCommodityWebView(webViewUrl: String) {
    webView = XBridManager.getWebView(this, "testidenfier", binding.commonWebView)
    webView.loadUrl(webViewUrl)
    Timber.tag("CommonWebView").e(" 请求地址： $webViewUrl")
    webView.webChromeClient = object : WebChromeClient() {

      override fun onReceivedTitle(view: WebView?, title: String?) {
        super.onReceivedTitle(view, title)
        if (!title.isNullOrBlank()) {
          Timber.tag("CommonWebView").e(" 页面title： $title")
          initPageTitle(title)
        }
      }

      override fun onProgressChanged(view: WebView?, newProgress: Int) {
        super.onProgressChanged(view, newProgress)
        if (newProgress == 100) {
          Timber.tag("CommonWebView").e(" CommonWebView 页面加载完成")
        }
      }
    }
    WebView.setWebContentsDebuggingEnabled(true)
  }

  private fun initPageTitle(title: String) {
    when (getCurrentPageName()) {
      XBirdPageConstants.FIGHT_ORDER_HOME_PAGE -> {
        binding.commonTopBar.setTitleTextColor(ContextCompat.getColor(this, R.color.white))
        binding.commonTopBar.setBackImageResource(R.drawable.icon_back_white)
        binding.commonTopBar.setStatusBarColor(ContextCompat.getColor(this, R.color.color_FD7823))
        binding.commonTopBar.setBgColor(R.color.color_FD7823)
      }
      else -> {
        binding.commonTopBar.setTitleTextColor(ContextCompat.getColor(this, R.color.color_333333))
        binding.commonTopBar.setBackImageResource(R.drawable.icon_back)
        binding.commonTopBar.setBgColor(R.color.transparent)
      }
    }
    binding.commonTopBar.setTitle(title)
  }

  override fun onDestroy() {
    super.onDestroy()
    if (::webView.isInitialized1) {
      XBridManager.backWebView(webView)
    }
  }

  override fun onBackPressed() {
    when (getCurrentPageName()) {
      XBirdPageConstants.COMMODITY_PUBLISH_COMMODITY -> {
        CommonHintDialog(this, "返回后，商品信息不会保存", arrayListOf("取消", "返回"), object : CommonHintDialog.OnHintOptionCallback {
          override fun onLeftOption() {

          }

          override fun onRightOption() {
            XPageManager.pop(null)
          }

        }, R.color.color_8F000000, R.color.color_FF3A3A).show()
      }
      else -> {
        super.onBackPressed()
      }
    }
  }

  /**
   * 获取当前加载页面的名称
   */
  private fun getCurrentPageName(): String? {
    return XBridManager.getXBridPageName(url)
  }

  companion object {
    var resolver: ResultResolver? = null
    val context by lazy { this }

    /**
     * 在H5页面调起支付
     */
    fun transferPayment(charge: String, resolver: ResultResolver) {
      this.resolver = resolver
      Pingpp.createPayment(this, charge)
    }
  }


  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    //支付页面返回处理
    if (requestCode == REQUEST_CODE_PAYMENT) {
      if (resultCode == RESULT_OK) {
        val result = data?.extras?.getString("pay_result")
        /* 处理返回值
         * "success" - 支付成功
         * "fail"    - 支付失败
         * "cancel"  - 取消支付
         * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
         * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
         */
        val errorMsg = data?.extras?.getString("error_msg") // 错误信息
        val extraMsg = data?.extras?.getString("extra_msg") // 错误信息
        resolver?.success(result)
      }
    }
  }

}
