package com.dlc.eboard.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import com.dlc.eboard.R
import com.dlc.eboard.databinding.WidgetLotControllerBinding

/**
 * info
 *
 * @author ReiChin_
 */
class LotControllerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    private val viewBinding =
        WidgetLotControllerBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.LotControllerView)
        val iconDrawable = typeArray.getDrawable(R.styleable.LotControllerView_lotIcon)
        if (null != iconDrawable) viewBinding.lotIcon.setImageDrawable(iconDrawable)
        viewBinding.lotName.text = typeArray.getString(R.styleable.LotControllerView_lotName)
        val lotOn = typeArray.getBoolean(R.styleable.LotControllerView_lotOn, false)
        typeArray.recycle()

        viewBinding.lotSwitch.setOnClickListener { view ->
            val switchOn = view.tag as? Boolean ?: false
            mSwitchListener?.invoke(view, switchOn)
        }
        controller(lotOn)
    }

    fun setLotInfo(lotName: String?, drawableResId: Int) {
        viewBinding.lotName.text = lotName
        viewBinding.lotIcon.setImageResource(drawableResId)
    }

    fun controller(switchOn: Boolean, blower: Boolean = false, mode: String? = null) {
        val resId = if (switchOn) R.mipmap.icon_kg_k else R.mipmap.icon_kg_g
        viewBinding.lotSwitch.setImageResource(resId)
        viewBinding.lotSwitch.tag = switchOn

        if (switchOn && blower && !mode.isNullOrEmpty()) {
            viewBinding.lotModeGroup.visibility = VISIBLE
            // 1:预案排风 2:人工排风 3:定时排风
            when (mode) {
                "1" -> switchLotMode(R.mipmap.icon_dspf_yapf, "预案")
                "2" -> switchLotMode(R.mipmap.icon_dspf_rgpf, "人工")
                "3" -> switchLotMode(R.mipmap.icon_dspf_dspf, "定时")
            }
        } else {
            viewBinding.lotModeGroup.visibility = GONE
        }
    }

    private fun switchLotMode(modeImgResId: Int, modeText: String) {
        viewBinding.lotModeImage.setImageResource(modeImgResId)
        viewBinding.lotModeText.text = modeText
    }

    private var mSwitchListener: ((v: View, on: Boolean) -> Unit)? = null

    fun setSwitchListener(listener: (v: View, on: Boolean) -> Unit) {
        this.mSwitchListener = listener
    }

}