package com.abbidot.tracker.ui.activity.device.set

import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.DurationSetAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityTrackingDurationSetBinding
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleCmdUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.TrackerSetViewModel
import com.clj.fastble.BleManager

class TrackingDurationSetActivity :
    BaseActivity<ActivityTrackingDurationSetBinding>(ActivityTrackingDurationSetBinding::inflate) {

    private val mTrackerSetViewModel: TrackerSetViewModel by viewModels()

    private lateinit var mDurationSetAdapter: DurationSetAdapter

    //选中的下标
    private var mSelectIndex = -1
    private var mSelectTempIndex = -1

    private var mMapDeviceBean: MapDeviceBean? = null

    override fun getTopBar() = mViewBinding.ilTrackingDurationSetTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.tracker_manage_set_duration)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        intent.extras?.apply {
            mMapDeviceBean = Util.getParcelableAdaptive(
                intent, ConstantString.MapDeviceBean, MapDeviceBean::class.java
            )
        }

        setListData()

        mViewBinding.apply {
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvTrackingDurationSetList, mDurationSetAdapter, top = AppUtils.dpToPx(10)
            )
        }
    }

    override fun liveDataObserve() {
        mTrackerSetViewModel.mReportIntervalLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    showToast(R.string.txt_change_successful)
                    mSelectIndex = mSelectTempIndex
                    ViewUtil.instance.updateDataBeanOnlySelectedItem(
                        mDurationSetAdapter, mDurationSetAdapter.getData(), mSelectIndex
                    )
                }
            })
        }

        //接收发送指令后设备返回的数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mMapDeviceBean?.let {
                if (it.deviceMacId == receiveData.mac) {
                    val data = receiveData.data
                    parseData(data)
                }
            }
        }
    }

    /**
     * 解析数据
     */
    private fun parseData(data: ByteArray?) {
        data?.apply {
            val data0 = SRBleCmdUtil.instance.byteToInt(data[0])
            val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
            val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
            if (data0 == 0x12 && data1 == 1) {
                mMapDeviceBean?.apply {
                    val dataBean = mDurationSetAdapter.getData()[mSelectIndex]
                    if (data2 == 0) {
                        mTrackerSetViewModel.reportInterval(
                            this@TrackingDurationSetActivity,
                            deviceServerId,
                            dataBean.imageId,
                            ConstantInt.Type1
                        )
                    } else {
                        mTrackerSetViewModel.reportInterval(
                            this@TrackingDurationSetActivity,
                            deviceServerId,
                            dataBean.imageId,
                            ConstantInt.Type3
                        )
                    }
                }
            }
        }
    }

    private fun setListData() {
        val durationList = mutableListOf<DataBean>()
        val timeList = mutableListOf(3, 5, 10, 15)
        for (time in timeList) {
            DataBean().apply {
                imageId = time
                name = String.format(getString(R.string.txt_duration_min_unit), "$time")
                durationList.add(this)
            }
        }
        mMapDeviceBean?.apply {
            for (i in 0 until durationList.size) {
                val data = durationList[i]
                if (gnssInterval / 60 == data.imageId) {
                    mSelectIndex = i
                    data.selected = true
                    break
                }
            }
        }
        mDurationSetAdapter = DurationSetAdapter(this, durationList).apply {
            setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    setTrackingDuration(pos)
                }
            })
        }
    }

    fun setTrackingDuration(pos: Int) {
        if (mSelectIndex == pos) return
        mMapDeviceBean?.apply {
            mSelectTempIndex = pos
            val dataBean = mDurationSetAdapter.getData()[pos]
            if (BleManager.getInstance().isConnected(deviceMacId)) {
                mSelectIndex = mSelectTempIndex
                SRBleUtil.instance.isConnectBleSendCmdData(
                    deviceMacId,
                    SRBleCmdUtil.instance.setAndRedGpsDuration(duration = dataBean.imageId * 60L)
                )
            } else {
                mTrackerSetViewModel.reportInterval(
                    this@TrackingDurationSetActivity,
                    deviceServerId,
                    dataBean.imageId,
                    ConstantInt.Type2
                )
            }
        }
    }
}