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

import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityPowerOffBinding
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.ConnectionDeviceViewModel
import com.clj.fastble.BleManager

class PowerOffActivity : BaseActivity<ActivityPowerOffBinding>(ActivityPowerOffBinding::inflate) {

    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()

    private var mPetBean: PetBean? = null

    override fun getTopBar() = mViewBinding.ilPowerOffTopBar.titleTopBar

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

        intent.extras?.apply {
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        }

        mViewBinding.apply {
            setOnClickListenerViews(btnPowerOffYes, ilPowerOffBluetoothTips.trbBleConnectState)
        }

        connectBle()
    }

    override fun liveDataObserve() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            showLoading(false)
            mViewBinding.ilPowerOffBluetoothTips.trbBleConnectState.let { view ->
                val bgColor = if (ble.conState == ConState.CONNECTED) {
                    ViewUtil.instance.viewShowFadeInAnimation(mViewBinding.btnPowerOffYes)
                    view.text = getString(R.string.tracker_manage_set_ble_connect)
                    ContextCompat.getColor(mContext, R.color.cyan_color1)
                } else {
                    ViewUtil.instance.viewHideFadeInAnimation(
                        mViewBinding.btnPowerOffYes, hideType = View.INVISIBLE
                    )
                    view.text = getString(R.string.tracker_manage_set_ble_unconnect)
                    ContextCompat.getColor(mContext, R.color.red_color4)
                }
                view.setBackgroundColor(bgColor)
            }
        }

        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            ViewUtil.instance.viewHideFadeInAnimation(
                mViewBinding.btnPowerOffYes, hideType = View.INVISIBLE
            )
            mViewBinding.ilPowerOffBluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState)
            }
        }

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

    /**
     * 解析数据
     */
    private fun parseData(data: ByteArray?) {
        if (null != data && data.isNotEmpty()) {
            val data0 = SRBleCmdUtil.instance.byteToInt(data[0])
            val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
            val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
            if (data0 == 0x18 && data1 == 1) {
                if (data2 == 0) showToast(R.string.txt_done, true)
                else if (data2 == 3) {
                    setButtonEnabled(mViewBinding.btnPowerOffYes)
                    showToast(R.string.txt_on_charging)
                }
            }
        }
    }

    private fun connectBle() {
        mPetBean?.apply {
            //是否连接了蓝牙
            if (BleManager.getInstance().isConnected(macID)) {
                ViewUtil.instance.viewShowFadeInAnimation(mViewBinding.btnPowerOffYes)
                mViewBinding.ilPowerOffBluetoothTips.trbBleConnectState.let {
                    it.setBackgroundColor(
                        ContextCompat.getColor(mContext, R.color.cyan_color1)
                    )
                    it.text = getString(R.string.tracker_manage_set_ble_connect)
                }
            } else {
                mConnectionDeviceViewModel.connectDeviceToMac(
                    this@PowerOffActivity, macID
                )
            }
        }
    }

    private fun bleTurnOff() {
        mPetBean?.apply {
            SRBleUtil.instance.getConnectMacDevice(macID)?.let {
                setButtonEnabled(mViewBinding.btnPowerOffYes)
                val cmd = SRBleCmdUtil.instance.forcedShutdown()
                SRBleUtil.instance.writeData(it.bleDevice, cmd)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnPowerOffYes -> bleTurnOff()

                ilPowerOffBluetoothTips.trbBleConnectState -> {
                    mPetBean?.apply {
                        ViewUtil.instance.connectionBtn(
                            mContext,
                            ilPowerOffBluetoothTips.trbBleConnectState.text.toString(),
                            macID
                        ) {
                            connectBle()
                        }
                    }
                }
            }
        }
    }
}