package com.abbidot.tracker.ui.activity.map

import android.content.Intent
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.view.KeyEvent
import android.view.View
import android.widget.RelativeLayout
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.HomeMapDeviceStateAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleReportDataBean
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.bean.LiveDataBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.bean.PetBean
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.ActivityLiveV3Binding
import com.abbidot.tracker.deprecated.ui.activity.vm.LedLightViewModel
import com.abbidot.tracker.dialog.CommonDialog1
import com.abbidot.tracker.dialog.SelectMapTypeDialog
import com.abbidot.tracker.ui.DebugActivity
import com.abbidot.tracker.ui.common.map.HomeMapCommonV3
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.abbidot.tracker.vm.CountDownTimerViewModel
import com.abbidot.tracker.vm.FencesMapViewModel
import com.abbidot.tracker.vm.FindBleDeviceViewModel
import com.abbidot.tracker.vm.MapLiveViewModel
import com.abbidot.tracker.vm.MapViewModel
import com.clj.fastble.BleManager
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class LiveActivityV3 : BaseActivity<ActivityLiveV3Binding>(ActivityLiveV3Binding::inflate) {

    private val mFencesMapViewModel: FencesMapViewModel by viewModels()
    private val mMapViewModel: MapViewModel by viewModels()
    private val mFindBleDeviceViewModel: FindBleDeviceViewModel by viewModels()
    private val mMapLiveViewModel: MapLiveViewModel by viewModels()
    private val mLedLightViewModel: LedLightViewModel by viewModels()
    private val mCountDownViewModel: CountDownTimerViewModel by viewModels()
    private val mConDeviceViewModel: ConnectionDeviceViewModel by viewModels()

    private var mSelectMapTypeDialog: SelectMapTypeDialog? = null

    private lateinit var mDeviceStateList: MutableList<DataBean>
    private lateinit var mDeviceStateAdapter: HomeMapDeviceStateAdapter

    @Inject
    lateinit var mHomeMapCommon: HomeMapCommonV3
    private lateinit var mFragment: Fragment

    private var mMapDeviceBean: MapDeviceBean? = null

    //启动动画移动地图摄像机
    private var isMoveCamera = true

    //是否显示围栏
    private var isShowFence = true

    //是否显示虚线
    private var isShowDashed = true

    //地图类型，标准和卫星地图
    private var mMapType = ConstantInt.Type0
    private var mShowCenterLocation = ConstantInt.PetLocationType

    //是否是直播跳转
    private var isLiveJump = true
    private var mLiveStatus = 1
    private var mPetBean: PetBean? = null
    private var mTrackBleDevice: BleTrackDeviceBean? = null

    //直播是否开始
    private var isStartLive = false

    //    private val mLiveStateTips = mutableListOf(
//        R.string.txt_starting_live, R.string.txt_con_network, R.string.txt_gps_position
//    )
    private var mStartLiveIndex = 0

    //直播时间 分钟
    private var mLiveTime = 5
    private lateinit var mSpeedUnit: String
    private lateinit var mDistanceUnit: String

    //是否打开了找设备的声音
    private var isOpenSound = false

    //设备Led灯开关
    private var isLedOpen = false
    private var mRequestModeType = ConstantInt.Type1
    private var isCloseBattery = false
    private var isCloseMsg = false

    override fun getTopBar() = null

    override fun initData() {
        super.initData()
        mSpeedUnit = Util.getMetricUnits(mContext, ConstantInt.Type2)
        mDistanceUnit = Util.getMetricUnits(mContext, ConstantInt.Type3)
        intent.extras?.apply {
            isLiveJump = getBoolean(ConstantString.JumpActivity, true)
            isCloseBattery = getBoolean(ConstantString.DeviceAuthorized)
            isCloseMsg = getBoolean(ConstantString.PetAuthorized)
            mMapViewModel.mDeviceMsgType = getInt(ConstantString.Type, ConstantInt.SpecialType)
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        }

        isShowFence = Util.getShowFenceSp()
        isShowDashed = MMKVUtil.getBoolean(MMKVKey.ShowDashedLine, false)

        mViewBinding.apply {
            ViewUtil.instance.viewRotationAnimator(
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.ilDeviceLightBtnState.ivLedBtnState,
                true
            )
            ViewUtil.instance.viewRotationAnimator(
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.ilDeviceLightBtnState.ivLedBtnState,
                true
            )
            ilLiveV2BluetoothFindDevice.ivMapLiveV2BleConState.setValue(0)
            mFragment = mHomeMapCommon.getMapFragment(
                mContext,
                ilLiveV3MapPetLocation,
                llLiveV3MapDeviceBatteryLayout,
                Utils.DATE_FORMAT_PATTERN_EN12,
                isLiveJump
            ) { mapLoadOk() }
            ViewUtil.instance.setMapSwitchLocationButtonImage(
                ivMapLiveV2RefreshBtn, mShowCenterLocation
            )
            setLedBtnEnabled(false)
            mPetBean?.let { p ->
                if (p.deviceType == ConstantInt.Type2) {
                    ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.tvDeviceLightSwitchTitle.text =
                        getString(R.string.txt_tone)
                    ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.tvDeviceLightSwitchTitle.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_sound_image, 0, 0, 0
                    )
                    ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.tvDeviceLightSwitchTitle.text =
                        getString(R.string.txt_tone)
                    ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.tvDeviceLightSwitchTitle.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_sound_image, 0, 0, 0
                    )
                } else {
                    ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.tvDeviceLightSwitchTitle.text =
                        getString(R.string.txt_light)
                    ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.tvDeviceLightSwitchTitle.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_light_svg, 0, 0, 0
                    )
                    ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.tvDeviceLightSwitchTitle.text =
                        getString(R.string.txt_light)
                    ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.tvDeviceLightSwitchTitle.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.icon_light_svg, 0, 0, 0
                    )
                }
            }
            ilLiveV2OperateLayout.tvLiveV2Speed.text = "--$mSpeedUnit"
            ilLiveV2OperateLayout.tvLiveV2Distance.text = "--$mDistanceUnit"
            llLiveV2MapTopPet.ivTopPetBtnSmall.setImageResource(R.drawable.icon_map_type)
            lavLiveV2StateAnim.let {
                it.setAnimation("lottie/loading_dog.json")
                it.playAnimation()
            }

            mDeviceStateList = mutableListOf()
            mMapViewModel.addDeviceDefaultStateData(mContext, mDeviceStateList)
            mDeviceStateAdapter = HomeMapDeviceStateAdapter(mContext, mDeviceStateList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvMapLiveV2DeviceState, mDeviceStateAdapter, bottom = 10
            )
            ilLiveV2BluetoothFindDevice.liveV2BluetoothSignal.setValue(0)
            ilLiveV2BluetoothFindDevice.findBleDeviceRadoView.setValue(0)

            setOnClickListenerViews(
                ilLiveV2OperateLayout.llLiveV2StopLive,
                ivMapLiveV2RefreshBtn,
                ivMapLiveV2BluetoothBtn,
                ilLiveV2BluetoothFindDevice.btnLiveV2StopRadar,
                llLiveV2MapTopPet.ivTopPetBtnSmall,
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.root,
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch,
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch,
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.root,
                ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound,
                ilLiveV2OperateLayout.btnLiveV2Issue,
                ilMapLiveV2IssueLayout.tvCloseIssueBtn,
                ilLiveV3MapDeviceBatteryLayout.ivDeviceCloseBtn,
                ilLiveV3MapPetLocation.ivPetLocationNavigationBtn,
                ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn
            )

            supportFragmentManager.commit {
                add(R.id.fc_live_v2_map_fragment, mFragment)
            }

            mPetBean?.let { pet ->
                if (!isLiveJump) {
                    findBleDevice(pet.macID)
                    llLiveV2StateLayout.visibility = View.GONE
                }

                if (AppUtils.isDebug()) {
                    llLiveV2MapTopPet.homeDataPetHeadSmall.root.setOnLongClickListener {
                        goToDebugActivity(pet)
                        true
                    }
                }
            }
        }
    }

    /**
     * 地图加载好了
     */
    private fun mapLoadOk() {
        showPetNameAndHead()
    }

    override fun liveDataObserve() {
        mCountDownViewModel.mCountDownEndLiveData.observe(this) {
            when (mStartLiveIndex) {
//                0 -> {
//                    mStartLiveIndex++
//                    //显示Connecting to network 30秒
//                    mViewBinding.tvLiveV2StateContent.setText(mLiveStateTips[mStartLiveIndex])
//                    mCountDownViewModel.startCountDown(30)
//                }
//
//                1 -> {
//                    mStartLiveIndex++
//                    //显示GPS positioning
//                    mCountDownViewModel.startCountDown(3 * 60)
//                    mViewBinding.tvLiveV2StateContent.setText(mLiveStateTips[mStartLiveIndex])
//                }
//
//                2 -> {
//                    if (isStartLive) {
//                        mStartLiveIndex++
//                        //显示Starting 5-min Live
//                        val str = String.format(getString(R.string.txt_start_min_live), mLiveTime)
//                        mViewBinding.tvLiveV2StateContent.text = str
//                        mCountDownViewModel.startCountDown(2)
//                    } else {
//                        //直播超时
//                        mLiveStatus = -1
//                        stopLive()
//                    }
//                }
//
                2 -> {
                    mViewBinding.llLiveV2StateLayout.visibility = View.VISIBLE
                    mStartLiveIndex++
                    //显示Starting 5-min Live
                    val str = String.format(getString(R.string.txt_start_min_live), "$mLiveTime")
                    mViewBinding.tvLiveV2StateContent.text = str
                    mCountDownViewModel.startCountDown(5)
                }

                3 -> mViewBinding.llLiveV2StateLayout.visibility = View.GONE
            }
        }
        //获取当前宠物位置和围栏信息
        mMapViewModel.mMapDeviceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()
                    data?.let { d ->
                        d.isCloseBattery = isCloseBattery
                        d.isCloseMsg = isCloseMsg
                        mMapDeviceBean = d
                        setMapData(d)
                        mMapViewModel.setDeviceStateAndWarningData(
                            mContext,
                            mPetBean,
                            d,
                            mViewBinding.ilLiveV3MapDeviceMsg.root,
                            mViewBinding.ilLiveV3MapDeviceMsg.tvDeviceMsgContent,
                            mViewBinding.ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn,
                            mDeviceStateList,
                            mDeviceStateAdapter
                        )
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    LogUtil.e("LiveV2Activity获取当前宠物位置和围栏信息onRequestError，再次请求")
                    if (exceptionCode == mNetworkRequestsFailLimit) {
                        finish()
                    } else {
                        mPetBean?.apply {
                            //获取首页设备信息状态
                            mMapViewModel.getMapDeviceStatus(deviceId, !isLiveJump)
                        }
                    }
                }
            }, showLoading = false)
        }

        mMapLiveViewModel.mMapLiveStatusLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mPetBean?.apply {
//                        SRBleUtil.instance.isConnectBleSendNotifyData(macID)
                        when (mLiveStatus) {
                            //直播超时
                            -1 -> {
                                XEventBus.post(EventName.LiveOpenTimeOut)
                                finishActivity()
                            }
                            //直播结束
                            0 -> {
                                mViewBinding.llLiveV2StateLayout.visibility = View.GONE
//                                showToast(R.string.txt_change_successful, true)
                                finishActivity()
                            }
                            //直播开始
                            else -> {
                                //直播开启后，就去获取直播轨迹
//                                if (!BleManager.getInstance().isConnected(macID)) {
//                                    mMapLiveViewModel.mGetPetLivePointTimeStamp =
//                                        System.currentTimeMillis() / 1000
//                                    mMapLiveViewModel.getPetLivePoint(deviceId)
//                                }
                                mMapLiveViewModel.mGetPetLivePointTimeStamp =
                                    System.currentTimeMillis() / 1000
                                mMapLiveViewModel.getPetLivePoint(deviceId)
                            }
                        }
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    LogUtil.e("HomeV2Activity直播开启错误onRequestError，再次请求")
                    if (exceptionCode == mNetworkRequestsFailLimit) {
                        finishActivity()
                    } else {
                        mPetBean?.apply {
                            mMapLiveViewModel.setupDeviceLiveStatus(
                                this@LiveActivityV3, deviceId, mLiveStatus, mRequestModeType
                            )
                        }
                    }
                }

                override fun onInterceptCode() {
                    setButtonEnabled(
                        mViewBinding.ilLiveV2OperateLayout.llLiveV2StopLive, ConstantInt.Type1
                    )
                    if (mLiveStatus == 1) finishActivity()
                }
            })
        }

        //获取直播轨迹
        mMapLiveViewModel.mMapLiveLiveData.observe(this) {
            mHomeMapCommon.startRefreshUserLocation()
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        setTrackData(this)
                    }
                }
            }, isShowRequestErrorTip = false)
        }

        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { trackBle: BleTrackDeviceBean ->
            mPetBean?.let { p ->
                if (trackBle.mac == p.macID && trackBle.conState != ConState.CONNECTED) {
                    //隐藏蓝牙nearby
                    mViewBinding.ilLiveV3MapDeviceMsg.root.visibility = View.GONE
                }
                mMapDeviceBean?.apply {
                    if (trackBle.mac == deviceMacId) {
                        //蓝牙连接断开更快更新状态
                        mMapViewModel.setDeviceStateAndWarningData(
                            mContext,
                            mPetBean,
                            this,
                            mViewBinding.ilLiveV3MapDeviceMsg.root,
                            mViewBinding.ilLiveV3MapDeviceMsg.tvDeviceMsgContent,
                            mViewBinding.ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn,
                            mDeviceStateList,
                            mDeviceStateAdapter
                        )
                        updateConState(trackBle)
                        //分享设备不可以控制灯
                        if (p.shared == ConstantInt.NoShare) {
                            setLedBtnEnabled(Util.getLedControlState(p.macID, this))
                        }
                    }
                }
            }
        }
//        //接收开蓝牙操作,然后搜索连接设备
//        XEventBus.observe(this, EventName.BluetoothSwitch) { conState: Int ->
//            if (conState == ConState.BLUETOOTH_OFF) {
//                //隐藏蓝牙nearby
//                mViewBinding.ilLiveV3MapDeviceMsg.root.visibility = View.GONE
//                //处理高版本关闭蓝牙开关，不断开蓝牙连接的情况
//                mMapDeviceBean?.apply {
//                    val trackBle = BleTrackDeviceBean()
//                    trackBle.mac = deviceMacId
//                    updateConState(trackBle)
//                }
//            }
//        }
        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            if (conState == ConState.DEVICE_NOT_FOUND) {
                openNetLive(ConstantInt.Type2)
            }
        }

        mLedLightViewModel.mLedSwitchLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mPetBean?.apply {
                        if (!SRBleUtil.instance.isMacConnect(macID)) {
                            mViewBinding.let { m ->
                                m.ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.let { i ->
                                    i.cbDeviceLightSwitch.isChecked = isLedOpen
                                    i.cbDeviceLightSwitch.visibility = View.VISIBLE
                                    i.ilDeviceLightBtnState.root.visibility = View.GONE
                                }
                                m.ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.let { i ->
                                    i.cbDeviceLightSwitch.isChecked = isLedOpen
                                    i.cbDeviceLightSwitch.visibility = View.VISIBLE
                                    i.ilDeviceLightBtnState.root.visibility = View.GONE
                                }
                            }
                        }
                    }
                }

                override fun onInterceptCode() {
                    setErrorLedState()
                }

                override fun onRequestError(exceptionCode: String?) {
                    setErrorLedState()
                }
            })
        }

        //蓝牙上报的数据
        XEventBus.observe(this, EventName.BleReportData) { reportData: BleReportDataBean ->
            mPetBean?.apply {
                if (macID == reportData.mac) updateBleReportData(reportData)
            }
        }

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

    private fun setErrorLedState() {
        mPetBean?.apply {
            if (!SRBleUtil.instance.isMacConnect(macID)) {
                isLedOpen = !isLedOpen
                mViewBinding.let { m ->
                    m.ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.let { i ->
                        i.cbDeviceLightSwitch.isChecked = isLedOpen
                        i.cbDeviceLightSwitch.visibility = View.VISIBLE
                        i.ilDeviceLightBtnState.root.visibility = View.GONE
                    }
                    m.ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.let { i ->
                        i.cbDeviceLightSwitch.isChecked = isLedOpen
                        i.cbDeviceLightSwitch.visibility = View.VISIBLE
                        i.ilDeviceLightBtnState.root.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun finishActivity() {
        val intent = Intent()
        mMapDeviceBean?.let {
            intent.putExtra(ConstantString.DeviceAuthorized, it.isCloseBattery)
            intent.putExtra(ConstantString.PetAuthorized, it.isCloseMsg)
            intent.putExtra(ConstantString.Type, mMapViewModel.mDeviceMsgType)
        }
        setResult(ResultCode.ResultCode_1, intent)
        finish()
    }


    /**
     * 跳转debug调试页面
     */
    private fun goToDebugActivity(petBean: PetBean) {
        val intent = Intent(mContext, DebugActivity::class.java)
        ArrayList<PetBean>().apply {
            add(petBean)
            intent.putParcelableArrayListExtra(ConstantString.Pet, this)
        }
        intent.putExtra(ConstantString.Index, 0)
        startActivity(intent)
    }

    /**
     * 解析蓝牙返回的数据
     */
    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 == 0x06 && data1 == 1) {
                val data3 = SRBleCmdUtil.instance.byteToInt(data[3])
                //开启直播
                if (data2 == 1) {
                    if (data3 == 0) {
                        LogUtil.e("蓝牙开启直播成功")
                        mPetBean?.apply {
                            mRequestModeType = ConstantInt.Type1
                            mMapLiveViewModel.setupDeviceLiveStatus(
                                this@LiveActivityV3, deviceId, mLiveStatus, mRequestModeType
                            )
                        }
                    } else {
                        LogUtil.e("蓝牙开启直播失败")
                        openNetLive(ConstantInt.Type3)
                    }
                } else if (data2 == 0) {
                    mPetBean?.apply {
                        //停止Live直播
                        mRequestModeType = if (data3 == 0) {
                            LogUtil.e("蓝牙停止直播成功")
                            ConstantInt.Type1
                        } else {
                            LogUtil.e("蓝牙停止直播失败")
                            ConstantInt.Type3
                        }
                        mMapLiveViewModel.setupDeviceLiveStatus(
                            this@LiveActivityV3, deviceId, 0, mRequestModeType
                        )
                    }
                }
            } else if (data0 == 3 && data1 == 1) {
                mViewBinding.let { m ->
                    m.ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.let { i ->
                        i.cbDeviceLightSwitch.isChecked = isLedOpen
                        i.cbDeviceLightSwitch.visibility = View.VISIBLE
                        i.ilDeviceLightBtnState.root.visibility = View.GONE
                    }
                    m.ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.let { i ->
                        i.cbDeviceLightSwitch.isChecked = isLedOpen
                        i.cbDeviceLightSwitch.visibility = View.VISIBLE
                        i.ilDeviceLightBtnState.root.visibility = View.GONE
                    }
                }
                val modeType = if (data2 == 0) {
                    ConstantInt.Type1
                } else {
                    ConstantInt.Type3
                }
                mMapDeviceBean?.apply {
                    mLedLightViewModel.setLedSwitch(
                        null, deviceServerId, ledSwitch, modeType
                    )
                }
            }
        }
    }

    /**
     * 开启网络上报直播
     */
    private fun openNetLive(modeType: Int) {
        if (isLiveJump) {
            mPetBean?.apply {
                //刚开始显示Starting Live.
                mCountDownViewModel.startCountDown(2)
                mRequestModeType = modeType
                mMapLiveViewModel.setupDeviceLiveStatus(
                    this@LiveActivityV3, deviceId, mLiveStatus, modeType
                )
            }
        }
    }

    /**
     * 更新蓝牙上报的数据
     */
    private fun updateBleReportData(bleReportDataBean: BleReportDataBean) {
        mMapLiveViewModel.stopGetData()
        mHomeMapCommon.startRefreshUserLocation()
        bleReportDataBean.apply {
            if (haveDeviceStateData) {
                if (null == mMapDeviceBean) mMapDeviceBean = MapDeviceBean()
                mMapDeviceBean?.let {
                    Util.bleReportDataToMapDevice(it, bleReportDataBean)

                    val isOpen = ledSwitch > ConstantInt.Close
                    mViewBinding.ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isChecked =
                        isOpen
                    mViewBinding.ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isChecked =
                        isOpen

//                    if (haveLocationData && liveFlag == ConstantInt.Type1) {
                    if (liveFlag == ConstantInt.Type1) {
                        if (!isStartLive) {
                            isStartLive = true
                            liveStartTip()
                        }
                        if (haveLocationData) {
                            lifecycleScope.launch {
                                locationList?.let { location ->
                                    liveDrawLines(location)
                                }
                            }
                        }
                        setMapDeviceBean(it)
                    } else if (liveFlag == ConstantInt.Type0) {
                        //直播自动结束
                        if (isStartLive) {
                            XEventBus.post(EventName.LiveAutoEnd)
                            finishActivity()
                        }
                    }

                    mMapViewModel.setDeviceStateAndWarningData(
                        mContext,
                        mPetBean,
                        it,
                        mViewBinding.ilLiveV3MapDeviceMsg.root,
                        mViewBinding.ilLiveV3MapDeviceMsg.tvDeviceMsgContent,
                        mViewBinding.ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn,
                        mDeviceStateList,
                        mDeviceStateAdapter
                    )
                }
            }
        }
    }

    /**
     * 远程设置led开关
     */
    private fun setLedSwitch() {
        mPetBean?.let { p ->
            //分享设备不可以点击控制灯
            if (p.shared != ConstantInt.NoShare) {
                return
            }
            isLedOpen = !isLedOpen
            mViewBinding.apply {
                //屏蔽点击就变状态
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.let {
                    it.cbDeviceLightSwitch.isChecked = !isLedOpen
                    it.cbDeviceLightSwitch.visibility = View.GONE
                    it.ilDeviceLightBtnState.root.visibility = View.VISIBLE
                }
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.let {
                    it.cbDeviceLightSwitch.isChecked = !isLedOpen
                    it.cbDeviceLightSwitch.visibility = View.GONE
                    it.ilDeviceLightBtnState.root.visibility = View.VISIBLE
                }

                val ledSwitch = if (isLedOpen) ConstantInt.Open
                else ConstantInt.Close

                mMapDeviceBean?.apply {
                    this.ledSwitch = ledSwitch
                    if (BleManager.getInstance().isConnected(deviceMacId)) {
                        setLedSwitch(ledSwitch)
                    } else {
                        mLedLightViewModel.setLedSwitch(
                            null, deviceServerId, ledSwitch, ConstantInt.Type2
                        )
                    }
                }
            }
        }
    }

    /**
     *发送设备开启关闭led蓝牙指令
     */
    private fun setLedSwitch(mode: Int) {
        mTrackBleDevice?.apply {
            SRBleUtil.instance.setBleLedSwitch(this@LiveActivityV3, bleDevice, mode)
        }
    }

    /**
     * 更新设备连接状态
     */
    private fun updateConState(trackBleDevice: BleTrackDeviceBean) {
        mTrackBleDevice = trackBleDevice
        if (trackBleDevice.conState == ConState.CONNECTED) {
            LogUtil.e("更新设备连接状态")
            if (isLiveJump) {
                if (isStartLive) {
                    mMapLiveViewModel.stopGetData()
                } else {
                    mCountDownViewModel.startCountDown(2)
                    lifecycleScope.launch {
                        //延时几秒发送消息
                        delay(1000)
                        trackBleDevice.apply {
                            SRBleUtil.instance.writeData(
                                bleDevice, SRBleCmdUtil.instance.setLiveSwitch(1, mLiveTime * 60L)
                            )
                        }
                    }
                }
            }
//            showToast(R.string.tracker_manage_set_ble_connect)
//            mViewBinding.ilLiveV2BluetoothFindDevice.ivMapLiveV2BleConState.setValue(2)
        } else if (trackBleDevice.conState == ConState.CONNECTION_FAIL) {
            if (isLiveJump) {
                openNetLive(ConstantInt.Type2)
            }
        } else {
            if (isLiveJump) {
                if (isStartLive) {
                    mPetBean?.apply {
                        //直播开启后，就去获取直播轨迹
                        mMapLiveViewModel.mGetPetLivePointTimeStamp =
                            System.currentTimeMillis() / 1000
                        mMapLiveViewModel.getPetLivePoint(deviceId)
                    }
                } else {
                    openNetLive(ConstantInt.Type2)
                }
            }
        }
    }


    /**
     * 显示地图类型选择弹窗
     */
    private fun showMapTypeDialog() {
        if (null == mSelectMapTypeDialog) {
            mSelectMapTypeDialog = ViewUtil.instance.getMapTypeDialog(
                mContext,
                object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        mMapType = Util.getMapTypeSp()
                        if (pos == mMapType) {
                            return
                        }
                        mHomeMapCommon.switchSatelliteAndNormalMapType()
                    }
                },
                { _, isChecked ->
                    isShowFence = isChecked
                    MMKVUtil.putBoolean(MMKVKey.ShowFence, isChecked)
                    if (isChecked) {
                        mMapDeviceBean?.fences?.let { fences ->
                            mFencesMapViewModel.setFencesData(mContext, fences, mFragment)
                        }
                    } else {
                        mFencesMapViewModel.setFencesData(mContext, null, mFragment)
                    }
                },
                { _, isChecked ->
                    isShowDashed = isChecked
                    MMKVUtil.putBoolean(MMKVKey.ShowDashedLine, isChecked)
                    if (isChecked) {
                        mHomeMapCommon.addUserAndPetLine()
                    } else {
                        mHomeMapCommon.removeUserAndPetLine()
                    }
                })
        } else {
            mSelectMapTypeDialog!!.mapTypeSpToUpdate()
        }
        mSelectMapTypeDialog?.show()
    }

    /**
     * 设置地图相关数据
     */
    private fun setMapData(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            mLiveTime = liveTime / 60

            mPetBean?.apply {
                //查找是否连接了蓝牙
                val bleConDevice = SRBleUtil.instance.getConnectMacDevice(macID)
                if (null == bleConDevice) {
                    if (isLiveJump) {
                        //没有连接，一进入页面就尝试连接
                        if (SRBleUtil.instance.isBleEnable(mContext)) {
                            mConDeviceViewModel.connectDeviceToMac(this@LiveActivityV3, macID)
                        } else {
                            openNetLive(ConstantInt.Type2)
                        }
                    }
                } else {
                    updateConState(bleConDevice)
                }
                mViewBinding.let {
                    //分享设备不可以控制灯
                    if (shared == ConstantInt.NoShare) {
                        setLedBtnEnabled(Util.getLedControlState(deviceMacId, mapDeviceBean))
                    }
                    isLedOpen = ledSwitch == ConstantInt.Open
                    it.ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isChecked =
                        isLedOpen
                    it.ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isChecked =
                        isLedOpen
//                it.tvLiveV2Speed.text = String.format(
//                    getString(R.string.txt_mph_unit),
//                    Utils.formatDecimal(Util.kmhToMph(speed.toDouble()))
//                )
                }
            }

            if (isShowFence) {
                fences?.let { fences ->
                    mFencesMapViewModel.setFencesData(mContext, fences, mFragment)
                }
            }

            mHomeMapCommon.let {
                setMapDeviceBean(this)
                it.refreshPetCurrentLocation(latitude, longitude, isMoveCamera)
                mViewBinding.root.postDelayed({ it.startRippleCircleAnim() }, 1500)
                isMoveCamera = false
//                val userAndPetDistance = it.getUserAndPetDistance()
//                mViewBinding.tvLiveV2Distance.text = String.format(
//                    getString(R.string.txt_ft_unit), Utils.formatDecimal(userAndPetDistance)
//                )
            }
        }
    }

    private fun setLedBtnEnabled(btnEnabled: Boolean) {
        mViewBinding.apply {
            ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.tvDeviceLightSwitchTitle.let {
                val tColor = if (btnEnabled) {
                    R.color.data_black_color
                } else {
                    R.color.grey_color
                }
                val cColor = ContextCompat.getColor(mContext, tColor)
                // 假设只给左侧图标 tint
                val drawables = ContextCompat.getDrawable(mContext, R.drawable.icon_light_svg)
                drawables?.let { d ->
                    val wrappedDrawable = DrawableCompat.wrap(d)
                    DrawableCompat.setTint(wrappedDrawable, cColor)
                    DrawableCompat.setTintMode(wrappedDrawable, PorterDuff.Mode.SRC_IN)
                    it.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null)
                }
                it.setTextColor(cColor)
            }
            ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isEnabled = btnEnabled
            ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.root.isEnabled = btnEnabled
            ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.root.isEnabled = btnEnabled
            ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isEnabled =
                btnEnabled
        }
    }

    private fun setMapDeviceBean(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            mViewBinding.ilLiveV3MapDeviceBatteryLayout.let {
                mMapViewModel.setMapDeviceBattery(
                    mContext, mapDeviceBean, it.root, it.tvDeviceBatteryInfo, it.ivDeviceCloseBtn
                )
            }
            mViewBinding.ilLiveV3MapPetLocation.let {
                mMapViewModel.setPetLocationReverseGeocode(
                    mContext, mapDeviceBean, it.root, it.tvPetLocationReverseGeocode
                )
            }
            mHomeMapCommon.setMapDeviceBean(this)
        }
    }


    /**
     * 显示选择宠物
     */
    private fun showPetNameAndHead() {
        mPetBean?.apply {
            showLoading(true)
            mViewBinding.llLiveV2MapTopPet.homeDataPetNameSmall.let {
                it.text = petName
                it.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
            }
            mViewBinding.llLiveV2MapTopPet.homeDataPetHeadSmall.appHeadImage.let {
                ViewUtil.instance.setPetTypeHead(it, imgurl, petType)
                ViewUtil.instance.viewAlphaAndRotationObjectAnimator(it)
            }
            //重新设置地图宠物头像
            mHomeMapCommon.setPetHeadIcon(imgurl, petType)

            //获取首页设备信息状态
            mMapViewModel.getMapDeviceStatus(deviceId, !isLiveJump)
        }
    }

    private fun setTrackData(liveDataBean: LiveDataBean) {
        //测试经纬度移动
//        mFencesViewModel.setFencesData(mContext!!, isInFence, mFencesList, mFragment)

        mViewBinding.apply {

            liveDataBean.deviceInfo?.apply {
                if (liveFlag == ConstantInt.Type0) {
                    //直播自动结束
                    if (isStartLive) {
                        XEventBus.post(EventName.LiveAutoEnd)
                        finishActivity()
                    }
                    return
                } else if (liveFlag == ConstantInt.Type1) {
                    if (!isStartLive) {
                        liveStartTip()
                        isStartLive = true
                    }
                }

                val speedStr = Util.metricConvertUnits(
                    speed, ConstantInt.Type2, 2
                ).toString() + mSpeedUnit
                ilLiveV2OperateLayout.tvLiveV2Speed.text = speedStr

                mMapDeviceBean?.let { m ->
                    isCloseMsg = m.isCloseMsg
                    isCloseBattery = m.isCloseBattery
                    canShowBattery = m.canShowBattery
                }
                setMapDeviceBean(this)
                val isOpen = ledSwitch == ConstantInt.Open
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isChecked = isOpen
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isChecked =
                    isOpen
                mMapViewModel.setDeviceStateAndWarningData(
                    mContext,
                    mPetBean,
                    this,
                    mViewBinding.ilLiveV3MapDeviceMsg.root,
                    mViewBinding.ilLiveV3MapDeviceMsg.tvDeviceMsgContent,
                    mViewBinding.ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn,
                    mDeviceStateList,
                    mDeviceStateAdapter
                )

                liveDataBean.livePoints?.apply {
                    if (size > 0) {
                        mMapLiveViewModel.mGetPetLivePointTimeStamp =
                            System.currentTimeMillis() / 1000
                        //只有一个点的时候,不用休眠
                        val sleepTime =
                            if (size - 1 > 0) mMapLiveViewModel.mRefreshTime / (size - 1) * 1000L
                            else 0
                        lifecycleScope.launch {
                            forEach {
                                liveDrawLine(it.latitude, it.longitude)
                                //休眠几秒再画线
                                if (sleepTime > 0) delay(sleepTime)
                            }
                        }
                    }
                }
                if (isShowDashed) {
                    mHomeMapCommon.addUserAndPetLine()
                }
            }
        }
    }

    /**
     * 直播开始提示
     */
    private fun liveStartTip() {
        LogUtil.e("直播开始了")
        if (mStartLiveIndex == 0) {
            mStartLiveIndex = 2
            //直播开始显示Starting 5-min Live
            mCountDownViewModel.startCountDown(1)
            mHomeMapCommon.greenRippleCircleAnim()
        }
    }

    /**
     * 直播画线
     */
    private fun liveDrawLine(latitude: Double, longitude: Double) {
        mHomeMapCommon.addTrackLine(latitude, longitude)
        val userAndPetDistance = mHomeMapCommon.getUserAndPetDistance()
        val distanceStr = Util.metricConvertUnits(
            userAndPetDistance.toFloat(), ConstantInt.Type3, 2
        ).toString() + mDistanceUnit
        mViewBinding.ilLiveV2OperateLayout.tvLiveV2Distance.text = distanceStr
    }

    /**
     * 直播画线
     */
    private fun liveDrawLines(trackList: MutableList<HistoryDataBean>) {
        mHomeMapCommon.addTrackLines(trackList)
        val userAndPetDistance = mHomeMapCommon.getUserAndPetDistance()
        val distanceStr = Util.metricConvertUnits(
            userAndPetDistance.toFloat(), ConstantInt.Type3, 2
        ).toString() + mDistanceUnit
        mViewBinding.ilLiveV2OperateLayout.tvLiveV2Distance.text = distanceStr
    }

    /**
     * 显示隐藏找蓝牙设备布局
     */
    private fun showAndHideFindLayout() {
        mViewBinding.apply {
            llLiveV3MapDeviceBatteryLayout.visibility = View.INVISIBLE
            val relativeLayout = ivMapLiveV2RefreshBtn.layoutParams as RelativeLayout.LayoutParams
            ivMapLiveV2RefreshBtn.visibility = View.GONE
            ilLiveV3MapPetLocation.root.visibility = View.INVISIBLE
            if (ilLiveV2BluetoothFindDevice.root.isGone) {
                //找蓝牙设备布局显示
                YoYo.with(Techniques.BounceInUp).duration(800).onStart {
                    ilLiveV2OperateLayout.root.visibility = View.GONE
                    ilLiveV2BluetoothFindDevice.root.visibility = View.VISIBLE
                }.onEnd {
                    //刷新定位按钮显示动画
                    ViewUtil.instance.viewShowFadeInAnimation(ivMapLiveV2RefreshBtn)
                }.playOn(ilLiveV2BluetoothFindDevice.root)

                ivMapLiveV2BluetoothBtn.visibility = View.GONE
                relativeLayout.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
                relativeLayout.addRule(RelativeLayout.ABOVE, R.id.il_live_v2_bluetooth_find_device)
            } else {
                //找蓝牙设备布局退出
                YoYo.with(Techniques.SlideOutDown).duration(600).onEnd {
                    ilLiveV2BluetoothFindDevice.root.visibility = View.GONE
                    ilLiveV2OperateLayout.root.visibility = View.VISIBLE
                }.playOn(ilLiveV2BluetoothFindDevice.root)
                //直播操作按钮布局显示
                YoYo.with(Techniques.BounceInUp).duration(800).delay(400).onEnd {
                    //蓝牙图标按钮显示动画
                    ViewUtil.instance.viewShowFadeInAnimation(ivMapLiveV2BluetoothBtn)
                    ViewUtil.instance.viewShowFadeInAnimation(ilLiveV3MapPetLocation.root)
                    //刷新定位按钮显示动画
                    ViewUtil.instance.viewShowFadeInAnimation(ivMapLiveV2RefreshBtn)
                }.playOn(ilLiveV2OperateLayout.root)

                relativeLayout.removeRule(RelativeLayout.ABOVE)
                relativeLayout.addRule(RelativeLayout.ABOVE, R.id.il_live_v3_map_pet_location)
            }

            root.postDelayed({
                mHomeMapCommon.setMarkerInfoViewOffset()
            }, 1000)
        }
    }

    /**
     * 显示直播问题
     */
    private fun showLiveIssue() {
        mViewBinding.apply {
            llLiveV3MapDeviceBatteryLayout.visibility = View.INVISIBLE
            if (ilMapLiveV2IssueLayout.root.isGone) {
                YoYo.with(Techniques.BounceInUp).duration(700).onStart {
                    ilLiveV2OperateLayout.root.visibility = View.GONE
                    ilLiveV3MapPetLocation.root.visibility = View.INVISIBLE
                    ilMapLiveV2IssueLayout.root.visibility = View.VISIBLE
                }.playOn(ilMapLiveV2IssueLayout.root)
            } else {
                YoYo.with(Techniques.SlideOutDown).duration(600).onEnd {
                    ilMapLiveV2IssueLayout.root.visibility = View.GONE
                    YoYo.with(Techniques.BounceInUp).duration(600).onStart {
                        ilLiveV3MapPetLocation.root.visibility = View.VISIBLE
                        ilLiveV2OperateLayout.root.visibility = View.VISIBLE
                    }.playOn(ilLiveV2OperateLayout.root)
                }.playOn(ilMapLiveV2IssueLayout.root)
            }

            root.postDelayed({
                mHomeMapCommon.setMarkerInfoViewOffset()
            }, 1000)
        }
    }

    /**
     * 找蓝牙设备
     */
    private fun findBleDevice(mac: String) {
        Util.checkBluetoothPermissionsEnabled(this, {
            showAndHideFindLayout()
            mViewBinding.ilLiveV2BluetoothFindDevice.apply {
                mFindBleDeviceViewModel.startScanFind(
                    this@LiveActivityV3,
                    mac.uppercase(),
                    liveV2BluetoothSignal,
                    findBleDeviceRadoView,
                    ivMapLiveV2BleConState
                )
            }
        })
    }

    override fun listenBackPressed() {
        if (isLiveJump) stopMapLive()
        else super.listenBackPressed()
    }

    private fun stopMapLive() {
        CommonDialog1(
            mContext,
            "",
            getString(R.string.txt_stop_live_tips),
            false,
            5f,
            Typeface.BOLD,
            R.color.data_black_color,
            canceledOnTouchOutside = true,
            okClickListener = object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    mMapDeviceBean?.apply {
                        mLiveStatus = 0
                        stopLive()
                    }
                }
            }).show()
    }

    /**
     * 停止直播
     */
    private fun stopLive() {
        mPetBean?.apply {
            setButtonEnabled(mViewBinding.ilLiveV2OperateLayout.llLiveV2StopLive, ConstantInt.Type0)
            if (BleManager.getInstance().isConnected(macID)) {
                SRBleUtil.instance.isConnectBleSendCmdData(
                    macID, SRBleCmdUtil.instance.setLiveSwitch(0, 0)
                )
            } else {
                mRequestModeType = ConstantInt.Type2
                mMapLiveViewModel.setupDeviceLiveStatus(
                    this@LiveActivityV3, mPetBean!!.deviceId, 0, mRequestModeType
                )
            }
        }

    }

    /**
     * 设置找设备声音音量
     */
    private fun setSound() {
        if (isOpenSound) {
            mFindBleDeviceViewModel.setVolume(0)
            mViewBinding.ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound.setImageResource(R.drawable.icon_sound_off_svg)
        } else {
            mFindBleDeviceViewModel.setVolume(mFindBleDeviceViewModel.mMaxVolume)
            mViewBinding.ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound.setImageResource(R.drawable.icon_sound_on_svg)
        }
        isOpenSound = !isOpenSound
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mViewBinding.ilLiveV2BluetoothFindDevice.root.isVisible) {
            when (keyCode) {
                KeyEvent.KEYCODE_VOLUME_DOWN -> {
                    val volume = mFindBleDeviceViewModel.getVolume()
                    if (volume == 1 && isOpenSound) {
                        isOpenSound = false
                        mViewBinding.ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound.setImageResource(
                            R.drawable.icon_sound_off_svg
                        )
                    }
                    LogUtil.e("音量减小--,$volume")
                }

                KeyEvent.KEYCODE_VOLUME_UP -> {
                    LogUtil.e("音量增加++")
                    if (!isOpenSound) {
                        isOpenSound = true
                        mViewBinding.ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound.setImageResource(
                            R.drawable.icon_sound_on_svg
                        )
                    }
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ivMapLiveV2RefreshBtn -> {
                    mShowCenterLocation = if (mShowCenterLocation == ConstantInt.PetLocationType) {
                        ConstantInt.UserLocationType
                    } else {
                        ConstantInt.PetLocationType
                    }
                    ViewUtil.instance.setMapSwitchLocationButtonImage(
                        ivMapLiveV2RefreshBtn, mShowCenterLocation
                    )
                    mHomeMapCommon.switchShowLocation(mShowCenterLocation)
                }

                ivMapLiveV2BluetoothBtn -> mPetBean?.apply {
                    findBleDevice(macID)
                }

                ilLiveV2BluetoothFindDevice.btnLiveV2StopRadar -> {
                    if (isLiveJump) {
                        isOpenSound = true
                        setSound()
                        mFindBleDeviceViewModel.stopPlay()
                        showAndHideFindLayout()
                    } else {
                        mFindBleDeviceViewModel.stopPlay()
                        mFindBleDeviceViewModel.stopFindDevice()
                        finishActivity()
                    }
                }

                llLiveV2MapTopPet.ivTopPetBtnSmall -> showMapTypeDialog()
                ilLiveV2OperateLayout.llLiveV2StopLive -> stopMapLive()
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.root, ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch, ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch, ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.root -> setLedSwitch()

                ilLiveV2OperateLayout.btnLiveV2Issue -> showLiveIssue()
                ilMapLiveV2IssueLayout.tvCloseIssueBtn -> showLiveIssue()
                ilLiveV2BluetoothFindDevice.ivLiveV2FindDeviceSound -> setSound()
                ilLiveV3MapDeviceBatteryLayout.ivDeviceCloseBtn -> {
                    mMapDeviceBean?.isCloseBattery = true
                    llLiveV3MapDeviceBatteryLayout.visibility = View.INVISIBLE
                }

                ilLiveV3MapDeviceMsg.ivDeviceMsgCloseBtn -> {
                    mMapDeviceBean?.isCloseMsg = true
                    ilLiveV3MapDeviceMsg.root.visibility = View.GONE
                }

                ilLiveV3MapPetLocation.ivPetLocationNavigationBtn -> {
                    if (isLimitClick()) return
                    mMapViewModel.showNavigationDialog(this@LiveActivityV3, mMapDeviceBean)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBinding.lavLiveV2StateAnim.cancelAnimation()
//        stopLive()
    }
}