package com.dlc.chemical.ui.unlock

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import com.dlc.chemical.R
import com.dlc.chemical.common.Constants
import com.dlc.chemical.databinding.ActivitySchoolCardAuthBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.serial.listener.OnSerialScanListener
import com.dlc.chemical.serial.port.scan.PortScanHelper
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.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.UserValidationVo

/**
 * info
 *
 * @author ReiChin_
 */
class SchoolCardAuthActivity : BaseCountDownActivity<ActivitySchoolCardAuthBinding>(),
    TitleBar.TitleListener {

    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() = ActivitySchoolCardAuthBinding.inflate(layoutInflater)

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

        // 取消
        viewBinding.cancel.setOnClickListener {
            finish()
        }

        // 重置
        viewBinding.reset.setOnClickListener {
            if (AUTH_STEP_P2 == mCurrentStep) {
                viewBinding.secondPerson.resetStatus()
                mCurrentStep = AUTH_STEP_P1
                refreshTips()
            } else if (AUTH_STEP_P1 == mCurrentStep) {
                viewBinding.firstPerson.resetStatus()
                mCurrentStep = AUTH_STEP_IDLE
                refreshTips()
            }
        }
        refreshTips()

        if (Constants.Mock.TWO_PERSON_AUTH_TEST) {
            viewBinding.firstPerson.setOnClickListener { handleScanEvent("") }
            viewBinding.secondPerson.setOnClickListener { handleScanEvent("") }
        }
    }

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

    private fun queryPerson(cardNumber: String) {
        showLoading("查询中...")
        val param = UserValidationVo().apply {
            cardNum = cardNumber
        }
        val disposable = ApiRepository.userValidation(param)
            .subscribe({ data ->
                dismissLoading()
                if (AUTH_STEP_IDLE == mCurrentStep) {
                    mCurrentStep = AUTH_STEP_P1
                    mAuthPerson1 = data
                    viewBinding.firstPerson.updateStatus(data.nickName, data.phonenumber)
                    refreshTips()
                } else if (AUTH_STEP_P1 == mCurrentStep) {
                    if (data.userId == mAuthPerson1?.userId) {
                        showToast("同一人员！")
                    } else {
                        mCurrentStep = AUTH_STEP_P2
                        mAuthPerson2 = data
                        viewBinding.secondPerson.updateStatus(data.nickName, data.phonenumber)
                        dispatchAuthSuccess()
                    }
                }
                mHandleScanEvent = false
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
                mHandleScanEvent = false
            })
        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()
    }

    private var mHandleScanEvent = false

    private fun handleScanEvent(content: String) {
        mHandleScanEvent = true
        if (Constants.Mock.TWO_PERSON_AUTH_TEST) {
            when (mCurrentStep) {
                AUTH_STEP_IDLE -> Constants.Mock.AUTH_PERSON_LIST[0]
                AUTH_STEP_P1 -> Constants.Mock.AUTH_PERSON_LIST[1]
                else -> null
            }?.let { queryPerson(it) }
        } else {
            queryPerson(content)
        }
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        mPortScanHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

    private val mPortScanHelper by lazy {
        PortScanHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (!mHandleScanEvent) {
                    handleScanEvent(content)
                }
            }

        })
    }

    override fun onResume() {
        super.onResume()
        mPortScanHelper.onResume()
    }

    override fun onPause() {
        mPortScanHelper.onPause()
        super.onPause()
    }

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

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

}