package com.dlc.eboard.ui.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 com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.ActivityThingsBinding
import com.dlc.eboard.mqtt.event.ThingsEvent
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.widget.LotControllerView
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.core.ui.widget.decoration.GridSpacingItemDecoration
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.ControllerCMD
import com.rc.httpcore.vo.response.LotDeviceVo
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

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

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

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    private val mLotThingsAdapter by lazy { LotThingsAdapter(this) }

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        val offset = DeviceUtils.dip2px(this, 90f)
        val gridExpectedSize = resources.getDimensionPixelSize(R.dimen.lot_things_size)
        val horizontalSpacing = DeviceUtils.dip2px(this, 25f)
        val spanCount = DeviceUtils.spanCount(this, gridExpectedSize, offset, horizontalSpacing)
        viewBinding.lotThings.layoutManager = GridLayoutManager(this, spanCount)
        val decor = GridSpacingItemDecoration(
            spanCount,
            horizontalSpacing,
            DeviceUtils.dip2px(this, 16f), false
        )
        viewBinding.lotThings.addItemDecoration(decor)
        viewBinding.lotThings.adapter = mLotThingsAdapter

        viewBinding.swipeRefreshLayout.setOnRefreshListener {
            queryControllerList()
        }
    }

    override fun initData() {
        queryControllerList()
    }

    private fun queryControllerList() {
        if (null == LabApp.sLabConfig) {
            viewBinding.swipeRefreshLayout.isRefreshing = false
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }

        showLoading("加载中...")
        val disposable = ApiRepository.controllerList(LabApp.sLabConfig!!.labId)
            .subscribe({ data ->
                viewBinding.swipeRefreshLayout.isRefreshing = false
//                dismissLoading()
                mLotThingsAdapter.setNewInstance(data.toMutableList())
                if (data.isNullOrEmpty()) {
                    mLotThingsAdapter.setEmptyView(R.layout.view_list_empty)
                }
            }, { throwable ->
                viewBinding.swipeRefreshLayout.isRefreshing = false
//                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
                mLotThingsAdapter.setEmptyView(R.layout.view_list_empty)
            })
        dismissLoading()
        addDisposable(disposable)
    }

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

    private fun generateCMD(item: LotDeviceVo): ControllerCMD {
        return ControllerCMD().apply {
            id = item.id
            num = item.hardwareNUM
            // 从 所有功能状态 中找到第一个不和 当前功能状态 相同的cmd
//            command = item.functionStatusList.find {
//                item.functionStatus.code != it.code
//            }?.cmd
            command = if (LotDeviceVo.SWITCH_ENUM_ON == item.switchEnums) "close" else "open"
        }
    }

    override fun enabledBackCountDown() = true

    override fun enabledLogoutCountDown() = true

}

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

    override fun convert(holder: BaseViewHolder, item: LotDeviceVo) {
        val itemView = holder.itemView as LotControllerView
        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(isSwitchOn(item.state), !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)
    }

}