package com.dlc.eboard.ui.finger

import android.app.Activity
import android.app.AlertDialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Base64
import android.view.View
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.common.Constants
import com.dlc.eboard.databinding.ActivityFingerEnrollBinding
import com.dlc.eboard.finger.FingerHelper
import com.dlc.eboard.finger.FingerService
import com.dlc.eboard.finger.OnFingerListener
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.eyecool.fp.client.Callback
import com.eyecool.fp.entity.FingerResult
import com.eyecool.fp.util.FpConst
import com.rc.core.log.RcLog
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.UserFingerVo
import java.nio.charset.Charset

/**
 * 指纹录入
 *
 * @author ReiChin_
 */
class FingerEnrollActivity :
    BaseCountDownActivity<ActivityFingerEnrollBinding>() {

    private lateinit var mUserId: String
    private lateinit var mUserName: String
    private lateinit var mUserType: String
    private lateinit var mFingerKey: String

    private var mEnrollIdx = 1
    private var ac: Activity? = null
    override fun createViewBinding() = ActivityFingerEnrollBinding.inflate(layoutInflater)

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    private lateinit var mFingerHelper: FingerHelper

    override fun initViews(savedInstanceState: Bundle?) {
        ac = this
        mUserId = intent.getStringExtra("userId")!!
        mUserName = intent.getStringExtra("userName")!!
        mUserType = intent.getStringExtra("userType")!!
        mFingerKey = intent.getStringExtra("fingerKey")!!
        super.initViews(savedInstanceState)

        viewBinding.tipGroup.visibility = View.VISIBLE
        viewBinding.enrollGroup.visibility = View.GONE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mFingerHelper = generateFingerHelper()
        lifecycle.addObserver(mFingerHelper)
    }

    override fun onDestroy() {
        super.onDestroy()
        mFeatureHandler.removeCallbacksAndMessages(null)
        lifecycle.removeObserver(mFingerHelper)
    }

    private fun generateFingerHelper(): FingerHelper {
        return FingerHelper(object: OnFingerListener {
            override fun showToast(message: String) {
                if (isFinishing) return
                this@FingerEnrollActivity.showToast(message)
                if ("设备忙" == message) {
                    viewBinding.titleBar.postDelayed({
                        enroll()
                    }, 1000)
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        // 5s后开始录入指纹
        viewBinding.titleBar.postDelayed({
            enroll()
        }, 1000)
    }

//    private fun callSaveFingerApi(template: ByteArray?) {
//        callSaveFingerApi(Base64.encodeToString(template, Base64.NO_WRAP))
//    }

    private fun callSaveFingerApi(template: ByteArray?) {
        showLoading("保存中...")
        val param = UserFingerVo().apply {
            finger = template?.let { String(it, Charset.defaultCharset()) }
            fingerKey = mFingerKey
            num = CommonUtils.getAndroidId()
            userId = mUserId
            userName = mUserName
            userType = mUserType
        }
        val disposable = ApiRepository.addUserFinger(param)
            .subscribe({
                dismissLoading()
                viewBinding.enrollText.text = "指纹录入成功，3秒后返回"
                viewBinding.enrollText.postDelayed({
                    setResult(RESULT_OK)
                    finish()
                }, 3000)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun enroll() {
        when (Constants.Mock.FINGER_ENROLL_MODE) {
            Constants.Mock.FINGER_ENROLL_TEMPLATE -> enrollByTemplate()
            Constants.Mock.FINGER_ENROLL_FEATURE -> enrollByFeature()
        }
    }

    private val mFeatureHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            displayMessage("请再次放置手指")
            enrollByFeature()
        }
    }

//    private val featureBuffer = mutableListOf<String>()

    private val mFeatureCallback = object : Callback() {
        override fun onSuccess(result: FingerResult?) {
            if (isFinishing)  return
            startCountDown()

            RcLog.info("[finger enroll]指纹注册进度,mEnrollIdx=${mEnrollIdx}")
            val template = result?.template
//            featureBuffer.add(Base64.encodeToString(template, Base64.NO_WRAP))

            displayMessage("请抬起手指")
            when (mEnrollIdx) {
                1 -> {
                    // 第一次录入成功
                    mEnrollIdx = 2
                    viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_ss)
                    mFeatureHandler.sendEmptyMessageDelayed(1, 2000)
                }
                2-> {
                    // 第二次录入成功
                    mEnrollIdx = 3
                    viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_ls)
                    mFeatureHandler.sendEmptyMessageDelayed(1, 2000)
                }
                3-> {
                    // 第三次录入成功
                    mEnrollIdx = 1
                    viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_yb)

//                    RcLog.info("[finger enroll]指纹注册成功================================")
//                    featureBuffer.forEachIndexed { index, s ->
//                        RcLog.info("[finger enroll]template_${index}：${s}")
//                    }
//                    RcLog.info("[finger enroll]指纹注册成功================================")

//                    val features = featureBuffer.reduce { acc, s -> "$acc${FingerService.FEATURE_SPLIT_TAG}$s" }
                    callSaveFingerApi(template)
                }
            }
        }

        override fun onError(errorCode: Int) {
            if (isFinishing) return
            RcLog.info("[finger enroll]指纹注册失败,errorCode=${errorCode},mEnrollIdx=${mEnrollIdx}")
            mEnrollIdx = 1
            AlertDialog.Builder(ac)
                .setTitle("提示")
                .setMessage("录入失败")
                .setCancelable(false)
                .setPositiveButton("重新录入") { _, _ ->
                    displayMessage("请再次放置手指")
//                    featureBuffer.clear()
                    enrollByFeature()
                }.show()
        }

    }

    private fun enrollByFeature() {
        mFingerHelper.enrollByFeature(mFeatureCallback)
    }

    private fun enrollByTemplate() {
        mFingerHelper.enroll(object: Callback() {
            override fun onSuccess(result: FingerResult?) {
                if (isFinishing)  return
                startCountDown()
                val template = result?.template
                RcLog.info("[finger enroll]指纹注册成功================================")
                RcLog.info("[finger enroll]enroll index：${mEnrollIdx}")
                RcLog.info("[finger enroll]template length：${template?.size ?: 0}")
                RcLog.info("[finger enroll]template：${template?.let { String(it) }}")
                RcLog.info("[finger enroll]template base64：${Base64.encodeToString(template, Base64.NO_WRAP)}")
                RcLog.info("[finger enroll]指纹注册成功================================")
                mEnrollIdx = 1
                displayMessage("请抬起手指")
                viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_yb)
                callSaveFingerApi(template)
            }

            override fun onProcess(code: Int, result: FingerResult?) {
                if (isFinishing)  return
                RcLog.info("[finger enroll]指纹注册进度,code=${code},mEnrollIdx=${mEnrollIdx}")
                when (code) {
                    FpConst.TCY_CAPTUREIMAGE -> {
                        if (mEnrollIdx > 1) displayMessage("请再次放置手指")
                        if (2 == mEnrollIdx) mEnrollIdx = 3
                    }
//                    FpConst.TCY_GETIMAGE -> result.getImgBytes()
                    FpConst.TCY_TOLV -> {
                        displayMessage("请抬起手指")
                        if (1 == mEnrollIdx) {
                            // 第一次录入成功
                            viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_ss)
                            mEnrollIdx = 2
                        }
                        if (3 == mEnrollIdx) {
                            // 第二次录入成功
                            viewBinding.enrollImage.setImageResource(R.mipmap.icon_zw_ls)
                        }
                    }
                    FpConst.TCY_TOO_LEFT -> displayMessage("手指偏左")
                    FpConst.TCY_TOO_RIGHT -> displayMessage("手指偏右")
                    FpConst.TCY_TOO_UP -> displayMessage("手指偏上")
                    FpConst.TCY_TOO_DOWN -> displayMessage("手指偏下")
                    FpConst.TCY_TOO_WET -> displayMessage("手指太湿")
                    FpConst.TCY_TOO_DRY -> displayMessage("手指太干")
                }
            }

            override fun onError(errorCode: Int) {
                if (isFinishing) return
                RcLog.info("[finger enroll]指纹注册失败,errorCode=${errorCode},mEnrollIdx=${mEnrollIdx}")
//                showToast("指纹注册失败, errorCode=${errorCode}")
                AlertDialog.Builder(ac)
                    .setTitle("提示")
                    .setMessage("录入失败")
                    .setCancelable(false)
                    .setPositiveButton("重新录入") { _, _ ->
                        displayMessage("请再次放置手指")
                        enrollByTemplate()
                    }.show()
                mEnrollIdx = 1
            }
        })
    }

    private fun displayMessage(message: String) {
        viewBinding.tipGroup.visibility = View.GONE
        viewBinding.enrollGroup.visibility = View.VISIBLE
        viewBinding.enrollText.text = message
    }

    override fun enabledBackCountDown() = true

}