package xn.xxp.main.things

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 core.ui.activity.BaseCountDownActivity
import core.ui.widget.decoration.GridSpacingItemDecoration
import http.client.ApiRepository
import http.vo.request.ControllerCMD
import http.vo.response.LotDeviceVo
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import xn.xxp.R
import xn.xxp.databinding.ActivityThingsBinding
import xn.xxp.mqtt.event.ThingsEvent
import xn.xxp.room.RoomTool
import xn.xxp.room.bean.LabConfig
import xn.xxp.utils.Tool
import xn.xxp.widget.ITitleBar
import xn.xxp.widget.IotControllerView
import xn.xxp.widget.NavViewCompat

/**
 * 物联控制
 *
 * @author ReiChin_
 */
open class ThingsActivity :
    BaseCountDownActivity<ActivityThingsBinding>(),
    LotThingsAdapter.OnItemSwitchListener {
    lateinit var labConfig: LabConfig

    override fun createViewBinding() = ActivityThingsBinding.inflate(layoutInflater)
    override fun getMTitleBar(): ITitleBar {
        return binding.titleBar
    }

    override fun getMNavView(): NavViewCompat {
        return binding.navView
    }

    private val mLotThingsAdapter by lazy { LotThingsAdapter(this) }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onThingsEvent(event: ThingsEvent) {
        queryControllerList()
    }

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

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        labConfig = RoomTool.getInstance().labConfigDao().labConfig
        val offset = Tool.INSTANCE.dip2px(90f)
        val gridExpectedSize = resources.getDimensionPixelSize(R.dimen.lot_things_size)
        val horizontalSpacing = Tool.INSTANCE.dip2px(25f)
        val spanCount = Tool.INSTANCE.spanCount(gridExpectedSize, offset, horizontalSpacing)
        binding.lotThings.layoutManager = GridLayoutManager(this, spanCount)
        val verticalSpacing = Tool.INSTANCE.dip2px(16f)
        val decor = GridSpacingItemDecoration(
            3,
            28,
            24, false
        )
        binding.lotThings.addItemDecoration(decor)
        binding.lotThings.adapter = mLotThingsAdapter

        binding.swipeRefreshLayout.setOnRefreshListener {
            queryControllerList()
        }
    }

    override fun initData() {
        queryControllerList()
    }

    private fun queryControllerList() {
        showLoading("加载中...")
        val disposable = ApiRepository.controllerList(labConfig.labId.toString())
            .subscribe({ data ->
                binding.swipeRefreshLayout.isRefreshing = false
                dismissLoading()
//                showToast("操作成功！")
                mLotThingsAdapter.setNewInstance(data.toMutableList())
                if (data.isNullOrEmpty()) {
                    mLotThingsAdapter.setEmptyView(R.layout.view_list_empty)
                }
            }, { throwable ->
                binding.swipeRefreshLayout.isRefreshing = false
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
                mLotThingsAdapter.setEmptyView(R.layout.view_list_empty)
            })
        addDisposable(disposable)
    }

    override fun onItemSwitch(v: View, on: Boolean, position: Int) {
        val item = mLotThingsAdapter.getItem(position)
        if (!item.isOnline) {
            // 当前设备不在线
            showToast("当前设备不在线")
            return
        }
        showLoading("加载中...")
        val disposable = ApiRepository.sendControllerCMD(generateCMD(item))
            .subscribe({ success ->
//                dismissLoading()
                if (success) {
                    binding.titleBar.postDelayed({
                        queryControllerList()
                    }, 2000)
                }
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun generateCMD(item: LotDeviceVo): ControllerCMD {
        return ControllerCMD().apply {
            id = item.hardwareNo
            command = if (item.isSwitchOn) "0" else "1"
        }
    }

    override fun enabledBackCountDown() = true
}

private class LotThingsAdapter(private val switchListener: OnItemSwitchListener? = null) :
    BaseQuickAdapter<LotDeviceVo, BaseViewHolder>(R.layout.item_iot_things) {

    override fun convert(holder: BaseViewHolder, item: LotDeviceVo) {
        val itemView = holder.itemView as IotControllerView
        val powerLot = isPowerLot(item.hardwareName)
        val resId = if (powerLot) R.mipmap.icon_dykz else R.mipmap.icon_dspf_fs
        itemView.setLotInfo(item.hardwareName, resId)
        itemView.controller(item.isSwitchOn/*, !powerLot, item.triggerModes*/)
        itemView.setSwitchListener { v, on ->
            switchListener?.onItemSwitch(v, on, holder.adapterPosition)
        }
    }

    private fun isPowerLot(name: String): Boolean {
        return name.contains("电源")
    }

//    private fun isSwitchOn(status: LotDeviceVo.State?): Boolean {
//        return LotDeviceVo.LOT_ON == status?.code
//    }

    interface OnItemSwitchListener {
        fun onItemSwitch(v: View, on: Boolean, position: Int)
    }

}