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

import android.content.Intent
import android.graphics.Typeface
import android.view.View
import android.widget.RelativeLayout
import androidx.activity.viewModels
import androidx.core.view.isGone
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.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.tracker.R
import com.abbidot.tracker.adapter.HomeMapDeviceMsgAdapter
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.ActivityLiveV2Binding
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.HomeMapCommon
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.abbidot.tracker.widget.MapDeviceNetView
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 LiveActivityV2 : BaseActivity<ActivityLiveV2Binding>(ActivityLiveV2Binding::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
    private lateinit var mDeviceMsgList: MutableList<DataBean>
    private lateinit var mDeviceMsgAdapter: HomeMapDeviceMsgAdapter

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

    private var mMapDeviceBean: MapDeviceBean? = null

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

    //是否显示围栏
    private var isShowFence = 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

    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)
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        }

        isShowFence = Util.getShowFenceSp()

        mViewBinding.apply {
            ilLiveV2BluetoothFindDevice.ivMapLiveV2BleConState.setValue(0)
            mFragment = mHomeMapCommon.getMapFragment(
                mContext, miLiveV2MapAddressView, dnLiveV2MapNetView
            ) { mapLoadOk() }
            dnLiveV2MapNetView.setShowNetType(MapDeviceNetView.NO_NET_TYPE)
            ViewUtil.instance.setMapSwitchLocationButtonImage(
                ivMapLiveV2RefreshBtn, mShowCenterLocation
            )
            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()
            mDeviceMsgList = mutableListOf()
            mMapViewModel.addDeviceDefaultStateData(mContext, mDeviceStateList)
            mDeviceStateAdapter = HomeMapDeviceStateAdapter(mContext, mDeviceStateList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvMapLiveV2DeviceState, mDeviceStateAdapter, bottom = 10
            )

            mDeviceMsgAdapter = HomeMapDeviceMsgAdapter(mContext, mDeviceMsgList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvLiveV2MapDeviceMsg, mDeviceMsgAdapter, 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
            )

            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?.apply {
                        mMapDeviceBean = data
                        setMapData(data)
                        mMapViewModel.setDeviceStateAndWarningData(
                            mContext,
                            mPetBean,
                            data,
                            mDeviceStateList,
                            mDeviceStateAdapter,
                            mDeviceMsgList,
                            mDeviceMsgAdapter,
                            mViewBinding.rvLiveV2MapDeviceMsg,
                            true
                        )
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    LogUtil.e("LiveV2Activity获取当前宠物位置和围栏信息onRequestError，再次请求")
                    if (exceptionCode == mNetworkRequestsFailLimit) {
                        finish()
                    } else {
                        mPetBean?.apply {
                            //获取首页设备信息状态
                            mMapViewModel.getMapDeviceStatus(deviceId, false)
                        }
                    }
                }
            }, 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)
                                finish()
                            }
                            //直播结束
                            0 -> {
                                mViewBinding.llLiveV2StateLayout.visibility = View.GONE
//                                showToast(R.string.txt_change_successful, true)
                                finish()
                            }
                            //直播开始
                            else -> {
                                //直播开启后，就去获取直播轨迹
                                if (!BleManager.getInstance().isConnected(macID)) {
                                    mMapLiveViewModel.mGetPetLivePointTimeStamp =
                                        System.currentTimeMillis() / 1000
                                    mMapLiveViewModel.getPetLivePoint(deviceId)
                                }
                            }
                        }
                    }
                }

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

        //获取直播轨迹
        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?.apply {
                if (trackBle.mac == macID && trackBle.conState != ConState.CONNECTED) {
                    mViewBinding.rvLiveV2MapDeviceMsg.visibility = View.GONE
                }
            }
            mMapDeviceBean?.apply {
                if (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) {
//                    mViewBinding.cbLiveV2DeviceLightSwitch.isChecked =
//                        !mViewBinding.cbLiveV2DeviceLightSwitch.isChecked
//                    showToast(R.string.txt_please_wait)
                }
            })
        }

        //蓝牙上报的数据
        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)
                }
            }
        }
    }


    /**
     * 跳转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@LiveActivityV2, 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@LiveActivityV2, deviceId, 0, mRequestModeType
                        )
                    }
                }
            } else if (data0 == 3 && data1 == 1) {
                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@LiveActivityV2, deviceId, mLiveStatus, modeType
                )
            }
        }
    }

    /**
     * 更新蓝牙上报的数据
     */
    private fun updateBleReportData(bleReportDataBean: BleReportDataBean) {
        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)
                                }
                            }
                        }
                        mHomeMapCommon.setMapDeviceBean(it)
                    } else if (liveFlag == ConstantInt.Type0) {
                        //直播自动结束
                        if (isStartLive) {
                            XEventBus.post(EventName.LiveAutoEnd)
                            finish()
                        }
                    }
                }

                mMapViewModel.setDeviceStateAndWarningData(
                    mContext,
                    mPetBean,
                    mMapDeviceBean!!,
                    mDeviceStateList,
                    mDeviceStateAdapter,
                    mDeviceMsgList,
                    mDeviceMsgAdapter,
                    mViewBinding.rvLiveV2MapDeviceMsg
                )
            }
        }
    }

    /**
     * 远程设置led开关
     */
    private fun setLedSwitch() {
        isLedOpen = !isLedOpen
        mViewBinding.apply {
            //屏蔽点击就变状态
//            cbLiveV2DeviceLightSwitch.isChecked = !cbLiveV2DeviceLightSwitch.isChecked
            ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isChecked = isLedOpen
            ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isChecked =
                isLedOpen
            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(mContext, 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 && isStartLive) {
                mPetBean?.apply {
                    //直播开启后，就去获取直播轨迹
                    mMapLiveViewModel.mGetPetLivePointTimeStamp = System.currentTimeMillis() / 1000
                    mMapLiveViewModel.getPetLivePoint(deviceId)
                }
            }
        }
    }


    /**
     * 显示地图类型选择弹窗
     */
    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()
                    }
                }) { v, isChecked ->
                if (v.id == R.id.cb_dialog_map_fences_switch) {
                    isShowFence = isChecked
                    MMKVUtil.putBoolean(MMKVKey.ShowFence, isChecked)
                    if (isChecked) {
                        mMapDeviceBean?.fences?.let { fences ->
                            mFencesMapViewModel.setFencesData(mContext, fences, mFragment)
                        }
                    } else {
                        mFencesMapViewModel.setFencesData(mContext, null, mFragment)
                    }
                }
            }
        } 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@LiveActivityV2, macID)
                        } else {
                            openNetLive(ConstantInt.Type2)
                        }
                    }
                } else {
                    updateConState(bleConDevice)
                }
            }

            mViewBinding.let {
                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 {
                it.setMapDeviceBean(this)
                it.refreshPetCurrentLocation(latitude, longitude, isMoveCamera)
                it.startRippleCircleAnim()
                isMoveCamera = false
//                val userAndPetDistance = it.getUserAndPetDistance()
//                mViewBinding.tvLiveV2Distance.text = String.format(
//                    getString(R.string.txt_ft_unit), Utils.formatDecimal(userAndPetDistance)
//                )
            }
        }
    }


    /**
     * 显示选择宠物弹窗
     */
    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, false)
        }
    }

    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)
                        finish()
                    }
                    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

                mHomeMapCommon.setMapDeviceBean(this)
                val isOpen = ledSwitch == ConstantInt.Open
                ilLiveV2OperateLayout.ilLiveV2DataLightSwitch.cbDeviceLightSwitch.isChecked = isOpen
                ilLiveV2BluetoothFindDevice.ilLiveV2RadarLightSwitch.cbDeviceLightSwitch.isChecked =
                    isOpen
                mMapViewModel.setDeviceStateAndWarningData(
                    mContext,
                    mPetBean,
                    this,
                    mDeviceStateList,
                    mDeviceStateAdapter,
                    mDeviceMsgList,
                    mDeviceMsgAdapter,
                    rvLiveV2MapDeviceMsg,
                    true
                )

                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)
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 直播开始提示
     */
    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 {
            miLiveV2MapAddressView.visibility = View.GONE
            val relativeLayout = ivMapLiveV2RefreshBtn.layoutParams as RelativeLayout.LayoutParams
            ivMapLiveV2RefreshBtn.visibility = View.GONE
            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(ivMapLiveV2RefreshBtn)
                }.playOn(ilLiveV2OperateLayout.root)

                relativeLayout.removeRule(RelativeLayout.ABOVE)
                relativeLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            }

            root.postDelayed({
                miLiveV2MapAddressView.visibility = View.VISIBLE
                mHomeMapCommon.setMarkerInfoViewOffset()
            }, 1000)
        }
    }

    /**
     * 显示直播问题
     */
    private fun showLiveIssue() {
        mViewBinding.apply {
            miLiveV2MapAddressView.visibility = View.GONE
            if (ilMapLiveV2IssueLayout.root.isGone) {
                YoYo.with(Techniques.BounceInUp).duration(700).onStart {
                    ilLiveV2OperateLayout.root.visibility = View.GONE
                    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 {
                        ilLiveV2OperateLayout.root.visibility = View.VISIBLE
                    }.playOn(ilLiveV2OperateLayout.root)
                }.playOn(ilMapLiveV2IssueLayout.root)
            }

            root.postDelayed({
                miLiveV2MapAddressView.visibility = View.VISIBLE
                mHomeMapCommon.setMarkerInfoViewOffset()
            }, 1000)
        }
    }

    /**
     * 找蓝牙设备
     */
    private fun findBleDevice(mac: String) {
        Util.checkBluetoothPermissionsEnabled(mContext, {
            showAndHideFindLayout()
            mViewBinding.ilLiveV2BluetoothFindDevice.apply {
                mFindBleDeviceViewModel.startScanFind(
                    this@LiveActivityV2,
                    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@LiveActivityV2, 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 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()
                        showAndHideFindLayout()
                    } else {
                        mFindBleDeviceViewModel.stopFindDevice()
                        finish()
                    }
                }

                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()
            }
        }
    }

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