package com.dlc.chemical.ui.unlock

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewTreeObserver
import com.arcsoft.face.FaceFeature
import com.arcsoft.face.FaceInfo
import com.dlc.chemical.R
import com.dlc.chemical.camera.FaceEngineHelper
import com.dlc.chemical.databinding.ActivityFaceDetectAuthBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.BaseCountDownActivity
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.UserValidationVo
import com.rc.httpcore.vo.response.SubInfoVo
import java.io.File

/**
 * info
 *
 * @author ReiChin_
 */
class FaceDetectAuthActivity : BaseCountDownActivity<ActivityFaceDetectAuthBinding>(),
    TitleBar.TitleListener,
    ViewTreeObserver.OnGlobalLayoutListener,
    FaceEngineHelper.EngineCallback {

    companion object {
        private const val AUTH_STEP_IDLE = 0
        private const val AUTH_STEP_P1 = 1
        private const val AUTH_STEP_P2 = 2
    }

    private var mCurrentStep = AUTH_STEP_IDLE

    private var mAuthPerson1: UserValidationVo? = null
    private var mAuthPerson2: UserValidationVo? = null

    override fun createViewBinding() = ActivityFaceDetectAuthBinding.inflate(layoutInflater)

    private var faceEngineHelper: FaceEngineHelper? = null

    private lateinit var mSubInfoVo: SubInfoVo

    override fun initViews(savedInstanceState: Bundle?) {
        mSubInfoVo = intent.getParcelableExtra("subInfo")!!

        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        // 在布局结束后才做初始化操作
        viewBinding.texturePreview.viewTreeObserver.addOnGlobalLayoutListener(this)

        viewBinding.cameraTips.text = "请将脸部对准摄像头"
        refreshTips()
    }

    private fun refreshTips() {
        if (AUTH_STEP_IDLE == mCurrentStep) {
            viewBinding.authTips.text = "请第一个人进行人脸验证"
            AudioPlayerManager.speakVoice(R.raw.audio_face_detect_p1)
        } else if (AUTH_STEP_P1 == mCurrentStep) {
            viewBinding.authTips.text = "请第二个人进行人脸验证"
            AudioPlayerManager.speakVoice(R.raw.audio_face_detect_p2)
        }
    }

    /*
    * 在viewBinding.texturePreview第一次布局完成后，去除该监听，并且进行引擎和相机的初始化
    */
    override fun onGlobalLayout() {
        viewBinding.texturePreview.viewTreeObserver.removeOnGlobalLayoutListener(this)
        if (null == faceEngineHelper) {
            faceEngineHelper = FaceEngineHelper(
                this,
                viewBinding.texturePreview,
                null, this
            ).apply {
                initEngineAndCamera()

                viewBinding.texturePreview.postDelayed({
                    startPreview()
                }, 100)
            }
        }
    }

    private fun startPreview() {
        // 核验通过，直接人脸识别
        faceEngineHelper?.isVisibleToUser = true
        faceEngineHelper?.stopPreview(false)
    }

    override fun onResume() {
        super.onResume()
        faceEngineHelper?.isVisibleToUser = true
    }

    override fun onPause() {
        faceEngineHelper?.isVisibleToUser = false
        super.onPause()
    }

    override fun onStop() {
        super.onStop()
        faceEngineHelper?.releaseEngineAndCamera()
    }

    override fun onDestroy() {
        super.onDestroy()
        faceEngineHelper?.releaseEngineAndCamera()
    }

    override fun onLivenessSuccess(
        nv21: ByteArray,
        width: Int,
        height: Int,
        faceInfo: FaceInfo?,
        callback: (comparing: Boolean) -> Unit
    ) {
        RcLog.info("活体检查成功，调用本地的比对方法")
    }

    override fun onFaceFile(file: File, callback: (comparing: Boolean) -> Unit) {
        RcLog.info("活体检查成功，已生成图片，调用后台服务人脸比对")
    }

    override fun onFaceFeature(faceFeature: FaceFeature, callback: (comparing: Boolean) -> Unit) {
        RcLog.info("人脸特征已生成，调用后台服务人脸比对，同时调用签到API")
        faceEngineHelper?.stopPreview(true)
        callback.invoke(true)

        // 调用人脸比对方法
        callFaceMatchingApi(faceFeature.featureData, callback)
    }

    private fun callFaceMatchingApi(
        featureData: ByteArray,
        callback: (comparing: Boolean) -> Unit
    ) {
        showLoading("比对中....")
        val param = mSubInfoVo.clone()
        param.data = featureData
        val disposable = ApiRepository.faceAuth(param)
            .subscribe({ data ->
                callback.invoke(false)
                dismissLoading()
                if (AUTH_STEP_IDLE == mCurrentStep) {
                    mCurrentStep = AUTH_STEP_P1
                    mAuthPerson1 = data
                    refreshTips()
                    // 延迟5s再进行第二位人员验证
                    Handler(Looper.getMainLooper()).postDelayed({
                        faceEngineHelper?.stopPreview(false)
                    }, 5000)
                } else if (AUTH_STEP_P1 == mCurrentStep) {
                    if (data.userId == mAuthPerson1?.userId) {
                        showToast("同一人员！")
                        // 延迟5s再进行下一次人员验证
                        Handler(Looper.getMainLooper()).postDelayed({
                            faceEngineHelper?.stopPreview(false)
                        }, 5000)
                    } else {
                        mCurrentStep = AUTH_STEP_P2
                        mAuthPerson2 = data
                        dispatchAuthSuccess()
                    }
                }
            }, { throwable ->
                callback.invoke(false)
                dismissLoading()
                faceEngineHelper?.stopPreview(false)
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun dispatchAuthSuccess() {
        AudioPlayerManager.speakVoice(R.raw.audio_success_person_auth)
        SuccessDialog(this, "身份认证成功").apply {
            setCancelable(false)
            setOnDismissListener {
                val intent = Intent()
                intent.putExtra("joinOneUser", mAuthPerson1?.userId)
                intent.putExtra("joinTwoUser", mAuthPerson2?.userId)
                setResult(RESULT_OK, intent)
                finish()
            }
        }.show()
    }

    override fun onCompareSuccess() {
    }

    override fun onError(errMsg: String, type: FaceEngineHelper.OperType) {
    }

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

}