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.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.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.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 {

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

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

  /**
   * 认证数据 还原认证流程用
   */
  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.svOccupation.setOnClickListener(this)
    viewBind.btnNext.setOnClickListener(this)
  }

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

  /**
   * 检查是否可以进行下一步
   */
  fun checkNextCondition() {
    if (LifeAccountAuthDataManager.personalAuthData.isAgreePrivacyAgreement
      && !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)
  }

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

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.sv_occupation -> {
        XPageManager.push(XRouterPathConstants.CHOOSE_CAREER, null)
      }
      R.id.btn_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
        LifeAccountAuthDataManager.personalAuthData.occupation = selectedCareer
        viewBind.svOccupation.setContentResult(selectedCareer)
        checkNextCondition()
      }
    }
  }

  override fun onLeftOption() {
    // 更换认证信息
    // 清空认证数据
    clearLifeAccountAuthData()
    // 清空职业标签回显
    viewBind.svOccupation.clearContentResult()
    // 清空身份信息页 直接替换fragment
    val targetFragment = LifeAccountIDCardAuthFragment()
    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)
  }

}
