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

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.text.InputFilter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.megvii.demo.activity.IDCardDetectActivity
import com.megvii.demo.utils.Configuration
import com.megvii.idcardquality.IDCardQualityLicenseManager
import com.megvii.licensemanager.Manager
import com.megvii.meglive_sdk.listener.DetectCallback
import com.megvii.meglive_sdk.listener.PreCallback
import com.megvii.meglive_sdk.manager.MegLiveManager
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.bcommon.base.BaseFragment
import com.yidian.bcommon.http.HttpResult
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.adapter.BottomSelectAdapter
import com.yidian.shenghuoquan.bmanagercenter.bean.BottomSelectBean
import com.yidian.bcommon.bean.HintOptionBean
import com.yidian.shenghuoquan.bmanagercenter.constant.Constant
import com.yidian.shenghuoquan.bmanagercenter.databinding.FragmentLifeAccountIdCardAuthBinding
import com.yidian.shenghuoquan.bmanagercenter.http.ApiService
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.*
import com.yidian.shenghuoquan.bmanagercenter.ui.dialog.BottomSelectDialog
import com.yidian.bcommon.widget.dialog.HintDialog
import com.yidian.shenghuoquan.bmanagercenter.http.callback.*
import com.yidian.shenghuoquan.bmanagercenter.utils.BitmapUtil
import com.yidian.shenghuoquan.bmanagercenter.utils.FileUtil
import com.yidian.shenghuoquan.bmanagercenter.utils.InputFilterUtil
import com.yidian.shenghuoquan.bmanagercenter.utils.KS3Core
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountAuthIdentityInfoEditView
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountAuthImageView
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountFaceAuthView
import com.yidian.shenghuoquan.bmanagercenter.widget.PrivacyAgreementView
import com.yidian.utils.ToastUtil
import java.io.File

/**
 * author: yinjiacheng
 * date: 5/26/21 7:49 PM
 * description: 生活号身份证认证
 */
class LifeAccountIDCardAuthFragment : BaseFragment<FragmentLifeAccountIdCardAuthBinding>(),
  View.OnClickListener, BottomSelectAdapter.OnItemClickListener<BottomSelectBean>, AuthPersonalGetTokenCallback,
  IdentifyIdOcrVerifyCallback, PreCallback, DetectCallback, KS3Core.OnKS3TaskListener, IAuthPersonalCheckCallback,
  IAuthLiveIdentityCallback, LifeAccountAuthImageView.OnLifeAccountAuthImageViewCallback,
  LifeAccountAuthIdentityInfoEditView.OnLifeAccountAuthIdentityInfoEditViewCallback,
  IAuthIndividualBusinessIdentityCommitCallback, IAuthEnterpriseLiveIdentityCallback,
  LifeAccountFaceAuthView.OnLifeAccountFaceAuthCallback, PrivacyAgreementView.OnPrivacyAgreementCallback {

  companion object {
    // 身份证采集页面回传数据
    private const val EXTRA_NAME_ID_CARD_IMAGE = "idcardimg_bitmap"

    // 活体检测模型文件名称
    private const val FILE_NAME_ALIVE_DETECT_MODEL = "faceidmodel.bin"

    //活体检测语种 详见文档
    private const val ALIVE_DETECT_LANGUAGE = "zh"

    //活体检测请求host 详见文档
    private const val ALIVE_DETECT_HOST = "https://api.megvii.com"

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

  /**
   * 标识用户当前上传的是身份证人像面或身份证国徽面 帮助onActivityResult区分
   */
  private var curFace: Int = -1

  /**
   * sdcard/Android/data/package/cache
   */
  private val cachePath by lazy { activity?.externalCacheDir?.absolutePath }

  /***
   * sdcard/Android/data/package/file/face_id
   */
  private val fileFaceIDPath by lazy { activity?.getExternalFilesDir("face_id")?.absolutePath }

  /**
   * 旷视活体检测
   */
  private val megLiveManager by lazy { MegLiveManager.getInstance() }

  /**
   * 当前认证类型
   */
  private var authType: Int? = null

  override fun createViewBinding(
    inflater: LayoutInflater,
    container: ViewGroup?
  ): FragmentLifeAccountIdCardAuthBinding {
    return FragmentLifeAccountIdCardAuthBinding.inflate(layoutInflater, container, false)
  }

  override fun onHiddenChanged(hidden: Boolean) {
    super.onHiddenChanged(hidden)
    if (!hidden) {
      // fragment显示
      initView()
    }
  }

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

  private fun initView() {
    authType = arguments?.getInt(Constant.TYPE_AUTH, Constant.TYPE_AUTH_PERSONAL)
      ?: Constant.TYPE_AUTH_PERSONAL
    when (authType) {
      Constant.TYPE_AUTH_PERSONAL -> {
        viewBinding.evRealName.setTitleContent(resources.getString(R.string.real_name))
      }
      Constant.TYPE_AUTH_INDIVIDUAL_BUSINESS -> {
        viewBinding.evRealName.setTitleContent(resources.getString(R.string.individual_business_manager_name))
      }
      Constant.TYPE_AUTH_COMMON_ENTERPRISE -> {
        viewBinding.evRealName.setTitleContent(resources.getString(R.string.enterprise_legal_name))
      }
    }
    viewBinding.evMobile.isVisible = authType == Constant.TYPE_AUTH_COMMON_ENTERPRISE
    viewBinding.avFaceAuth.isVisible =
      (authType == Constant.TYPE_AUTH_PERSONAL) or (authType == Constant.TYPE_AUTH_INDIVIDUAL_BUSINESS)
    // 输入过滤
    viewBinding.evRealName.setInputFilters(InputFilterUtil.getRealNameFilter(), InputFilter.LengthFilter(40))
    // 身份证号码输入限制18位字符，数字+大小写x 小写x自动转大写X
    viewBinding.evIdCardNumber.setInputFilters(InputFilterUtil.getIDCardNumberFilter(), InputFilter.LengthFilter(18), InputFilter.AllCaps())
    viewBinding.evMobile.setInputFilters(InputFilterUtil.getPhoneNumberFilter(), InputFilter.LengthFilter(11))
  }

  private fun initListener() {
    viewBinding.ivIdCardPortraitFace.setOnClickListener(this)
    viewBinding.ivIdCardNationalEmblemFace.setOnClickListener(this)
    viewBinding.ivIdCardPortraitFace.setOnLifeAccountAuthImageViewCallback(this)
    viewBinding.ivIdCardNationalEmblemFace.setOnLifeAccountAuthImageViewCallback(this)
    viewBinding.evRealName.setOnLifeAccountAuthIdentityInfoEditViewCallback(this)
    viewBinding.evIdCardNumber.setOnLifeAccountAuthIdentityInfoEditViewCallback(this)
    viewBinding.evMobile.setOnLifeAccountAuthIdentityInfoEditViewCallback(this)
    viewBinding.avFaceAuth.setOnLifeAccountFaceAuthCallback(this)
    viewBinding.avPrivacyAgreement.setOnPrivacyAgreementCallback(this)
  }

  private fun initData() {
    // 还原认证数据
    val authData = arguments?.getSerializable(EXTRA_AUTH_DATA) ?: return
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      fillPersonalAuthInfo(authData as AuthAuthenticationBean.Response)
    } else {
      fillEnterpriseAuthInfo(authData as AuthMerchantCheckBean.Response)
    }
  }

  /**
   * 初始化旷视FaceID
   */
  private fun initFaceID() {
    // 身份证采集初始化
    // 竖屏采集
    Configuration.setIsVertical(activity, true)
    // 检查license是否有效
    checkFaceIDLicense()
    // 若活体检测模型文件不存在则从assets中拷贝
    if (!File(fileFaceIDPath + File.separator + FILE_NAME_ALIVE_DETECT_MODEL).exists()) {
      FileUtil.copyFileFromAssets(
        activity,
        FILE_NAME_ALIVE_DETECT_MODEL,
        fileFaceIDPath + File.separator + FILE_NAME_ALIVE_DETECT_MODEL
      )
    }
  }

  /**
   * 检查旷视FaceID授权有效
   */
  private fun checkFaceIDLicense(): Boolean {
    val licenseManager = IDCardQualityLicenseManager(activity)
    if (licenseManager.checkCachedLicense() > 0) {
      //已授权或者授权未过期
      Log.i(Constant.LIFE_ACCOUNT_AUTH_TAG, "FaceID 授权有效")
      return true
    } else {
      //需要重新授权
      Log.i(Constant.LIFE_ACCOUNT_AUTH_TAG, "FaceID 授权无效，开始获取授权")
      Thread {
        val manager = Manager(activity, true)
        manager.registerLicenseManager(licenseManager)
        manager.takeLicenseFromNetwork(
          licenseManager.getContext(
            Configuration.getUUID(activity)
          )
        )
      }.start()
    }
    return false
  }

  /**
   * 个人认证流程中断，下次进入认证流程时还原进度
   */
  private fun fillPersonalAuthInfo(data: AuthAuthenticationBean.Response) {
    viewBinding.ivIdCardPortraitFace.addImage(data.front_id_card_url)
    viewBinding.ivIdCardNationalEmblemFace.addImage(data.back_id_card_url)
    viewBinding.evRealName.fillEditContent(data.full_name)
    viewBinding.evIdCardNumber.fillEditContent(data.id_card)
    if (data.live_identity_status == Constant.ALIVE_DETECT_SUCCESS) viewBinding.avFaceAuth.showFaceAuthResult(true)
    // 如果人脸验证已通过 则直接锁定输入状态
    if (data.live_identity_status == Constant.ALIVE_DETECT_SUCCESS) lockPersonalAuthInfo()
    // 检查下一步条件
    (activity as LifeAccountPersonalAuthActivity).checkNextCondition()
  }

  /**
   * 企业认证流程中断，下次进入认证流程时还原进度
   */
  private fun fillEnterpriseAuthInfo(data: AuthMerchantCheckBean.Response) {
    viewBinding.ivIdCardPortraitFace.addImage(data.legal_front_id_card_url)
    viewBinding.ivIdCardNationalEmblemFace.addImage(data.legal_back_id_card_url)
    viewBinding.evRealName.fillEditContent(data.legal_person)
    viewBinding.evIdCardNumber.fillEditContent(data.legal_id_card)
    if (authType == Constant.TYPE_AUTH_INDIVIDUAL_BUSINESS) {
      // 个体工商户
      if (data.live_identity_status == Constant.ALIVE_DETECT_SUCCESS) viewBinding.avFaceAuth.showFaceAuthResult(true)
      // 如果人脸验证已通过 则直接锁定输入状态
      if (data.live_identity_status == Constant.ALIVE_DETECT_SUCCESS) lockEnterpriseAuthInfo()
    } else {
      // 普通企业
      viewBinding.evMobile.fillEditContent(data.mobile)
    }
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

  /**
   * 锁定当前输入状态
   * 即完成人脸验证后无法修改身份证照片、姓名、身份证号、职业标签
   */
  private fun lockPersonalAuthInfo() {
    viewBinding.ivIdCardPortraitFace.disableModify()
    viewBinding.ivIdCardNationalEmblemFace.disableModify()
    viewBinding.evRealName.disableModify()
    viewBinding.evIdCardNumber.disableModify()
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      (activity as LifeAccountPersonalAuthActivity).disableModifyOccupation()
    }
  }

  /**
   * 锁定当前输入状态
   * 即完成人脸验证后无法修改身份证照片、姓名、身份证号
   */
  private fun lockEnterpriseAuthInfo() {
    viewBinding.ivIdCardPortraitFace.disableModify()
    viewBinding.ivIdCardNationalEmblemFace.disableModify()
    viewBinding.evRealName.disableModify()
    viewBinding.evIdCardNumber.disableModify()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.iv_id_card_portrait_face -> {
        // 上传身份证人像面
        curFace = Constant.ID_CARD_PORTRAIT_FACE
        Configuration.setCardType(activity, Constant.ID_CARD_PORTRAIT_FACE)
        activity?.let {
          BottomSelectDialog(
            it,
            this,
            arrayListOf(
              BottomSelectBean(Constant.ITEM_TAKE_PHOTO),
              BottomSelectBean(Constant.ITEM_OPEN_ALBUM)
            )
          ).show()
        }
      }
      R.id.iv_id_card_national_emblem_face -> {
        // 上传身份证国徽面
        curFace = Constant.ID_CARD_NATIONAL_EMBLEM_FACE
        Configuration.setCardType(activity, Constant.ID_CARD_NATIONAL_EMBLEM_FACE)
        activity?.let {
          BottomSelectDialog(
            it,
            this,
            arrayListOf(
              BottomSelectBean(Constant.ITEM_TAKE_PHOTO),
              BottomSelectBean(Constant.ITEM_OPEN_ALBUM)
            )
          ).show()
        }
      }
    }
  }

  override fun onItemClick(view: View, position: Int, data: BottomSelectBean) {
    when (data.item) {
      Constant.ITEM_TAKE_PHOTO -> {
        // 判断camera权限
        RxPermissions(this).request(Manifest.permission.CAMERA).subscribe {
          if (it) {
            // 调用FaceID进行身份证采集
            if (checkFaceIDLicense()) {
              startActivityForResult(
                Intent(activity, IDCardDetectActivity::class.java),
                Constant.REQUEST_CODE_ID_CARD_CAPTURE
              )
            } else {
              ToastUtil.showToast(activity, "获取授权失败，请稍后重试")
            }
          } else {
            ToastUtil.showToast(activity, "请在设置里同意相关权限")
          }
        }
      }
      Constant.ITEM_OPEN_ALBUM -> {
        // 打开系统相册
        startActivityForResult(
          Intent(Intent.ACTION_PICK).setDataAndType(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            "image/*"
          ),
          Constant.REQUEST_CODE_OPEN_ALBUM
        )
      }
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
      when (requestCode) {
        Constant.REQUEST_CODE_OPEN_ALBUM -> {
          if (curFace == Constant.ID_CARD_PORTRAIT_FACE) {
            val bitmap = BitmapUtil.generateBitmapFromUri(
              activity,
              data?.data,
              viewBinding.ivIdCardPortraitFace
            )
            viewBinding.ivIdCardPortraitFace.addImage(bitmap)
            FileUtil.generateFileFromUri(
              activity,
              data?.data,
              cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE
            )
            BitmapUtil.compressImage(
              cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE,
              10
            )
            startIDCardUpload(Constant.ID_CARD_PORTRAIT_FACE)
          } else {
            val bitmap = BitmapUtil.generateBitmapFromUri(
              activity,
              data?.data,
              viewBinding.ivIdCardNationalEmblemFace
            )
            viewBinding.ivIdCardNationalEmblemFace.addImage(bitmap)
            FileUtil.generateFileFromUri(
              activity,
              data?.data,
              cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE
            )
            BitmapUtil.compressImage(
              cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE,
              10
            )
            startIDCardUpload(Constant.ID_CARD_NATIONAL_EMBLEM_FACE)
          }
        }
        Constant.REQUEST_CODE_ID_CARD_CAPTURE -> {
          val bytes = data?.getByteArrayExtra(EXTRA_NAME_ID_CARD_IMAGE)
          if (curFace == Constant.ID_CARD_PORTRAIT_FACE) {
            val bitmap = bytes?.size?.let {
              BitmapFactory.decodeByteArray(
                bytes, 0,
                it
              )
            }
            viewBinding.ivIdCardPortraitFace.addImage(bitmap)
            BitmapUtil.generateFileFromBitmap(
              bitmap,
              100,
              cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE
            )
            startIDCardUpload(Constant.ID_CARD_PORTRAIT_FACE)
          } else {
            val bitmap = bytes?.size?.let {
              BitmapFactory.decodeByteArray(
                bytes, 0,
                it
              )
            }
            viewBinding.ivIdCardNationalEmblemFace.addImage(bitmap)
            BitmapUtil.generateFileFromBitmap(
              bitmap,
              100,
              cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE
            )
            startIDCardUpload(Constant.ID_CARD_NATIONAL_EMBLEM_FACE)
          }
        }
      }
    }
  }

  /**
   * 执行身份证上传金山云
   * @param face 身份证两面标识
   */
  private fun startIDCardUpload(face: Int) {
    val uploadFile = if (face == Constant.ID_CARD_PORTRAIT_FACE) {
      File(cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE)
    } else {
      File(cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE)
    }
    KS3Core.INSTANCE.uploadObject(
      uploadFile,
      KS3Core.ObjectType.IMAGE,
      KS3Core.ScenarioType.ID_CARD,
      object : KS3Core.OnKS3TaskListener {
        override fun onTaskStart() {

        }

        override fun onTaskProgress(progress: Double) {

        }

        override fun onTaskFinish() {

        }

        override fun onTaskCancel() {

        }

        override fun onTaskSuccess(bucket: String?, objectKey: String?) {
          if (face == Constant.ID_CARD_PORTRAIT_FACE) {
            LifeAccountAuthDataManager.personalAuthData.isIDCardPortraitFaceUpload =
              true
            LifeAccountAuthDataManager.personalAuthData.idCardPortraitFaceObjectKey =
              objectKey
            LifeAccountAuthDataManager.personalAuthData.idCardPortraitFaceBucket =
              bucket
            LifeAccountAuthDataManager.personalAuthData.idCardPortraitFaceUrl = "${bucket}/${objectKey}"
          } else {
            LifeAccountAuthDataManager.personalAuthData.isIDCardNationalEmblemFaceUpload =
              true
            LifeAccountAuthDataManager.personalAuthData.idCardNationalEmblemFaceObjectKey =
              objectKey
            LifeAccountAuthDataManager.personalAuthData.idCardNationalEmblemFaceBucket =
              bucket
            LifeAccountAuthDataManager.personalAuthData.idCardNationalEmblemFaceUrl = "${bucket}/${objectKey}"
          }
          startIDCardOCR(face, objectKey, bucket)
        }

        override fun onTaskFailure(statesCode: Int, message: String?) {

        }
      }
    )
  }

  /**
   * 执行身份证OCR
   */
  private fun startIDCardOCR(face: Int, objectKey: String?, bucket: String?) {
    if (face == Constant.ID_CARD_PORTRAIT_FACE) {
      ApiService.getIDCardOCR(
        object : IGetIDCardOCRCallback {
          override fun getIDCardOCRSuccess(result: GetIDCardOCRBean.Response?) {
            result?.let { LifeAccountAuthDataManager.generateIDCardPortraitFaceData(it) }
            // 回显OCR结果
            viewBinding.evRealName.fillEditContent(result?.posit?.name)
            viewBinding.evIdCardNumber.fillEditContent(result?.posit?.idcard_number)
            // 此时身份证人像面已上传并OCR识别完成 删除本地临时存储文件
            File(cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE).apply {
              if (exists()) delete()
            }
            // 检查下一步条件
            if (authType == Constant.TYPE_AUTH_PERSONAL) {
              activity?.let { (it as LifeAccountPersonalAuthActivity).checkNextCondition() }
            } else {
              activity?.let { (it as LifeAccountEnterpriseAuthActivity).checkNextCondition() }
            }
          }

          override fun getIDCardOCRFailure(message: String?) {

          }

        }, hashMapOf(
          Pair("posit_image_url", "$bucket/$objectKey")
        )
      )
    } else {
      ApiService.getIDCardOCR(
        object : IGetIDCardOCRCallback {
          override fun getIDCardOCRSuccess(result: GetIDCardOCRBean.Response?) {
            result?.let { LifeAccountAuthDataManager.generateIDCardNationEmblemFaceData(it) }
            // 此时身份证国徽面已上传并OCR识别完成 删除本地临时存储文件
            File(cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE).apply {
              if (exists()) delete()
            }
            // 检查下一步条件
            if (authType == Constant.TYPE_AUTH_PERSONAL) {
              activity?.let { (it as LifeAccountPersonalAuthActivity).checkNextCondition() }
            } else {
              activity?.let { (it as LifeAccountEnterpriseAuthActivity).checkNextCondition() }
            }
          }

          override fun getIDCardOCRFailure(message: String?) {

          }

        }, hashMapOf(
          Pair("back_image_url", "$bucket/$objectKey")
        )
      )
    }
  }

  override fun getTokenSuccess(t: HttpResult<AuthPersonalGetTokenBean.Response?>?) {
    LifeAccountAuthDataManager.personalAuthData.liveDetectBizToken = t?.result?.biz_token
    megLiveManager.preDetect(
      activity,
      t?.result?.biz_token,
      ALIVE_DETECT_LANGUAGE,
      ALIVE_DETECT_HOST,
      fileFaceIDPath + File.separator + FILE_NAME_ALIVE_DETECT_MODEL,
      this
    )
  }

  override fun identifyIdOcrVerifySuccess(t: HttpResult<IdentifyIdOcrVerifyBean.Response?>?) {
    if (t?.result?.verify_result == true) {
      // 保存人脸验证结果
      LifeAccountAuthDataManager.personalAuthData.isFaceAuthPass = true
      // 人脸验证通过UI
      viewBinding.avFaceAuth.showFaceAuthResult(true)
      // 删除活体检测数据
      File(cachePath + Constant.FILE_PATH_ALIVE_DETECT_VERIFY_DATA).apply {
        if (exists()) delete()
      }
      lockPersonalAuthInfo()
      // 回调server 保存活体识别认证状态
      if (authType == Constant.TYPE_AUTH_PERSONAL) {
        ApiService.authLiveIdentity(this)
        // 检查下一步条件
        activity?.let { (it as LifeAccountPersonalAuthActivity).checkNextCondition() }
      } else {
        ApiService.authEnterpriseLiveIdentity(
          this,
          hashMapOf(
            Pair(
              "record_id",
              LifeAccountAuthDataManager.merchantAuthData.authRecordId.toString()
            )
          )
        )
        // 检查下一步条件
        activity?.let { (it as LifeAccountEnterpriseAuthActivity).checkNextCondition() }
      }
    }
  }

  override fun identifyIdOcrVerifyFailure(t: HttpResult<IdentifyIdOcrVerifyBean.Response?>?) {
    LifeAccountAuthDataManager.personalAuthData.isFaceAuthPass = false
    // 人脸验证未通过UI
    viewBinding.avFaceAuth.showFaceAuthResult(false)
  }

  override fun onPreStart() {
    // TODO: 6/1/21 show progress
  }

  override fun onPreFinish(token: String?, errorCode: Int, errorMessage: String?) {
    // 只有当完成预处理且errorCode==1000的时候才可以调用startDetect开启活体检测
    if (errorCode == 1000) {
      megLiveManager.setVerticalDetectionType(MegLiveManager.DETECT_VERITICAL_FRONT)
      megLiveManager.startDetect(this)
    } else {
      Log.e(
        Constant.LIFE_ACCOUNT_AUTH_TAG,
        "alive detect pre detect failure, errorCode: $errorCode, errorMessage: $errorMessage"
      )
    }
  }

  override fun onDetectFinish(
    token: String?,
    errorCode: Int,
    errorMessage: String?,
    data: String?
  ) {
    if (errorCode == 1000) {
      // 保存活体加密数据 上传金山云
      FileUtil.generateFileFromString(
        data,
        cachePath + Constant.FILE_PATH_ALIVE_DETECT_VERIFY_DATA
      )
      KS3Core.INSTANCE.uploadObject(
        cachePath + Constant.FILE_PATH_ALIVE_DETECT_VERIFY_DATA,
        KS3Core.ScenarioType.ALIVE_DETECT,
        this
      )
    } else {
      Log.e(
        Constant.LIFE_ACCOUNT_AUTH_TAG,
        "alive detect detect failure, errorCode: $errorCode, errorMessage: $errorMessage"
      )
      viewBinding.avFaceAuth.showFaceAuthResult(false)
    }
  }

  override fun onTaskStart() {

  }

  override fun onTaskProgress(progress: Double) {

  }

  override fun onTaskFinish() {

  }

  override fun onTaskCancel() {

  }

  override fun onTaskSuccess(bucket: String?, objectKey: String?) {
    LifeAccountAuthDataManager.personalAuthData.liveDetectObjectKey = objectKey
    LifeAccountAuthDataManager.personalAuthData.liveDetectBucket = bucket
    ApiService.identifyIdOcrVerify(
      this,
      hashMapOf(
        Pair(
          "biz_token",
          LifeAccountAuthDataManager.personalAuthData.liveDetectBizToken
        ),
        Pair("meglive_url", "$bucket/$objectKey")
      )
    )
  }

  override fun onTaskFailure(statesCode: Int, message: String?) {

  }

  override fun authPersonCheckSuccess() {
    // 身份信息校验成功后才允许进行人脸验证
    // 若存在上一次活体检测数据则删除 处理活体检测失败 再次进入
    File(cachePath + Constant.FILE_PATH_ALIVE_DETECT_VERIFY_DATA).apply {
      if (exists()) delete()
    }
    // 跳转人脸认证
    ApiService.authPersonalGetToken(
      this,
      hashMapOf(
        Pair("id_number", LifeAccountAuthDataManager.personalAuthData.idCardNum),
        Pair("id_card_name", LifeAccountAuthDataManager.personalAuthData.realName),
        Pair("liveness_type", Constant.TYPE_MEG_LIVE)
      )
    )
  }

  override fun authPersonCheckFailure(code: Int?, message: String?) {
    if (code == Constant.ERROR_CODE_PERSONAL_AUTH_INFO_DUPLICATE) {
      // 身份证号已认证并且认证手机号不是当前手机号 弹窗提示
      activity?.let {
        HintDialog(
          it, message.toString(),
          arrayListOf(
            HintOptionBean(resources.getString(R.string.change)),
            HintOptionBean(resources.getString(R.string.login_again))
          ), it as LifeAccountPersonalAuthActivity
        ).setRightBtnColor(ContextCompat.getColor(it, R.color.color_FF1852F1)).show()
      }
      return
    }
    // 展示输入框下错误提示
    when (message) {
      Constant.ERROR_MESSAGE_REAL_NAME -> {
        viewBinding.evRealName.showErrorTips(
          resources.getText(R.string.id_card_name_error_tips) as String
        )
        viewBinding.evRealName.highLightEditContent()
      }
      Constant.ERROR_MESSAGE_ID_CARD_NUMBER -> {
        viewBinding.evIdCardNumber.showErrorTips(resources.getText(R.string.id_card_number_error_tips) as String)
        viewBinding.evIdCardNumber.highLightEditContent()
      }
    }
  }

  override fun authLiveIdentitySuccess() {

  }

  override fun authLiveIdentityFailure(message: String?) {

  }

  override fun onImageClear(from: LifeAccountAuthImageView) {
    if (from == viewBinding.ivIdCardPortraitFace) {
      // 清除照片时删除本地文件
      File(cachePath + Constant.FILE_PATH_ID_CARD_PORTRAIT_FACE).apply {
        if (exists()) delete()
      }
      LifeAccountAuthDataManager.personalAuthData.isIDCardPortraitFaceUpload = false
      viewBinding.evRealName.clearEditContent()
      viewBinding.evIdCardNumber.clearEditContent()
      LifeAccountAuthDataManager.personalAuthData.realName = ""
      LifeAccountAuthDataManager.personalAuthData.idCardNum = ""
    } else {
      File(cachePath + Constant.FILE_PATH_ID_CARD_NATIONAL_EMBLEM_FACE).apply {
        if (exists()) delete()
      }
      LifeAccountAuthDataManager.personalAuthData.isIDCardNationalEmblemFaceUpload = false
    }
    // 检查下一步条件
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      (activity as LifeAccountPersonalAuthActivity).checkNextCondition()
    } else {
      (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
    }
  }

  override fun onTextClear(from: LifeAccountAuthIdentityInfoEditView) {
    when (from) {
      viewBinding.evRealName -> {
        LifeAccountAuthDataManager.personalAuthData.realName = ""
      }
      viewBinding.evIdCardNumber -> {
        LifeAccountAuthDataManager.personalAuthData.idCardNum = ""
      }
      viewBinding.evMobile -> {
        LifeAccountAuthDataManager.personalAuthData.phoneNum = ""
      }
    }
    // 检查下一步条件
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      (activity as LifeAccountPersonalAuthActivity).checkNextCondition()
    } else {
      (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
    }
  }

  override fun onTextChange(from: LifeAccountAuthIdentityInfoEditView, text: String) {
    when (from) {
      viewBinding.evRealName -> {
        LifeAccountAuthDataManager.personalAuthData.realName = text
      }
      viewBinding.evIdCardNumber -> {
        LifeAccountAuthDataManager.personalAuthData.idCardNum = text
      }
      viewBinding.evMobile -> {
        LifeAccountAuthDataManager.personalAuthData.phoneNum = text
      }
    }
    // 检查下一步条件
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      (activity as LifeAccountPersonalAuthActivity).checkNextCondition()
    } else {
      (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
    }
  }

  override fun onStartFaceAuth() {
    // 判断是否满足条件进行活体检测
    if (!checkFaceAuthCondition()) {
      ToastUtil.showToast(activity, "请补全信息后重试")
      return
    }
    // 判断camera权限
    RxPermissions(this).request(Manifest.permission.CAMERA).subscribe {
      if (it) {
        when (authType) {
          Constant.TYPE_AUTH_PERSONAL -> {
            ApiService.authPersonalCheck(
              this,
              LifeAccountAuthDataManager.generateAuthPersonalCheckRequest()
            )
          }
          Constant.TYPE_AUTH_INDIVIDUAL_BUSINESS -> {
            ApiService.authIndividualBusinessIdentityCommit(
              this,
              LifeAccountAuthDataManager.generateAuthIndividualBusinessIdentityCommitRequest()
            )
          }
        }
      } else {
        ToastUtil.showToast(activity, "请在设置里同意相关权限")
      }
    }
  }

  override fun authIndividualBusinessIdentityCommitSuccess() {
    // 身份信息校验成功后才允许进行人脸验证
    // 若存在上一次活体检测数据则删除 处理活体检测失败 再次进入
    File(cachePath + Constant.FILE_PATH_ALIVE_DETECT_VERIFY_DATA).apply {
      if (exists()) delete()
    }
    // 跳转人脸认证
    ApiService.authPersonalGetToken(
      this,
      hashMapOf(
        Pair("id_number", LifeAccountAuthDataManager.personalAuthData.idCardNum),
        Pair("id_card_name", LifeAccountAuthDataManager.personalAuthData.realName),
        Pair("liveness_type", Constant.TYPE_MEG_LIVE)
      )
    )
  }

  override fun authIndividualBusinessIdentityCommitFailure(message: String?) {
    // 展示输入框下错误提示
    when (message) {
      Constant.ERROR_MESSAGE_REAL_NAME -> {
        viewBinding.evRealName.showErrorTips(
          resources.getText(R.string.id_card_name_error_tips) as String
        )
        viewBinding.evRealName.highLightEditContent()
      }
      Constant.ERROR_MESSAGE_ID_CARD_NUMBER -> {
        viewBinding.evIdCardNumber.showErrorTips(resources.getText(R.string.id_card_number_error_tips) as String)
        viewBinding.evIdCardNumber.highLightEditContent()
      }
    }
  }

  override fun authEnterpriseLiveIdentitySuccess() {

  }

  override fun authEnterpriseLiveIdentityFailure(message: String?) {

  }

  /**
   * 本地校验是否可以进行人脸验证
   * 必须同时满足真实姓名已填、身份证号已填、身份证两面已上传、职业标签已选(只有个人认证需要)
   */
  private fun checkFaceAuthCondition(): Boolean {
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      return !LifeAccountAuthDataManager.personalAuthData.occupation.isNullOrEmpty()
        && !LifeAccountAuthDataManager.personalAuthData.realName.isNullOrEmpty()
        && !LifeAccountAuthDataManager.personalAuthData.idCardNum.isNullOrEmpty()
        && LifeAccountAuthDataManager.personalAuthData.isIDCardPortraitFaceUpload
        && LifeAccountAuthDataManager.personalAuthData.isIDCardNationalEmblemFaceUpload
    }
    return !LifeAccountAuthDataManager.personalAuthData.realName.isNullOrEmpty()
      && !LifeAccountAuthDataManager.personalAuthData.idCardNum.isNullOrEmpty()
      && LifeAccountAuthDataManager.personalAuthData.isIDCardPortraitFaceUpload
      && LifeAccountAuthDataManager.personalAuthData.isIDCardNationalEmblemFaceUpload
  }

  override fun onCheckPrivacyAgreement(isCheck: Boolean) {
    LifeAccountAuthDataManager.personalAuthData.isAgreePrivacyAgreement = isCheck
    // 检查下一步条件
    if (authType == Constant.TYPE_AUTH_PERSONAL) {
      (activity as LifeAccountPersonalAuthActivity).checkNextCondition()
    } else {
      (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
    }
  }

}
