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

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.orhanobut.hawk.Hawk
import com.yidian.common.HawkConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.adapter.BottomSelectAdapter
import com.yidian.shenghuoquan.newscontent.bean.BottomSelectBean
import com.yidian.shenghuoquan.newscontent.constant.Constant
import com.yidian.shenghuoquan.newscontent.databinding.ActivityLifeAccountEnterpriseAuthBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.callback.IAuthBusinessLicenseCommitCallback
import com.yidian.shenghuoquan.newscontent.http.callback.IAuthEnterpriseLegalIdentityCommitCallback
import com.yidian.shenghuoquan.newscontent.http.callback.IAuthIndividualBusinessCompleteCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthBusinessLicenseCommitBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthEnterpriseLegalIdentityCommitBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthIndividualBusinessCompleteBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.newscontent.ui.dialog.BottomSelectDialog
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.shenghuoquan.newscontent.widget.CommonTopBarView
import com.yidian.shenghuoquan.newscontent.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"
  }

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

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

  /**
   * 个人生活号id 企业升级用
   */
  private val personalLifeAccountId by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      (it as HashMap<*, *>)[EXTRA_LIFE_ACCOUNT_ID]?.let { id ->
        id as String
      } ?: Hawk.get(HawkConfig.LifeAccountId, null)
    }
  }

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

  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.btnNext.setOnClickListener(this)
  }

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

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

  private fun initData() {
    // 如果有已存在的认证流程则还原进度
    authData?.let { LifeAccountAuthDataManager.generateMerchantAuthData(it) }
    authData?.data_type?.let {
      viewBind.svMerchantType.setContentResult(
        if (it == Constant.TYPE_INDIVIDUAL_BUSINESS) {
          Constant.ITEM_INDIVIDUAL_BUSINESSES
        } else {
          Constant.ITEM_COMMON_ENTERPRISE
        }
      )
    }
    val bundle = Bundle()
    bundle.putSerializable(LifeAccountBusinessLicenseAuthFragment.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
  }

  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.btn_next -> {
        if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_QUALIFICATION) {
          // personalLifeAccountId不为null则是由个人生活号升级为企业生活号情况
          // personalLifeAccountId为null则是直接进行企业认证情况
          ApiService.authBusinessLicenseCommit(
            this,
            LifeAccountAuthDataManager.generateAuthBusinessLicenseCommitRequest(
              personalLifeAccountId
            )
          )
        } else if (viewBind.pvAuthProcess.curProcess == LifeAccountAuthProcessView.PROCESS_ENTERPRISE_MANAGER) {
          if (LifeAccountAuthDataManager.merchantAuthData.merchantType == Constant.TYPE_INDIVIDUAL_BUSINESS) {
            ApiService.authIndividualBusinessComplete(
              this,
              LifeAccountAuthDataManager.generateAuthIndividualBusinessCompleteRequest(
                personalLifeAccountId
              )
            )
          } else if (LifeAccountAuthDataManager.merchantAuthData.merchantType == Constant.TYPE_COMMON_ENTERPRISE) {
            ApiService.authEnterpriseLegalIdentityCommit(
              this,
              LifeAccountAuthDataManager.generateAuthEnterpriseLegalIdentityCommitRequest(
                personalLifeAccountId
              )
            )
          }
        }
      }
    }
  }

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

  override fun authBusinessLicenseCommitSuccess(result: AuthBusinessLicenseCommitBean.Response?) {
    // 营业执照提交成功
    LifeAccountAuthDataManager.merchantAuthData.authRecordId = result?.enterprise_auth_record_id
    viewBind.pvAuthProcess.setProcess(++viewBind.pvAuthProcess.curProcess)
    viewBind.svMerchantType.enableSelect(false)
    // 向身份信息fragment传参
    val fragment = fragmentList[viewBind.pvAuthProcess.curProcess]
    val bundle = Bundle()
    bundle.putInt(
      Constant.TYPE_AUTH,
      LifeAccountAuthDataManager.merchantAuthData.merchantType
    )
    bundle.putSerializable(LifeAccountIDCardAuthFragment.EXTRA_AUTH_DATA, authData)
    fragment.arguments = bundle
    switchFragment(fragment)
  }

  override fun authBusinessLicenseCommitFailure(message: String?) {
    Log.e(
      Constant.LIFE_ACCOUNT_AUTH_TAG,
      "request auth business license commit failure, message: $message"
    )
  }

  override fun authEnterpriseLegalIdentityCommitSuccess(result: AuthEnterpriseLegalIdentityCommitBean.Response?) {
    // 本地保存生活号id
    StorageUtil.putLifeAccountId(result?.life_account_id)
    // 普通企业法人身份信息提交成功
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_AUTH_COMPLETE,
      hashMapOf(
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_NAME,
          LifeAccountAuthDataManager.merchantAuthData.registrationName
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_CODE,
          LifeAccountAuthDataManager.merchantAuthData.registrationCode
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NAME,
          LifeAccountAuthDataManager.personalAuthData.realName
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NUM,
          LifeAccountAuthDataManager.personalAuthData.idCardNum
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID,
          result?.life_account_id
        )
      )
    )
  }

  override fun authEnterpriseLegalIdentityCommitFailure(message: String?) {
    Log.e(
      Constant.LIFE_ACCOUNT_AUTH_TAG,
      "request auth enterprise legal identity commit failure, message: $message"
    )
  }

  override fun authIndividualBusinessCompleteSuccess(result: AuthIndividualBusinessCompleteBean.Response?) {
    // 本地保存生活号id
    StorageUtil.putLifeAccountId(result?.life_account_id)
    // 个体工商户认证完成
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_AUTH_COMPLETE,
      hashMapOf(
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_NAME,
          LifeAccountAuthDataManager.merchantAuthData.registrationName
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.REGISTRATION_CODE,
          LifeAccountAuthDataManager.merchantAuthData.registrationCode
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NAME,
          LifeAccountAuthDataManager.personalAuthData.realName
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.ID_CARD_NUM,
          LifeAccountAuthDataManager.personalAuthData.idCardNum
        ),
        Pair(
          LifeAccountEnterpriseAuthCompleteActivity.EXTRA_LIFE_ACCOUNT_ID,
          result?.life_account_id
        )
      )
    )
  }

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

  override fun onDoBack() {
    // 返回上一步/上一页
    if (viewBind.pvAuthProcess.curProcess == 0) {
      // 当前是第一个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()
    }
  }

}
