package com.dlc.chemical.ui.common

import android.annotation.SuppressLint
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.CommonUtils
import com.dlc.chemical.databinding.ActivityChemicalUnlockBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.mqtt.event.CabinetLockEvent
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.input.InputStoreCompletedActivity
import com.rc.core.ui.activity.RcBaseActivity
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.CabinetLockVo
import com.rc.httpcore.vo.response.ChemicalBean
import com.rc.httpcore.vo.response.LockRespBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * info
 *
 * @author ReiChin_
 */
class ChemicalUnlockActivity : RcBaseActivity<ActivityChemicalUnlockBinding>() {

    // 用于调用关锁API
    private val mCabinetLockVo: CabinetLockVo by lazy {
        intent.getParcelableExtra("cabinetLock")!!
    }

    // 用于展示：机柜名称-柜锁名称
    private val mLockRespBean: LockRespBean by lazy {
        intent.getParcelableExtra("lockRespBean")!!
    }

    private val mChemicalBean: ChemicalBean by lazy {
        intent.getParcelableExtra("chemicalBean")!!
    }

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

    private fun moduleText(): String {
        return when (mCabinetLockVo.lockType) {
            LockType.IN_STOCK.code -> "化学品入库"
            LockType.USE.code -> "领用化学品"
            LockType.BACK.code -> "归还化学品"
            LockType.OUT_STOCK.code -> "化学品出库"
            else -> ""
        }
    }

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

        viewBinding.moduleName.text = moduleText()

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

        AudioPlayerManager.speakVoice(R.raw.audio_lock_tips)
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        // 机柜名称-柜锁名称
        viewBinding.cabinetName.text = "${mLockRespBean.cabinetName ?: ""}-${mLockRespBean.lockName ?: ""}"
        // 化学品名
        viewBinding.chemicalName.text = "化学品名：${mChemicalBean.chemicalName ?: ""}"
        // 分类
        viewBinding.classifyName.text = "分类：${mChemicalBean.classifyName ?: ""}"
        // 编号
        viewBinding.chemicalNum.text = "编号：${mChemicalBean.chemicalNum ?: ""}"
        // CAS号
        viewBinding.casNum.text = "CAS号：${mChemicalBean.casNum ?: ""}"
        val chemicalUnit = mChemicalBean.chemicalUnit ?: "g"
        // 称重重量
        if (LockType.USE.code == mCabinetLockVo.lockType
            || LockType.OUT_STOCK.code == mCabinetLockVo.lockType) {
            viewBinding.weightValue.visibility = View.GONE
        } else {
            viewBinding.weightValue.visibility = View.VISIBLE
            viewBinding.weightValue.text = weightText(chemicalUnit)
        }
        // 化学品净重
        viewBinding.suttleWeight.text = suttleText(chemicalUnit)
        // 提示信息
        viewBinding.tips.text = tipsText()
    }

    private fun tipsText(): String {
        return when (mCabinetLockVo.lockType) {
            LockType.IN_STOCK.code -> "请将您要入库的化学品放置柜中，完成后，关门并点击屏幕下方的“关锁”按钮。"
            LockType.USE.code -> "请取走您领用的化学品，完成后，关门并点击屏幕下方的“关锁”按钮。"
            LockType.BACK.code -> "请将您要归还的化学品放置柜中，完成后，关门并点击屏幕下方的“关锁”按钮。"
            LockType.OUT_STOCK.code -> "请取走您要出库的化学品，完成后，关门并点击屏幕下方的“关锁”按钮。"
            else -> ""
        }
    }

    private fun weightText(chemicalUnit: String): String {
        return when (mCabinetLockVo.lockType) {
            LockType.IN_STOCK.code -> "称重重量：${mChemicalBean.usages ?: "0.0"}${chemicalUnit}"
            LockType.BACK.code -> "称重重量：${mChemicalBean.returnStockNum ?: "0.0"}${chemicalUnit}"
            else -> ""
        }
    }

    private fun suttleText(chemicalUnit: String): String {
        return when (mCabinetLockVo.lockType) {
            LockType.IN_STOCK.code -> "化学品净重：${mChemicalBean.suttle ?: "0.0"}${chemicalUnit}"
            LockType.USE.code -> "库存净重：${mChemicalBean.suttle ?: "0.0"}${chemicalUnit}"
            LockType.BACK.code -> "化学品净重：${calculateSuttle(mChemicalBean.returnStockNum)}${chemicalUnit}"
            LockType.OUT_STOCK.code -> "出库净重：${mChemicalBean.suttle ?: "0.0"}${chemicalUnit}"
            else -> ""
        }
    }

    // 计算净重量
    private fun calculateSuttle(weight: String?, tare: String? = mChemicalBean.tare): Float {
        return CommonUtils.stringParseFloat(weight) - CommonUtils.stringParseFloat(tare)
    }

    private fun callCloseLockApi() {
        showLoading("关锁中...")
        mCabinetLockVo.lockLogId = mLockRespBean.lockLogId
        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 {
                if (LockType.IN_STOCK.code == mCabinetLockVo.lockType) {
                    val intent =
                        Intent(this@ChemicalUnlockActivity, InputStoreCompletedActivity::class.java)
                    intent.putExtra("chemicalBean", mChemicalBean)
                    startActivity(intent)
                    finish()
                } else if (LockType.USE.code == mCabinetLockVo.lockType
                    || LockType.OUT_STOCK.code == mCabinetLockVo.lockType) {
                    val intent = Intent(this@ChemicalUnlockActivity, TagScanActivity::class.java)
                    intent.putExtra("chemicalBean", mChemicalBean)
                    if (LockType.USE.code == mCabinetLockVo.lockType) {
                        intent.putExtra("moduleEnum", ModuleEnum.USE)
                    } else {
                        intent.putExtra("moduleEnum", ModuleEnum.OUTPUT_STORE)
                        intent.putExtra("stockStatus", getIntent().getStringExtra("stockStatus"))
                    }
                    intent.putExtra("lockLogId", mLockRespBean.lockLogId)
                    intent.putExtra("oneUser", getIntent().getStringExtra("oneUser"))
                    intent.putExtra("twoUser", getIntent().getStringExtra("twoUser"))
                    startActivity(intent)
                    finish()
                } else if (LockType.BACK.code == mCabinetLockVo.lockType) {
                    val intent = Intent()
                    intent.putExtra("lockLogId", mLockRespBean.lockLogId)
                    setResult(RESULT_OK, intent)
                    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)
    }

}