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

import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.HawkConfig
import com.yidian.bcommon.XEventConfig
import com.yidian.bcommon.XRouterPathConstants
import com.yidian.bcommon.base.BaseActivity
import com.yidian.shenghuoquan.newscontent.R
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.callback.IUserLogoutCallBack
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthAuthenticationBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthPersonalCompleteBean
import com.yidian.shenghuoquan.newscontent.ui.dialog.HintDialog
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.shenghuoquan.newscontent.widget.CommonTopBarView
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, HintDialog.OnHintOptionCallback, IUserLogoutCallBack, CommonTopBarView.OnCommonTopBarBackCallback {

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

  /**
   * 当前fragment
   */
  private lateinit var curFragment: LifeAccountIDCardAuthFragmentV2

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

  /**
   * 个人未认证的生活号升级传入
   */
  private val lifeAccountId by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let { params ->
      (params as HashMap<*, *>)[EXTRA_LIFE_ACCOUNT_ID]?.let {
        it as String
      }
    }
  }

  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.bvTopBar.setOnCommonTopBarCallback(this, null)
    viewBind.svOccupation.setOnClickListener(this)
    viewBind.tvNext.setOnClickListener(this)
  }

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

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

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

  /**
   * 清空认证数据
   * 避免在升级企业认证时出现数据异常
   */
  private fun clearLifeAccountAuthData() {
    LifeAccountAuthDataManagerV2.personalAuthData.isAgreePrivacyAgreement = false
    LifeAccountAuthDataManagerV2.personalAuthData.occupation = null
    LifeAccountAuthDataManagerV2.personalAuthData.isFaceAuthPass = false
    LifeAccountAuthDataManagerV2.personalAuthData.realName = null
    LifeAccountAuthDataManagerV2.personalAuthData.idCardNum = null
    LifeAccountAuthDataManagerV2.personalAuthData.occupation = null
    LifeAccountAuthDataManagerV2.personalAuthData.isIDCardPortraitFaceUpload = false
    LifeAccountAuthDataManagerV2.personalAuthData.isIDCardNationalEmblemFaceUpload = false
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.sv_occupation -> {
        XPageManager.push(XRouterPathConstants.CHOOSE_CAREER, null)
      }
      R.id.tv_next -> {
        // 个人认证 完成认证
        ApiService.authComplete(this, lifeAccountId?.let { hashMapOf(Pair(EXTRA_LIFE_ACCOUNT_ID, it)) } ?: hashMapOf())
      }
    }
  }

  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)
    // 清空认证数据
    clearLifeAccountAuthData()
    // 跳转个人认证成功页
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_PERSONAL_AUTH_COMPLETE,
      hashMapOf(
        Pair(LifeAccountPersonalAuthCompleteActivity.OCCUPATION, result?.occupation),
        Pair(LifeAccountPersonalAuthCompleteActivity.PHONE_NUM, Hawk.get(HawkConfig.Mobile, "")),
        Pair(LifeAccountPersonalAuthCompleteActivity.REAL_NAME, result?.full_name),
        Pair(LifeAccountPersonalAuthCompleteActivity.ID_CARD_NUM, result?.id_card),
        Pair(LifeAccountPersonalAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID, result?.life_account_id),
        Pair(LifeAccountPersonalAuthCompleteActivity.LIFE_ACCOUNT_NAME, result?.life_account_name)
      )
    )
    XPageManager.pop(null)
  }

  override fun authPersonalCompleteFailure(message: String?) {

  }

  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
        LifeAccountAuthDataManagerV2.personalAuthData.occupation = selectedCareer
        viewBind.svOccupation.setContentResult(selectedCareer)
        checkNextCondition()
      }
    }
  }

  override fun onLeftOption() {
    // 更换认证信息
    // 清空认证数据
    clearLifeAccountAuthData()
    // 清空职业标签回显
    viewBind.svOccupation.clearContentResult()
    // 清空身份信息页 直接替换fragment
    val targetFragment = LifeAccountIDCardAuthFragmentV2()
    supportFragmentManager.beginTransaction().remove(curFragment).add(R.id.fragment_container, targetFragment).commit()
    curFragment = targetFragment
  }

  override fun onRightOption() {
    // 重新登录
    ApiService.userLogout(this)
  }

  override fun userLogoutSuccess() {
    XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
  }

  override fun onDoBack() {
    // 清空内存中的认证数据
    clearLifeAccountAuthData()
    XPageManager.pop(null)
  }

  override fun onBackPressed() {
    // 清空内存中的认证数据
    clearLifeAccountAuthData()
    XPageManager.pop(null)
  }

}
