package com.dlc.chemical.ui.login

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import androidx.appcompat.app.AlertDialog
import com.arcsoft.face.FaceFeature
import com.arcsoft.face.FaceInfo
import com.dlc.chemical.ChemicalApp
import com.dlc.chemical.camera.FaceEngineHelper
import com.dlc.chemical.common.CommonUtils
import com.dlc.chemical.databinding.ActivityLoginBinding
import com.dlc.chemical.ui.common.BaseCountDownActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import com.rc.httpcore.vo.request.FaceCompareReq
import java.io.File

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

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

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

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

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

    private var faceEngineHelper: FaceEngineHelper? = null

    /*
    * 在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
    ) {
        if (null == ChemicalApp.sLearnLoginVo) return
        showLoading("比对中....")
        val param = FaceCompareReq().apply {
            data = featureData
            userId = ChemicalApp.sLearnLoginVo!!.user_id
        }
        val disposable = ApiRepository.faceCompare(param)
            .subscribe({ success ->
                dismissLoading()
                callback.invoke(false)
                if (success) {
                    // 人脸比对成功，登录成功，进入主页
                    callLearnLoginApi(true) {
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                }
            }, { throwable ->
                callback.invoke(false)
                dismissLoading()
                if (!pretreatmentError(throwable)) {
                    faceEngineHelper?.stopPreview(false)
                    throwable.printStackTrace()
                    showNetError(throwable)
                }
            })
        addDisposable(disposable)
    }

    private fun pretreatmentError(throwable: Throwable): Boolean {
        if (throwable is NetException) {
            // 600- 签到&签出已超时，请重新刷卡重试！
            if ("600" == throwable.code) {
                AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage(throwable.message)
                    .setPositiveButton("确定") { _, _ ->
                        callLearnLoginApi {
                            faceEngineHelper?.stopPreview(false)
                        }
                    }.show()
                return true
            } else if ("500" == throwable.code &&
                true == throwable.message?.startsWith("人脸对比不符")
            ) {
                // 500- 人脸对比不符！
                AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setTitle("提示")
                    .setMessage(throwable.message)
                    .setPositiveButton("确定") { _, _ ->
                        faceEngineHelper?.stopPreview(false)
                    }.show()
                return true
            }
        }
        return false
    }

    private fun callLearnLoginApi(realLogin: Boolean = false, callback: () -> Unit) {
        val defUsername = ChemicalApp.sLearnLoginVo?.username
        val username = intent.getStringExtra("username") ?: defUsername
        if (username.isNullOrEmpty()) {
            ChemicalApp.sLearnLoginVo = null
            HttpClient.token = null
            CommonUtils.restartApp(this)
            return
        }

        showLoading("查询中...")
        val disposable = ApiRepository.learnLogin(username, CommonUtils.getAndroidId(), realLogin)
            .subscribe({ data ->
                dismissLoading()
                ChemicalApp.sLearnLoginVo = data
                callback.invoke()
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    override fun onCompareSuccess() {
    }

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

    override fun onBackPressed() {
        faceEngineHelper?.stopPreview(true)
        faceEngineHelper?.releaseEngineAndCamera()
        ChemicalApp.sLearnLoginVo = null
        HttpClient.token = null
        super.onBackPressed()
    }

    override fun onHomeViewClicked(view: View) {
        onBackPressed()
    }

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

}