package com.yidian.shenghuoquan.bmanagercenter.ui.auth

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.base.BaseActivity
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.adapter.BottomSelectAdapter
import com.yidian.shenghuoquan.bmanagercenter.bean.BottomSelectBean
import com.yidian.shenghuoquan.bmanagercenter.constant.Constant
import com.yidian.shenghuoquan.bmanagercenter.databinding.ActivityLifeAccountEnterpriseAuthBinding
import com.yidian.shenghuoquan.bmanagercenter.http.ApiService
import com.yidian.shenghuoquan.bmanagercenter.http.callback.IAuthBusinessLicenseCommitCallback
import com.yidian.shenghuoquan.bmanagercenter.http.callback.IAuthEnterpriseLegalIdentityCommitCallback
import com.yidian.shenghuoquan.bmanagercenter.http.callback.IAuthIndividualBusinessCompleteCallback
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthBusinessLicenseCommitBean
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthEnterpriseLegalIdentityCommitBean
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthIndividualBusinessCompleteBean
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.bmanagercenter.ui.dialog.BottomSelectDialog
import com.yidian.bcommon.utils.StorageUtil
import com.yidian.shenghuoquan.bmanagercenter.widget.CommonTopBarView
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountAuthProcessView
import com.yidian.xpage.XPageManager

/**
 * author: yinjiacheng
 * date: 5/27/21 5:33 PM
 * description: 生活号企业认证
 */
class LifeAccountEnterpriseAuthActivity : BaseActivity<ActivityLifeAccountEnterpriseAuthBinding>(),
  View.OnClickListener, BottomSelectAdapter.OnItemClickListener<BottomSelectBean>,
  IAuthBusinessLicenseCommitCallback, IAuthEnterpriseLegalIdentityCommitCallback,
  IAuthIndividualBusinessCompleteCallback, CommonTopBarView.OnCommonTopBarBackCallback {

  companion object {

    // 生活号id 个人生活号主动升级企业生活号的认证流程传入
    const val EXTRA_LIFE_ACCOUNT_ID = "life_account_id"

    // 认证数据
    const val EXTRA_AUTH_DATA = "authData"

    // 是否审核驳回后修改认证
    const val EXTRA_IS_AUTH_MODIFY = "isAuthModify"
  }

  private val fragmentList: ArrayList<Fragment> by lazy {
    arrayListOf(
      LifeAccountBusinessLicenseAuthFragmentV2(),
      LifeAccountIDCardAuthFragmentV2()
    )
  }

  /**
   * 当前显示的fragment
   */
  private var curFragment: Fragment? = null

  /**
   * 生活号id 个人认证升级企业认证、企业认证审核驳回修改用
   */
  private val lifeAccountId by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      (it as HashMap<*, *>)[EXTRA_LIFE_ACCOUNT_ID]?.let { id ->
        id as String
      }
    }
  }

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

  /**
   * 是否为认证驳回修改情况
   */
  private val isAuthModify by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      (it as HashMap<*, *>)[EXTRA_IS_AUTH_MODIFY]?.let { bool ->
        bool as Boolean
      } ?: false
    } ?: false
  }

  /**
   * 上一次选择的商户类型
   */
  private var lastSelectedMerchantType: String? = null

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

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

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

  private fun initView() {
    viewBind.pvAuthProcess.setProcess(LifeAccountAuthProcessView.PROCESS_ENTERPRISE_QUALIFICATION)
  }

  private fun initListener() {
    viewBind.bvTopBar.setOnCommonTopBarCallback(this, null)
    viewBind.svMerchantType.setOnClickListener(this)
    viewBind.tvNext.setOnClickListener(this)
  }

  /**
   * 检查是否可以进行下一步
   */
  fun checkNextCondition() {
    if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_QUALIFICATION
      && LifeAccountAuthDataManagerV2.merchantAuthData.merchantType != 0
      && LifeAccountAuthDataManagerV2.merchantAuthData.isBusinessLicenseUpload
      && !LifeAccountAuthDataManagerV2.merchantAuthData.registrationName.isNullOrEmpty()
      && !LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode.isNullOrEmpty()
    ) {
      viewBind.tvNext.alpha = 1f
      viewBind.tvNext.isEnabled = true
    } else if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_MANAGER
      && LifeAccountAuthDataManagerV2.personalAuthData.isAgreePrivacyAgreement
      && LifeAccountAuthDataManagerV2.merchantAuthData.merchantType == Constant.TYPE_INDIVIDUAL_BUSINESS
      && LifeAccountAuthDataManagerV2.personalAuthData.isFaceAuthPass
    ) {
      viewBind.tvNext.alpha = 1f
      viewBind.tvNext.isEnabled = true
    } else if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_MANAGER
      && LifeAccountAuthDataManagerV2.personalAuthData.isAgreePrivacyAgreement
      && LifeAccountAuthDataManagerV2.merchantAuthData.merchantType == Constant.TYPE_COMMON_ENTERPRISE
      && LifeAccountAuthDataManagerV2.personalAuthData.isIDCardPortraitFaceUpload
      && LifeAccountAuthDataManagerV2.personalAuthData.isIDCardNationalEmblemFaceUpload
      && !LifeAccountAuthDataManagerV2.personalAuthData.realName.isNullOrEmpty()
      && !LifeAccountAuthDataManagerV2.personalAuthData.idCardNum.isNullOrEmpty()
      && !LifeAccountAuthDataManagerV2.personalAuthData.phoneNum.isNullOrEmpty()
    ) {
      viewBind.tvNext.alpha = 1f
      viewBind.tvNext.isEnabled = true
    } else {
      viewBind.tvNext.alpha = 0.32f
      viewBind.tvNext.isEnabled = false
    }
  }

  /**
   * 禁止修改商户类型
   */
  fun disableModifyMerchantType() {
    viewBind.svMerchantType.enableSelect(false)
  }

  private fun initData() {
    // 如果有已存在的认证流程则还原进度
    authData?.let { LifeAccountAuthDataManagerV2.generateMerchantAuthData(it) }
    authData?.data_type?.let {
      // 商户类型
      val type = if (it == Constant.TYPE_INDIVIDUAL_BUSINESS) {
        Constant.ITEM_INDIVIDUAL_BUSINESSES
      } else {
        Constant.ITEM_COMMON_ENTERPRISE
      }
      viewBind.svMerchantType.setContentResult(type)
      lastSelectedMerchantType = type
    }
    val bundle = Bundle()
    bundle.putSerializable(LifeAccountBusinessLicenseAuthFragmentV2.EXTRA_AUTH_DATA, authData)
    fragmentList[0].arguments = bundle
    switchFragment(fragmentList[0])
  }

  /**
   * fragment切换
   */
  private fun switchFragment(targetFragment: Fragment) {
    when {
      // 当前无fragment被添加
      curFragment == null -> {
        supportFragmentManager.beginTransaction()
          .add(R.id.fragment_container, targetFragment)
          .commit()
      }
      // 目标fragment已被添加
      targetFragment.isAdded -> {
        curFragment?.let {
          supportFragmentManager.beginTransaction().hide(it).show(targetFragment)
            .commit()
        }
      }
      // 目前fragment没被添加
      else -> {
        curFragment?.let {
          supportFragmentManager.beginTransaction().hide(it)
            .add(R.id.fragment_container, targetFragment).commit()
        }
      }
    }
    curFragment = targetFragment
  }

  /**
   * 清理认证数据
   * 避免在修改认证时出现数据异常
   */
  private fun clearLifeAccountAuthData() {
    LifeAccountAuthDataManagerV2.merchantAuthData.merchantType = 0
    LifeAccountAuthDataManagerV2.merchantAuthData.authRecordId = -1
    LifeAccountAuthDataManagerV2.merchantAuthData.isBusinessLicenseUpload = false
    LifeAccountAuthDataManagerV2.merchantAuthData.registrationName = null
    LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode = null
    LifeAccountAuthDataManagerV2.personalAuthData.isAgreePrivacyAgreement = false
    LifeAccountAuthDataManagerV2.personalAuthData.isFaceAuthPass = false
    LifeAccountAuthDataManagerV2.personalAuthData.isIDCardPortraitFaceUpload = false
    LifeAccountAuthDataManagerV2.personalAuthData.isIDCardNationalEmblemFaceUpload = false
    LifeAccountAuthDataManagerV2.personalAuthData.realName = null
    LifeAccountAuthDataManagerV2.personalAuthData.idCardNum = null
    LifeAccountAuthDataManagerV2.personalAuthData.phoneNum = null
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.sv_merchant_type -> {
        // 弹出商户类型选择
        BottomSelectDialog(
          this,
          this,
          arrayListOf(
            BottomSelectBean(Constant.ITEM_INDIVIDUAL_BUSINESSES),
            BottomSelectBean(Constant.ITEM_COMMON_ENTERPRISE)
          )
        ).show()
      }
      R.id.tv_next -> {
        if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_QUALIFICATION) {
          // personalLifeAccountId不为null则是由个人生活号升级为企业生活号情况
          // personalLifeAccountId为null则是直接进行企业认证情况
          // 402接口 直接企业认证生活号id和审核id均不传 个人认证升级只传生活号id 认证修改只传审核id
          ApiService.authBusinessLicenseCommit(
            this,
            LifeAccountAuthDataManagerV2.generateAuthBusinessLicenseCommitRequest(
              if (isAuthModify) null else lifeAccountId,
              LifeAccountAuthDataManagerV2.merchantAuthData.authRecordId
            )
          )
        } else if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_MANAGER) {
          // 406接口 直接企业认证和认证修改不传生活号id 个人认证升级传生活号id
          if (LifeAccountAuthDataManagerV2.merchantAuthData.merchantType == Constant.TYPE_INDIVIDUAL_BUSINESS) {
            ApiService.authIndividualBusinessComplete(
              this,
              LifeAccountAuthDataManagerV2.generateAuthIndividualBusinessCompleteRequest(
                if (isAuthModify) null else lifeAccountId
              )
            )
          } else if (LifeAccountAuthDataManagerV2.merchantAuthData.merchantType == Constant.TYPE_COMMON_ENTERPRISE) {
            // 403接口 直接企业认证和认证修改不传生活号id 个人认证升级传生活号id
            ApiService.authEnterpriseLegalIdentityCommit(
              this,
              LifeAccountAuthDataManagerV2.generateAuthEnterpriseLegalIdentityCommitRequest(
                if (isAuthModify) null else lifeAccountId
              )
            )
          }
        }
      }
    }
  }

  override fun onItemClick(view: View, position: Int, data: BottomSelectBean) {
    // 未修改商户类型不清空营业执照信息
    if (lastSelectedMerchantType == data.item) {
      return
    } else {
      // 回显选择的商户类型
      viewBind.svMerchantType.setContentResult(data.item)
      // 保存选择的商户类型
      LifeAccountAuthDataManagerV2.merchantAuthData.merchantType =
        if (data.item == Constant.ITEM_INDIVIDUAL_BUSINESSES) Constant.TYPE_INDIVIDUAL_BUSINESS else Constant.TYPE_COMMON_ENTERPRISE
      // 第一次选择商户类型不清空营业执照信息
      if (lastSelectedMerchantType != null) {
        // 更换商户类型，清空营业执照图片、清空注册名称和注册码
        (fragmentList[0] as LifeAccountBusinessLicenseAuthFragmentV2).clearBusinessLicenseInfo()
      }
      // 检查下一步条件
      checkNextCondition()
      lastSelectedMerchantType = data.item
    }
  }

  override fun authBusinessLicenseCommitSuccess(result: AuthBusinessLicenseCommitBean.Response?) {
    // 营业执照提交成功
    result?.enterprise_auth_record_id?.let { LifeAccountAuthDataManagerV2.merchantAuthData.authRecordId = it }
    viewBind.pvAuthProcess.setProcess(++viewBind.pvAuthProcess.curProcess)
    viewBind.svMerchantType.enableSelect(false)
    if (LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify) {
      // 认证信息修改 清空第二步回显数据
      LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify = false
      LifeAccountAuthDataManagerV2.personalAuthData.isIDCardPortraitFaceUpload = false
      LifeAccountAuthDataManagerV2.personalAuthData.isIDCardNationalEmblemFaceUpload = false
      LifeAccountAuthDataManagerV2.personalAuthData.realName = null
      LifeAccountAuthDataManagerV2.personalAuthData.idCardNum = null
      LifeAccountAuthDataManagerV2.personalAuthData.isFaceAuthPass = false
      LifeAccountAuthDataManagerV2.personalAuthData.phoneNum = null
      fragmentList.removeAt(viewBind.pvAuthProcess.curProcess)
      val fragment = LifeAccountIDCardAuthFragmentV2()
      fragmentList.add(viewBind.pvAuthProcess.curProcess, fragment)
      val bundle = Bundle()
      bundle.putInt(
        Constant.TYPE_AUTH,
        LifeAccountAuthDataManagerV2.merchantAuthData.merchantType
      )
      fragment.arguments = bundle
    } else {
      // 向身份信息fragment传参用于回显
      val fragment = fragmentList[viewBind.pvAuthProcess.curProcess]
      val bundle = Bundle()
      bundle.putInt(
        Constant.TYPE_AUTH,
        LifeAccountAuthDataManagerV2.merchantAuthData.merchantType
      )
      bundle.putSerializable(LifeAccountIDCardAuthFragmentV2.EXTRA_AUTH_DATA, authData)
      fragment.arguments = bundle
    }
    switchFragment(fragmentList[viewBind.pvAuthProcess.curProcess])
    // 检查下一步条件
    checkNextCondition()
  }

  override fun authBusinessLicenseCommitFailure(message: String?) {

  }

  override fun authEnterpriseLegalIdentityCommitSuccess(result: AuthEnterpriseLegalIdentityCommitBean.Response?) {
    // 本地保存生活号id
    StorageUtil.putLifeAccountId(result?.life_account_id)
    // 清空认证数据
    clearLifeAccountAuthData()
    // 普通企业法人身份信息提交成功
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_AUTH_COMPLETE,
      hashMapOf(
        Pair(LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_NAME, result?.name),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_CODE, result?.code),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NAME, result?.legal_person),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NUM, result?.legal_id_card),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID, result?.life_account_id),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.EXTRA_IS_AUTH_MODIFY, isAuthModify)
      )
    )
    XPageManager.pop(null)
  }

  override fun authEnterpriseLegalIdentityCommitFailure(message: String?) {

  }

  override fun authIndividualBusinessCompleteSuccess(result: AuthIndividualBusinessCompleteBean.Response?) {
    // 本地保存生活号id
    StorageUtil.putLifeAccountId(result?.life_account_id)
    // 清空认证数据
    clearLifeAccountAuthData()
    // 个体工商户认证完成
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_AUTH_COMPLETE,
      hashMapOf(
        Pair(LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_NAME, result?.name),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_CODE, result?.code),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NAME, result?.legal_person),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NUM, result?.legal_id_card),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID, result?.life_account_id),
        Pair(LifeAccountEnterpriseAuthCompleteActivity.EXTRA_IS_AUTH_MODIFY, isAuthModify)
      )
    )
    XPageManager.pop(null)
  }

  override fun authIndividualBusinessCompleteFailure(message: String?) {

  }

  override fun onDoBack() {
    // 返回上一步/上一页
    if (viewBind.pvAuthProcess.curProcess == 0) {
      // 清空内存中的认证数据
      clearLifeAccountAuthData()
      // 当前是第一个fragment 则退出当前activity
      XPageManager.pop(null)
    } else {
      viewBind.pvAuthProcess.setProcess(--viewBind.pvAuthProcess.curProcess)
      if (viewBind.pvAuthProcess.curProcess == 0) {
        viewBind.svMerchantType.enableSelect(true)
      }
      // 回退fragment
      switchFragment(fragmentList[viewBind.pvAuthProcess.curProcess])
      checkNextCondition()
    }
  }

  override fun onBackPressed() {
    // 返回上一步/上一页
    if (viewBind.pvAuthProcess.curProcess == 0) {
      // 清空内存中的认证数据
      clearLifeAccountAuthData()
      // 当前是第一个fragment 则退出当前activity
      XPageManager.pop(null)
    } else {
      viewBind.pvAuthProcess.setProcess(--viewBind.pvAuthProcess.curProcess)
      if (viewBind.pvAuthProcess.curProcess == 0) {
        viewBind.svMerchantType.enableSelect(true)
      }
      // 回退fragment
      switchFragment(fragmentList[viewBind.pvAuthProcess.curProcess])
      checkNextCondition()
    }
  }

}
