package com.dlc.chemical.ui.unlock

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.chemical.R
import com.dlc.chemical.common.Constants
import com.dlc.chemical.databinding.ActivityChemicalCabinetBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.mqtt.MqttManager
import com.dlc.chemical.mqtt.event.CabinetLockEvent
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.BaseCountDownActivity
import com.dlc.chemical.ui.common.LockType
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.response.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

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

    private var mChemicalBean: ChemicalBean? = null

    override fun beforeSetContentView() {
        mChemicalBean = intent.getParcelableExtra("chemicalBean")
    }

    private val mChemicalCabinetAdapter by lazy { ChemicalCabinetAdapter() }

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

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

        viewBinding.recyclerView.layoutManager = GridLayoutManager(this, 3)
        viewBinding.recyclerView.adapter = mChemicalCabinetAdapter
        mChemicalCabinetAdapter.setOnItemClickListener { _, _, position ->
            showSelectedLockDialog(mChemicalCabinetAdapter.getItem(position))
        }

        viewBinding.cabinetName.setOnClickListener {
            showSelectedLockDialog(it.tag as CabinetBean?)
        }
    }

    private fun showSelectedLockDialog(item: CabinetBean?) {
        if (null == item) return

        queryCabinetLockList(item.id) { data ->
            SelectCabinetLockDialog(this, item.cabinetName, data) { cLockVo ->
                // 选择柜锁返回, 调用开锁API
                callOpenLockApi(cLockVo.lockId)
            }.show()
        }
    }

    private fun callOpenLockApi(lockId: String?) {
        showLoading("开锁中...")
        val param = CabinetLockVo()
        param.lockType = LockType.SYSTEM.code
        param.lockId = lockId
        val disposable = ApiRepository.openLock(param)
            .subscribe({ data ->
                dismissLoading()
                if (data.success) {
                    // 开锁成功
                    dispatchOpenLockSuccess(param, data)
                } else {
                    showToast("开锁失败")
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchOpenLockSuccess(cabinetLock: CabinetLockVo, lockRespBean: LockRespBean) {
        AudioPlayerManager.speakVoice(R.raw.audio_success_open_lock)
        SuccessDialog(this, "开锁成功").apply {
            setCancelable(false)
            setOnDismissListener {
                cabinetLock.lockLogId = lockRespBean.lockLogId
                val intent =
                    Intent(this@ChemicalCabinetActivity, UnlockCompletedActivity::class.java)
                intent.putExtra("cabinetLock", cabinetLock)
                startActivity(intent)
                finish()
            }
        }.show()
    }

    private fun queryCabinetLockList(
        cabinetId: String?,
        callback: (data: MutableList<CabinetLockVo>) -> Unit
    ) {
        showLoading("查询中...")
        val param = CabinetLockVo()
        param.cabinetId = cabinetId
        val disposable = ApiRepository.queryCabinetLockList(param)
            .subscribe({ data ->
                dismissLoading()
                callback.invoke(data.toMutableList())
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    override fun initData() {
        querySubInfo()
        queryCabinetList()
    }

    private var mSubInfoVo: SubInfoVo? = null

    /**
     * 查询实验室信息
     */
    private fun querySubInfo() {
        showLoading("查询中...")
        val disposable = ApiRepository.querySubInfo()
            .subscribe({ data ->
                dismissLoading()
                mSubInfoVo = data
                viewBinding.subName.text = data.subName
                if (Constants.Mock.MQTT_ENABLED) {
                    MqttManager.instance.subscribe(
                        Constants.MqttConfig.Topic.CABINET_LOCK.plus(data.subId),
                        0
                    )
                }
            }, { throwable ->
                mSubInfoVo = null
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    /*
     * 查询机柜
     */
    private fun queryCabinetList() {
        showLoading("查询中...")
        val disposable = ApiRepository.queryCabinetList()
            .subscribe({ data ->
                dismissLoading()
                if (data.isNullOrEmpty()) {
                    mChemicalCabinetAdapter.setEmptyView(R.layout.view_list_empty)
                } else if (data.size == 1) {
                    viewBinding.recyclerView.visibility = View.GONE
                    viewBinding.cabinetName.visibility = View.VISIBLE
                    viewBinding.cabinetName.text = data[0].cabinetName
                    viewBinding.cabinetName.tag = data[0]
                } else {
                    mChemicalCabinetAdapter.setNewInstance(data.toMutableList())
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
                mChemicalCabinetAdapter.setEmptyView(R.layout.view_list_empty)
            })
        addDisposable(disposable)
    }

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

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

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

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

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

}

private class ChemicalCabinetAdapter :
    BaseQuickAdapter<CabinetBean, BaseViewHolder>(R.layout.item_chemical_cabinet) {

    var selectedCabinetId: String? = null

    override fun convert(holder: BaseViewHolder, item: CabinetBean) {
        val backgroundRes =
            if (selectedCabinetId == item.id) R.drawable.shape_rect_round_6_solid_330183fa
            else R.drawable.shape_rect_round_6_solid_f5
        holder.setText(R.id.cabinetName, item.cabinetName)
            .setBackgroundResource(R.id.cabinetName, backgroundRes)
            .setTextColor(
                R.id.cabinetName,
                Color.parseColor(if (selectedCabinetId == item.id) "#0183FA" else "#333333")
            )
    }

}