package com.yidian.shenghuoquan.newscontent.ui.auth

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import com.orhanobut.hawk.Hawk
import com.yidian.common.AppConfig
import com.yidian.common.HawkConfig
import com.yidian.common.XEventConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.constant.Constant
import com.yidian.shenghuoquan.newscontent.databinding.ActivityLifeAccountPersonalAuthBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.callback.IAuthPersonalCompleteCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthAuthenticationBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthPersonalCompleteBean
import com.yidian.shenghuoquan.newscontent.ui.ProtocolActivity
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * author: yinjiacheng
 * date: 5/26/21 7:38 PM
 * description: 生活号个人认证
 */
class LifeAccountPersonalAuthActivity :
  BaseActivity<ActivityLifeAccountPersonalAuthBinding>(),
  View.OnClickListener, CompoundButton.OnCheckedChangeListener, IAuthPersonalCompleteCallback {

  companion object {
    // 认证数据
    const val EXTRA_AUTH_DATA = "authData"
  }

  /**
   * 当前fragment
   */
  private val fragment by lazy { LifeAccountIDCardAuthFragment() }

  /**
   * 认证数据 还原认证流程用
   */
  private val authData by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      (it as HashMap<*, *>)[EXTRA_AUTH_DATA]?.let { data ->
        data as AuthAuthenticationBean.Response
      }
    }
  }

  override fun createViewBinding(): ActivityLifeAccountPersonalAuthBinding {
    return ActivityLifeAccountPersonalAuthBinding.inflate(layoutInflater)
  }

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

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    XEventManager.register(this)
    initView()
    initListener()
    initData()
  }

  private fun initView() {

  }

  private fun initListener() {
    viewBind.svOccupation.setOnClickListener(this)
    viewBind.cbProtocol.setOnCheckedChangeListener(this)
    viewBind.btnNext.setOnClickListener(this)
    viewBind.tvPrivacyCertification.setOnClickListener(this)
    viewBind.tvUserAgreement.setOnClickListener(this)
  }

  private fun initData() {
    // 如果有已存在的认证流程则还原进度
    authData?.let { LifeAccountAuthDataManager.generatePersonalAuthData(it) }
    authData?.occupation?.let { viewBind.svOccupation.setContentResult(it) }
    val bundle = Bundle()
    bundle.putSerializable(LifeAccountIDCardAuthFragment.EXTRA_AUTH_DATA, authData)
    fragment.arguments = bundle
    supportFragmentManager.beginTransaction()
      .add(R.id.fragment_container, fragment).commit()
  }

  /**
   * 检查是否可以进行下一步
   */
  fun checkNextCondition() {
    if (viewBind.cbProtocol.isChecked
      && !LifeAccountAuthDataManager.personalAuthData.occupation.isNullOrEmpty()
      && LifeAccountAuthDataManager.personalAuthData.isFaceAuthPass
    ) {
      viewBind.btnNext.alpha = 1f
      viewBind.btnNext.isEnabled = true
    } else {
      viewBind.btnNext.alpha = 0.32f
      viewBind.btnNext.isEnabled = false
    }
  }

  /**
   * 禁止修改职业标签 用于人脸验证通过后
   */
  fun disableModifyOccupation() {
    viewBind.svOccupation.enableSelect(false)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.sv_occupation -> {
        XPageManager.push(XRouterPathConstants.CHOOSE_CAREER, null)
      }
      R.id.btn_next -> {
        // 个人认证 完成认证
        val requestParams = HashMap<String, String?>()
        requestParams["mobile"] = Hawk.get(HawkConfig.Mobile, "")
        ApiService.authComplete(
          this,
          requestParams
        )
      }

      R.id.tv_privacy_certification -> {
        val urlMap = HashMap<String, String>()
        urlMap[ProtocolActivity.ProtocolUrlKey] = AppConfig.privacyPolicyStatement
        XPageManager.push(XRouterPathConstants.PROTOCOL, urlMap)
      }


      R.id.tv_user_agreement -> {
        val urlMap = HashMap<String, String>()
        urlMap[ProtocolActivity.ProtocolUrlKey] = AppConfig.userProtocol
        XPageManager.push(XRouterPathConstants.PROTOCOL, urlMap)
      }
    }
  }

  override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
    if (buttonView?.isPressed == false) return
    checkNextCondition()
  }

  override fun authPersonalCompleteSuccess(result: AuthPersonalCompleteBean.Response?) {
    // 本地保存生活号id
    StorageUtil.putLifeAccountId(result?.life_account_id)
    // 跳转个人认证成功页
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_PERSONAL_AUTH_COMPLETE,
      hashMapOf(
        Pair(
          LifeAccountPersonalAuthCompleteActivity.OCCUPATION,
          LifeAccountAuthDataManager.personalAuthData.occupation
        ),
        Pair(
          LifeAccountPersonalAuthCompleteActivity.PHONE_NUM,
          Hawk.get(HawkConfig.Mobile, "")
        ),
        Pair(
          LifeAccountPersonalAuthCompleteActivity.REAL_NAME,
          LifeAccountAuthDataManager.personalAuthData.realName
        ),
        Pair(
          LifeAccountPersonalAuthCompleteActivity.ID_CARD_NUM,
          LifeAccountAuthDataManager.personalAuthData.idCardNum
        ),
        Pair(
          LifeAccountPersonalAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID,
          result?.life_account_id
        )
      )
    )
    XPageManager.pop(null)
  }

  override fun authPersonalCompleteFailure(message: String?) {
    Log.e(
      Constant.LIFE_ACCOUNT_AUTH_TAG,
      "request auth complete failure: message: $message"
    )
  }

  override fun onDestroy() {
    super.onDestroy()
    XEventManager.unRegister(this)
  }


  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.CHOOSE_CAREER -> {
        val selectedCareer = event.body as String
        LifeAccountAuthDataManager.personalAuthData.occupation = selectedCareer
        viewBind.svOccupation.setContentResult(selectedCareer)
        checkNextCondition()
      }
    }
  }

}
