package com.module.backstage.fragment.param

import android.util.Log
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.sbc.VBoxMessage
import com.module.backstage.R
import com.module.backstage.adapter.DebugParamAdapter
import com.module.backstage.adapter.DebugStateParamAdapter
import com.module.backstage.databinding.BackstageFragmentDebugParamBinding
import com.module.backstage.dialog.OKCancelDialog
import com.module.backstage.listener.DebugClickListener
import com.module.backstage.vm.DebugParamFragmentVM
import com.quyunshuo.androidbaseframemvvm.base.constant.DebugType
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 调试页参数Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@RegisterEventBus
@AndroidEntryPoint
class DebugParamFragment :
    BaseFragment<BackstageFragmentDebugParamBinding, DebugParamFragmentVM>() {
    private val TAG = "DebugParamFragment"
    private var debugParamAdapter: DebugParamAdapter? = null
    var okCancelDialog: OKCancelDialog? = null
    private var debugStateParamAdapter: DebugStateParamAdapter? = null
    override val mViewModel: DebugParamFragmentVM by viewModels()
    override fun createVB() = BackstageFragmentDebugParamBinding.inflate(layoutInflater)

    override fun onDestroyView() {
        mBinding.debugRvProduct.adapter = null
        mBinding.debugStataRv.adapter = null
        super.onDestroyView()
    }

    override fun BackstageFragmentDebugParamBinding.initView() {
        with(debugRvProduct) {
            //设置布局排列方式，默认垂直排列
            val gridLayoutManager: GridLayoutManager =
                GridLayoutManager(
                    this@DebugParamFragment.context,
                    3,
                    GridLayoutManager.VERTICAL,
                    false
                )
            layoutManager = gridLayoutManager
            debugParamAdapter = DebugParamAdapter(mViewModel.getDebugParamData())
            debugParamAdapter?.setItemListener(object : DebugClickListener {
                override fun onClickListener(
                    type: Int,
                    pit:Int,
                    visSelected: Boolean,
                    position: Int,
                    data: String?
                ) {

                    showOnOffDialog(type, visSelected, position, data)
                }
            })
            adapter = debugParamAdapter
        }
        with(debugStataRv) {
            layoutManager = LinearLayoutManager(activity)
            debugStateParamAdapter = DebugStateParamAdapter(mViewModel.getDebugStataParamData())
            adapter = debugStateParamAdapter
        }
        mViewModel.lutouC.observe(viewLifecycleOwner) {
            tvLutou.text = it
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(messageEvent: VBoxMessage) {
        XLogUtil.d("VBoxMessage:$messageEvent")
        mViewModel.disposeData(messageEvent)
    }

    override fun initObserve() {
        lifecycle.addObserver(mViewModel.getThreadDebugParamParam())
        /*        observeLiveData(mViewModel.paramDataListM228, ::setM228)
                observeLiveData(mViewModel.paramDataListM111, ::setM111)
                observeLiveData(mViewModel.paramDataListM166, ::setM166)
                observeLiveData(mViewModel.paramDataListM171, ::setM171)
                observeLiveData(mViewModel.paramDataListM178, ::setM178)
                observeLiveData(mViewModel.paramDataListM198, ::setM198)
                observeLiveData(mViewModel.paramDataListM208, ::setM208)
                observeLiveData(mViewModel.paramDataListM218, ::setM218)*/
        observeLiveData(mViewModel.refreshPage, ::refreshPage)

        observeLiveData(mViewModel.refreshStataPage, ::refreshStataPage)

    }

    private fun refreshPage(b: MutableList<String>) {
        debugParamAdapter?.setState(b)
        debugParamAdapter?.notifyDataSetChanged()
    }


    private fun refreshStataPage(b: List<String>) {
        debugStateParamAdapter?.setState(b)
        debugStateParamAdapter?.notifyDataSetChanged()
    }


    override fun initRequestData() {
        mViewModel.getArticleData()
    }

    /*  fun setM111(lis: List<String>) {
          Log.d(TAG, "setM111: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  7 -> getValue(lis, i, 0)
                  12 -> getValue(lis, i, 1)
              }
              i++
          }
      }

      fun setM166(lis: List<String>) {
          Log.d(TAG, "setM166: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  1 -> getValue(lis, i, 2)
              }
              i++
          }
      }

      fun setM171(lis: List<String>) {
          Log.d(TAG, "setM171: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  3 -> getValue(lis, i, 3)
                  5 -> getValue(lis, i, 4)
                  6 -> getValue(lis, i, 5)
                  7 -> getValue(lis, i, 6)
                  8 -> getValue(lis, i, 7)
                  9 -> getValue(lis, i, 8)

              }
              i++
          }
      }

      fun setM178(lis: List<String>) {
          Log.d(TAG, "setM178: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  2 -> getValue(lis, i, 9)
                  3 -> getValue(lis, i, 10)
                  4 -> getValue(lis, i, 11)
                  5 -> getValue(lis, i, 12)
                  6 -> getValue(lis, i, 13)
                  8 -> getValue(lis, i, 14)

              }
              i++
          }
      }

      fun setM198(lis: List<String>) {
          Log.d(TAG, "setM198: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  0 -> getValue(lis, i, 16)
                  1 -> getValue(lis, i, 15)

              }
              i++
          }
      }

      fun setM208(lis: List<String>) {
          Log.d(TAG, "setM208: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  0 -> getValue(lis, i, 17)
                  1 -> getValue(lis, i, 18)

              }
              i++
          }
      }

      fun setM218(lis: List<String>) {
          Log.d(TAG, "setM218: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  2 -> getValue(lis, i, 19)
                  3 -> getValue(lis, i, 20)

              }
              i++
          }
      }

      fun setM228(lis: List<String>) {
          Log.d(TAG, "setM228: " + lis)
          var i = 0
          val len = lis.size
          while (i < len) {
              when (i) {
                  2 -> getValue(lis, i, 22)
                  3 -> getValue(lis, i, 21)

              }
              i++
          }
      }

      */
    /**
     * 改变对应的状态
     *
     * @param lis      读取lpc返回值列表
     * @param index    lis对应的值
     * @param position 要改变的checkbox的位置
     *//*
    private fun getValue(lis: List<String>, index: Int, position: Int) {
        val view: View = mBinding.debugRvProduct.getChildAt(position)
        if (null != mBinding.debugRvProduct.getChildViewHolder(view)) {
            val viewHolder: DebugParamAdapter.MyViewHolder =
                mBinding.debugRvProduct.getChildViewHolder(view) as DebugParamAdapter.MyViewHolder
            Log.d(
                TAG,
                "position: " + position + "getValue isChecked: " + viewHolder.mBinding.cbManual.isChecked
            )
            if ("1".equals(lis[index])) {
                //当它为选择状态时，无需设置，避免闪硕
                if (!viewHolder.mBinding.cbManual.isChecked) { //如果已经选中了，那么我们这边就不会执行了。
                    viewHolder.mBinding.cbManual.isChecked = true
                }
            } else {
                if (viewHolder.mBinding.cbManual.isChecked) {
                    viewHolder.mBinding.cbManual.isChecked = false
                }
            }
        }
    }*/


    private fun showOnOffDialog(
        cmdtype: Int,
        isChecked: Boolean,
        position: Int,
        data: String?
    ) {
        if (okCancelDialog == null) {
            okCancelDialog = this@DebugParamFragment.context?.let { OKCancelDialog(it) }
        }
        okCancelDialog?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    okCancelDialog?.type1 -> {
                        okCancelDialog?.dismiss()
                        if (cmdtype == DebugType.OUT_IO) {
                            mViewModel.setBtnParam(data!!, isChecked, position)
                        } else if (cmdtype == DebugType.PWM1_IO || cmdtype == DebugType.PWM2_IO || cmdtype == DebugType.PWM3_IO) {
                            mViewModel.setLutou(data!!, isChecked, cmdtype)
                        } else if (cmdtype == DebugType.PWMCLEAN) {
                            if (debugParamAdapter?.getState()?.get(24).equals("00")) {
                                ToastUtil.switchToastStyleToWarn(UiUtil.getStringRes(R.string.base_open_head_heating))
                            } else {
                                mViewModel.openClean(data!!, checked = isChecked)
                            }
                        } else if (cmdtype == DebugType.PWMSTUCK) {
                            mViewModel.stuck(data!!)
                        } else if (cmdtype == DebugType.PWMXRESET) {
                            mViewModel.xReset(data!!)
                        }

                    }

                    else -> {

                    }
                }
            }

        })

        okCancelDialog?.show()
    }

}