package com.dlc.chemical.ui.unlock

import android.os.Bundle
import android.view.KeyEvent
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityUnlockCompletedBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.mqtt.event.CabinetLockEvent
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.CabinetLockVo
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * info
 *
 * @author ReiChin_
 */
class UnlockCompletedActivity : RcBaseActivity<ActivityUnlockCompletedBinding>() {

    private val mCabinetLockVo: CabinetLockVo by lazy {
        intent.getParcelableExtra("cabinetLock")!!
    }

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

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

        // 关锁
        viewBinding.lock.setOnClickListener {
            // 调用关锁API，完成后语音播报：关锁成功
            callCloseLockApi()
        }

        AudioPlayerManager.speakVoice(R.raw.audio_lock_tips)
    }

    private fun callCloseLockApi() {
        showLoading("关锁中...")
        val disposable = ApiRepository.closeLock(mCabinetLockVo)
            .subscribe({ data ->
                dismissLoading()
                if (data.success) {
                    // 关锁成功
                    dispatchCloseLockSuccess()
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchCloseLockSuccess() {
        AudioPlayerManager.speakVoice(R.raw.audio_success_close_lock)
        SuccessDialog(this, "关锁成功").apply {
            setCancelable(false)
            setOnDismissListener {
                finish()
            }
        }.show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCabinetLockEvent(event: CabinetLockEvent) {
        // TODO ReiChin_ 关锁成功 dispatchCloseLockSuccess()
    }

    override fun onResume() {
        super.onResume()
        EventBus.getDefault().register(this)
    }

    override fun onPause() {
        EventBus.getDefault().unregister(this)
        super.onPause()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 禁用back键
        if (KeyEvent.KEYCODE_BACK == keyCode) return true
        return super.onKeyDown(keyCode, event)
    }

}