package com.abbidot.tracker.ui.fragment.device

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.viewModels
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.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.FencesZoneAdapter
import com.abbidot.tracker.adapter.HomePetTrackMenuAdapter
import com.abbidot.tracker.adapter.HomePetTrackStateAdapter
import com.abbidot.tracker.adapter.WiFiZoneAdapter
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.BleReportDataBean
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.FencesBean
import com.abbidot.tracker.bean.FirmwareBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.bean.WiFiZoneBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.constant.MultipleEntity
import com.abbidot.tracker.databinding.FragmentHomeTrackBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.LedLightViewModel
import com.abbidot.tracker.dialog.DFUNewDialog
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.device.fences.VirtualFencesActivity
import com.abbidot.tracker.ui.activity.device.wifi.PowerSavingSetActivity
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.DeviceDFUViewModel
import com.abbidot.tracker.vm.DownLoadFileViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import com.abbidot.tracker.vm.TrackerSetViewModel
import com.clj.fastble.BleManager
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import no.nordicsemi.android.dfu.DfuServiceListenerHelper


/**
 * 首页Track切换页面
 * create an instance of this fragment.
 */
class HomeTrackFragment :
    BaseFragment<FragmentHomeTrackBinding>(FragmentHomeTrackBinding::inflate) {

    private val mTrackerInfoViewModel: TrackerInfoViewModel by viewModels()
    private val mTrackerSetViewModel: TrackerSetViewModel by viewModels()
    private val mLedLightViewModel: LedLightViewModel by viewModels()
    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()
    private val mDeviceDFUViewModel: DeviceDFUViewModel by viewModels()
    private val mDownLoadFileViewModel: DownLoadFileViewModel by viewModels()

    private lateinit var mHomePetTrackStateAdapter: HomePetTrackStateAdapter
    private lateinit var mTrackStateList: MutableList<MenuTxtBean>

    private lateinit var mFencesAdapter: FencesZoneAdapter
    private lateinit var mFencesList: MutableList<FencesBean>

    private lateinit var mZoneAdapter: WiFiZoneAdapter
    private lateinit var mZoneList: MutableList<WiFiZoneBean>

    private lateinit var mTrackMenuAdapter: HomePetTrackMenuAdapter
    private lateinit var mTrackMenuList: MutableList<MenuTxtBean>

    private var mDFUNewDialogDialog: DFUNewDialog? = null
//    private var mTrackerDFUStateDialog: TrackerDFUStateDialog? = null
//    private lateinit var mDFUStateAdapter: DFUStateAdapter

    private var mMapDeviceBean: MapDeviceBean? = null
    private var mBleTrackDeviceBean: BleTrackDeviceBean? = null

    //是否是dfu的返回的
    private var isDFUCallback = false
    private var mFirmwareBean: FirmwareBean? = null
    private var isSwitchPet = true
    private var mLedMac = ""

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = HomeTrackFragment().apply {
            mContext = context
        }
    }

    override fun initData() {
        mViewBinding.apply {
            root.setBackgroundResource(R.color.transparent)
            addStateListData()
            mHomePetTrackStateAdapter =
                HomePetTrackStateAdapter(mContext!!, mTrackStateList).apply {
                    setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                        override fun onItemClick(itemView: View?, pos: Int) {
                            when (pos) {
                                0 -> {
                                    val value = mHomePetTrackStateAdapter.getData()[pos].menuValue
                                    if (value == getString(R.string.txt_offline)) showToast(
                                        R.string.txt_no_signal_tip, gravity = Gravity.CENTER
                                    )
                                }

                                1 -> {
                                    val value = mHomePetTrackStateAdapter.getData()[pos].menuValue
                                    if (value == getString(R.string.txt_no_signal)) showToast(
                                        R.string.txt_no_signal_tip, gravity = Gravity.CENTER
                                    )
                                }

                                4 -> {
                                    val share = MMKVUtil.getInt(MMKVKey.Shared)
                                    if (share != ConstantInt.NoShare) {
                                        LogUtil.e("分享的设备,不可点击")
                                        return
                                    }
                                    connectionBtn(getData()[pos].menuValue)
                                }

                                5 -> {
                                    val share = MMKVUtil.getInt(MMKVKey.Shared)
                                    if (share != ConstantInt.NoShare) {
                                        LogUtil.e("分享的设备,不可点击")
                                        return
                                    }
                                    if (mHomePetTrackStateAdapter.getData()[pos].type == ConstantInt.SpecialType) {
                                        return
                                    }
                                    setLedSwitch()
                                }
                            }
                        }
                    })
                }
            ViewUtil.instance.setRecyclerViewGridLayout(
                mContext!!,
                rvHomePetTrackState,
                mHomePetTrackStateAdapter,
                3,
                itemWidth = AppUtils.dpToPx(110),
                top = QMUIDisplayHelper.dpToPx(8),
                offset = AppUtils.dpToPx(16)
            )
            mFencesAdapter = FencesZoneAdapter(mContext!!, mFencesList, false).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        getHomeV2Activity()?.getPet()?.apply {
                            goPetDataActivity(VirtualFencesActivity::class.java)
                        }
                    }
                })
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        val share = MMKVUtil.getInt(MMKVKey.Shared)
                        if (share == ConstantInt.NoShare) {
                            getHomeV2Activity()?.getPet()?.let { pet ->
                                if (Util.checkPackageLimit(getHomeV2Activity()!!, pet.deviceId)) {
                                    return
                                }
                            }
                            goPetDataActivity(VirtualFencesActivity::class.java)
                        }
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!,
                rvHomePetTrackVirtualFences,
                mFencesAdapter,
                top = QMUIDisplayHelper.dpToPx(18)
            )

            mZoneAdapter = WiFiZoneAdapter(mContext!!, mZoneList, false).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        goPetDataActivity(PowerSavingSetActivity::class.java)
                    }
                })
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        val share = MMKVUtil.getInt(MMKVKey.Shared)
                        if (share == ConstantInt.NoShare) {
                            mMapDeviceBean?.let {
                                if (it.powerSwitch != ConstantInt.Type0) {
                                    goPetDataActivity(PowerSavingSetActivity::class.java)
                                }
                            }
                        }
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvHomePetTrackWifiZone, mZoneAdapter, top = QMUIDisplayHelper.dpToPx(18)
            )

            mTrackMenuAdapter = HomePetTrackMenuAdapter(this@HomeTrackFragment, mTrackMenuList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvHomePetTrackMenu, mTrackMenuAdapter
            )

            setOnClickListenerViews(btnHomePetTrackWifiZoneManage, btnHomePetTrackVirtualFencesEdit)

//            mHomeV2Activity.getPet()?.apply {
//                mTrackerManageSetViewModel.getPetTrackerInfo(mHomeV2Activity, deviceId)
//            }
        }

        getPetTrackerInfoData(isSwitchPet)
    }

    private fun getHomeV2Activity(): HomeV2Activity? {
        return if (null == activity) {
            LogUtil.e("HomeTrackFragment,getHomeV2Activity,null == activity")
            null
        } else {
            activity as HomeV2Activity
        }
    }

    override fun liveDataObserve() {
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            getHomeV2Activity()?.getPet()?.apply {
                if (ble.mac == macID) {
                    updateConState(ble)
                }
            }
        }
        //接收开蓝牙操作,然后搜索连接设备
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            getHomeV2Activity()?.getPet()?.apply {
                if (BleManager.getInstance().isConnected(macID)) return@apply
                if (conState == ConState.CONNECTING || conState == ConState.CONNECTING_MAC) {
                    mTrackStateList[4].apply {
                        menuValue = getString(R.string.txt_connecting)
                        colorRedId = R.color.gray
                        isSwitch = true
                        mHomePetTrackStateAdapter.notifyItemChanged(4)
                    }
                } else {
                    mTrackStateList[4].apply {
                        menuValue = getString(R.string.txt_unconnect_no)
                        isSwitch = false
                        colorRedId = R.color.orange_color3
                        mHomePetTrackStateAdapter.notifyItemChanged(4)
                    }
                }
            }
        }
        //接收发送指令后设备返回的数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            getBleTrackDeviceBean(false)?.let {
                if (it.mac == receiveData.mac) {
                    val data = receiveData.data
                    parseData(data)
                }
            }
        }
        //蓝牙上报的数据
        XEventBus.observe(this, EventName.BleReportData) { reportData: BleReportDataBean ->
            getHomeV2Activity()?.getPet(false)?.apply {
                if (macID == reportData.mac) updateBleReportData(reportData)
            }
        }

        mTrackerInfoViewModel.mTrackerInfoLiveData.observe(viewLifecycleOwner) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()
                    data?.apply {
                        mMapDeviceBean = data
//                        if (BleManager.getInstance().isConnected(deviceMacId)) {
//                            LogUtil.e("蓝牙连接，不使用接口数据更新状态")
//                        } else {
//                        }
                        setStateData(data)
                        setZoneData(data)
                    }
                }
            })
            shareDeviceState()
        }

        //下载固件
        mDownLoadFileViewModel.mDownloadProgressLiveData.observe(this) {
            it?.apply {
//                mTrackerDFUStateDialog?.addData(this)
                if (progress == 100) {
                    LogUtil.e("固件下载完成")
                    mBleTrackDeviceBean?.let { b ->
                        b.bleDevice?.let { ble ->
                            getHomeV2Activity()?.let { m ->
                                m.getPet(false)?.let { p ->
                                    if (p.deviceType == ConstantInt.Type2) {
                                        mDeviceDFUViewModel.startG40DFU(mContext!!, ble, filePath)
                                    } else {
                                        mDeviceDFUViewModel.startG30DFU(mContext!!, ble, filePath)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        mDeviceDFUViewModel.apply {
            //接收固件版本返回
            mFirmwareInfoLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mFirmwareBean = this
                            mFirmwareBean?.mac = mBleTrackDeviceBean?.mac!!

                            findItem(
                                mTrackMenuList, getString(R.string.txt_firmware_version)
                            )?.let { m ->
                                val localVersion = m.menuValue
                                if (mDeviceDFUViewModel.checkVersionUpdate(localVersion, version)) {
                                    m.isSwitch = true
                                    mTrackMenuAdapter.notifyItemChanged(
                                        findIndexOf(
                                            mTrackMenuList, getString(R.string.txt_firmware_version)
                                        )
                                    )
                                }
                            }
                        }
                    }
                })
            }
            //接收dfu结果
            mDfuStateLiveData.observe(viewLifecycleOwner) {
                it?.apply {
//                    mTrackerDFUStateDialog?.addData(this)
                    if (progress in 0..100) mDFUNewDialogDialog?.setDFUProgress(progress)
                    if (progress == mDeviceDFUViewModel.mDFUSuccessCode) {
                        mDFUNewDialogDialog?.setDFUProgress(100)
                        isDFUCallback = true
                        mBleTrackDeviceBean?.let { ble ->
                            getHomeV2Activity()?.apply {
                                mConnectionDeviceViewModel.connectDeviceToMac(
                                    this, ble.mac, false
                                )
                            }
                        }
                    } else if (progress == mDeviceDFUViewModel.mDFUFailCode) {
//                        mTrackerDFUStateDialog?.dismiss()
                        dfuEnd()
                        mDFUNewDialogDialog?.setDFUFail {
                            mFirmwareBean?.apply {
                                dfuStart()
                                mDownLoadFileViewModel.downLoadFile(
                                    mContext!!, fileName, firmwareUrl
                                )
                            }
                        }
                    }
                }
            }
        }

        mTrackerSetViewModel.apply {
            mTurnoffLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
//                        mBleTrackDeviceBean?.apply {
//                            SRBleUtil.instance.writeData(
//                                bleDevice, SRBleCmdUtil.instance.forcedShutdown()
//                            )
//                        }
                    }
                })
            }

        }
        mLedLightViewModel.mLedSwitchLiveData.observe(viewLifecycleOwner) {
            dealRequestResult(
                it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        getHomeV2Activity()?.let { h ->
                            h.getPet(false)?.let { p ->
                                if (mLedMac == p.macID && !BleManager.getInstance()
                                        .isConnected(p.macID)
                                ) {
                                    mTrackStateList[5].apply {
                                        val ledSwitch =
                                            if (menuValue == getString(R.string.tracker_manage_set_led_on)) {
                                                ConstantInt.Close
                                            } else {
                                                ConstantInt.Open
                                            }
                                        setLedState(ledSwitch)
                                    }
                                }
                            }
                        }
                    }

                    override fun onInterceptCode() {
                        setLedErrorState()
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        setLedErrorState()
                    }
                }, isRequestErrorTip = getShowError(), isShowCodeError = getShowError()
            )
        }
    }

    private fun getShowError(): Boolean {
        var showCodeError = false
        getHomeV2Activity()?.apply {
            getPet(false)?.let {
                showCodeError = mLedMac == it.macID
            }
        }
        return showCodeError
    }

    private fun setLedErrorState() {
        getHomeV2Activity()?.apply {
            getPet(false)?.let {
                if (mLedMac == it.macID && !BleManager.getInstance().isConnected(it.macID)) {
                    mTrackStateList[5].apply {
                        state = ConstantInt.Type0
                        type = ConstantInt.Type0
                        mHomePetTrackStateAdapter.notifyItemChanged(5)
                    }
                }
            }
        }
    }

    fun getPetTrackerInfoData(switchPet: Boolean = false) {
        isSwitchPet = switchPet
        getHomeV2Activity()?.let {
            it.getPet()?.apply {
                if (isSwitchPet) {
                    isSwitchPet = false
                    mTrackStateList[5].apply {
                        state = ConstantInt.Type0
                        type = ConstantInt.SpecialType
                        menuValue = getString(R.string.tracker_manage_set_led_off)
                        mHomePetTrackStateAdapter.notifyItemChanged(5)
                    }
                    mTrackMenuAdapter.notifyItemRangeRemoved(0, mTrackMenuList.size)
                    mTrackMenuList.clear()
                }

                addMenuListData(this)
                mTrackerInfoViewModel.getPetTrackerInfo(it, deviceId)
            }
        }
    }

    /**
     * 显示分享的设备状态
     */
    private fun shareDeviceState() {
        val share = MMKVUtil.getInt(MMKVKey.Shared)
        if (share == ConstantInt.NoShare) {
            mViewBinding.rvHomePetTrackMenu.visibility = View.VISIBLE
            mZoneAdapter.showNoDataAddButton(true)
            mFencesAdapter.showNoDataAddButton(true)
        } else {
            mViewBinding.rvHomePetTrackMenu.visibility = View.GONE
            mZoneAdapter.showNoDataAddButton(false)
            mFencesAdapter.showNoDataAddButton(false)
        }
    }

    private fun addStateListData() {
        mTrackStateList = mutableListOf()
        mFencesList = mutableListOf()
        mZoneList = mutableListOf()
        mTrackMenuList = mutableListOf()
        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.tracker_manage_set_network),
            getString(R.string.txt_offline),
            imageResId = R.drawable.icon_map_signal
        )
        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.tracker_manage_set_gps),
            getString(R.string.txt_sleep),
            imageResId = R.drawable.icon_map_gps
        )
        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.txt_battery),
            "N/A",
            imageResId = -1,
            menuType = MultipleEntity.IMG_TEXT_IMG
        )
        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.txt_low_zone),
            getString(R.string.txt_outside),
            imageResId = R.drawable.icon_map_zone
        )
        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.txt_bluetooth),
            getString(R.string.txt_unconnect_no),
            menuType = MultipleEntity.TEXT_TEXT_IMG
        )

        ViewUtil.instance.addMenuBean(
            mTrackStateList,
            getString(R.string.txt_light),
            getString(R.string.tracker_manage_set_led_off),
            imageResId = R.drawable.icon_light_svg,
            type = ConstantInt.SpecialType
        )
    }

    private fun addMenuListData(petBean: PetBean) {
        petBean.apply {
            if (mTrackMenuList.size == 0) {
                if (deviceType == ConstantInt.Type1) {
                    ViewUtil.instance.addMenuBean(
                        mTrackMenuList, getString(R.string.tracker_manage_led)
                    )
                }
                ViewUtil.instance.addMenuBean(
                    mTrackMenuList, getString(R.string.tracker_manage_set_duration)
                )
                if (deviceType == ConstantInt.Type2) {
                    ViewUtil.instance.addMenuBean(
                        mTrackMenuList, getString(R.string.txt_live_duration)
                    )
                }
                ViewUtil.instance.addMenuBean(
                    mTrackMenuList,
                    getString(R.string.txt_firmware_version),
                    menuType = MultipleEntity.IMG_TEXT_IMG
                )
                if (deviceType == ConstantInt.Type1) {
                    ViewUtil.instance.addMenuBean(mTrackMenuList, getString(R.string.txt_power_off))
                }
            }
        }

        getBleTrackDeviceBean(false)?.let { ble ->
            if (BleManager.getInstance().isConnected(ble.mac)) {
                //获取固件版本号
                if (null == mFirmwareBean) {
                    SRBleUtil.instance.writeData(
                        ble.bleDevice, SRBleCmdUtil.instance.getFirmwareVersion()
                    )
                } else {
                    //只有新的设备，回到这个界面才去检查dfu
                    if (mFirmwareBean?.mac != ble.mac) {
                        findItem(
                            mTrackMenuList, getString(R.string.txt_firmware_version)
                        )?.let { m ->
                            m.menuValue = ""
                            m.isSwitch = false
                        }
                        SRBleUtil.instance.writeData(
                            ble.bleDevice, SRBleCmdUtil.instance.getFirmwareVersion()
                        )
                    } else {
                        findItem(
                            mTrackMenuList, getString(R.string.txt_firmware_version)
                        )?.let { m ->
                            if (TextUtils.isEmpty(m.menuValue)) {
                                SRBleUtil.instance.writeData(
                                    ble.bleDevice, SRBleCmdUtil.instance.getFirmwareVersion()
                                )
                            }
                        }
                    }
                }
            } else {
                mFirmwareBean = null
                findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let { m ->
                    m.menuValue = ""
                    m.isSwitch = false
                }
            }
        }
        if (null == mBleTrackDeviceBean) {
            mFirmwareBean = null
            findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let { m ->
                m.menuValue = ""
                m.isSwitch = false
            }
        }
        mTrackMenuAdapter.notifyItemChanged(
            findIndexOf(
                mTrackMenuList, getString(R.string.txt_firmware_version)
            )
        )
    }

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

    /**
     * 设置相关状态数据
     */
    private fun setStateData(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            val startTime = "${getString(R.string.txt_start_time)}:${
                startTime.split(" ")[0].replace(
                    "-", "."
                )
            }"
            val eTime = Utils.stringToDate(
                endTime, Utils.DATE_FORMAT_PATTERN_CN, Utils.DATE_FORMAT_PATTERN_CN
            )
            val endTime = "${getString(R.string.txt_end_time)}：$eTime"
            val id = "ID:$deviceOutId"
            mViewBinding.let {
                it.ivHomePetTrackPetHead.setImageResource(Util.getDeviceTypeImage(deviceType))
                it.tvHomePetTrackPetStartTime.text = startTime
                it.tvHomePetTrackPetEndTime.text = endTime
                it.tvHomePetTrackId.text = id
            }

            //是否超时上报
            val isTimeoutReport = Util.isTimeoutReport(updateTime, gnssInterval)
            mTrackStateList[0].let {
                it.menuValue =
                    if (isTimeoutReport || lteSignal == ConstantInt.NoSignal || powerSwitch == ConstantInt.Type0 || powerSwitch == ConstantInt.Type2) {
                        it.colorRedId = R.color.orange_color3
                        getString(R.string.txt_offline)
                    } else {
                        it.colorRedId = R.color.blue_color1
                        getString(R.string.txt_online)
                    }
            }
            mTrackStateList[1].let {
                it.colorRedId = R.color.blue_color1
                it.menuValue =
                    if (isTimeoutReport || powerSwitch == ConstantInt.Type0 || powerSwitch == ConstantInt.Type2 || powerSwitch == ConstantInt.Type3 || inWifiZone == ConstantInt.Type1) {
                        it.colorRedId = R.color.orange_color3
                        getString(R.string.txt_sleep)
                    } else if (gpsSignal > ConstantInt.WeakSignal) getString(R.string.txt_strong_signal)
                    else if (gpsSignal == ConstantInt.NoSignal) {
                        it.colorRedId = R.color.orange_color3
                        getString(R.string.txt_no_signal)
                    } else getString(R.string.txt_weak_signal)
            }
            mTrackStateList[2].let {
                it.menuValue =
                    if (isTimeoutReport || lteSignal == ConstantInt.NoSignal || powerSwitch == ConstantInt.Type0 || powerSwitch == ConstantInt.Type2) {
                        it.colorRedId = R.color.blue_color1
//                        it.imageId = -1
//                        "N/A"
                        "${batteryLevel}%"
                    } else {
                        it.colorRedId =
                            if (batteryLevel > ConstantInt.LowBattery20) R.color.blue_color1
                            else R.color.orange_color3
                        "${batteryLevel}%"
                    }
                it.imageId = Utils.calculatePowerLevel(batteryLevel)
            }
            mTrackStateList[3].let {
                it.colorRedId = R.color.orange_color3
                it.menuValue = when (inWifiZone) {
                    ConstantInt.Open -> {
                        it.colorRedId = R.color.blue_color1
                        getString(R.string.txt_inside)
                    }

                    ConstantInt.Type2 -> getString(R.string.txt_not_set)
                    else -> getString(R.string.txt_outside)
                }
            }
            mTrackStateList[4].let {
                if (it.menuValue != getString(R.string.txt_connecting)) {
                    it.colorRedId = R.color.orange_color3
                    it.menuValue = if (BleManager.getInstance().isConnected(deviceMacId)) {
                        it.colorRedId = R.color.blue_color1
                        getString(R.string.txt_connected)
                    } else {
                        getString(R.string.txt_unconnect_no)
                    }
                }
            }
            setLedControlState(mapDeviceBean)

            mTrackMenuList.let {
                findItem(it, getString(R.string.tracker_manage_set_duration))?.menuValue =
                    (gnssInterval / 60).toString() + getString(R.string.data_active_unit_min)
                findItem(it, getString(R.string.txt_live_duration))?.menuValue =
                    (liveTime / 60).toString() + getString(R.string.data_active_unit_min)
                findItem(it, getString(R.string.txt_power_off))?.let { menu ->
                    menu.type =
                        if (powerSwitch == ConstantInt.Type3 || powerSwitch == ConstantInt.Type0) ConstantInt.SpecialType
                        else ConstantInt.Type0
                    menu.menuValue = when (powerSwitch) {
                        ConstantInt.Type0 -> getString(R.string.tracker_manage_set_led_off)
                        ConstantInt.Type1 -> getString(R.string.tracker_manage_set_led_on)
                        else -> ""
                    }
                }
            }

            if (powerSwitch == ConstantInt.Type0) {
                mZoneAdapter.setDisabledMode(true)
            } else {
                mZoneAdapter.setDisabledMode(false)
            }
        }

        mTrackMenuAdapter.notifyItemRangeChanged(
            findIndexOf(
                mTrackMenuList, getString(R.string.tracker_manage_set_duration)
            ), mTrackMenuList.size
        )
        mHomePetTrackStateAdapter.notifyItemRangeChanged(0, mTrackStateList.size)
    }

    private fun findItem(list: MutableList<MenuTxtBean>, name: String): MenuTxtBean? {
        var menuTxt: MenuTxtBean? = null
        for (l in list) {
            if (name == l.menuName) {
                menuTxt = l
                break
            }
        }
        return menuTxt
    }

    private fun findIndexOf(list: MutableList<MenuTxtBean>, name: String): Int {
        var index = 0
        for (i in 0 until list.size) {
            if (name == list[i].menuName) {
                index = i
                break
            }
        }
        return index
    }

    private fun setLedControlState(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            //是否超时上报
//            val isTimeoutReport = Util.isTimeoutReport(updateTime,gnssInterval)
            mTrackStateList[5].let {
                if (deviceType == ConstantInt.Type1) {
                    it.imageId = R.drawable.icon_light_svg
                    it.menuName = getString(R.string.txt_light)
                } else {
                    it.imageId = R.drawable.icon_sound_image
                    it.menuName = getString(R.string.txt_tone)
                }
                it.colorRedId = R.color.orange_color3
                it.type = if (Util.getLedControlState(deviceMacId, this)) ConstantInt.Type0
                else ConstantInt.SpecialType

                it.menuValue = if (ledSwitch == ConstantInt.Open) {
                    it.colorRedId = R.color.blue_color1
                    getString(R.string.tracker_manage_set_led_on)
                } else {
                    getString(R.string.tracker_manage_set_led_off)
                }
            }
        }
    }

    private fun setZoneData(mapDeviceBean: MapDeviceBean) {
        mFencesList.clear()
        mZoneList.clear()
        mFencesAdapter.setData(null)
        mZoneAdapter.setData(null)
        mapDeviceBean.fences?.apply {
            if (size > 0) {
                if (size > 3) mFencesList.addAll(subList(0, 3).toList())
                else mFencesList.addAll(this.toList())
                mFencesAdapter.setData(mFencesList, true)
                mViewBinding.btnHomePetTrackVirtualFencesEdit.visibility = View.VISIBLE
            } else {
                mViewBinding.btnHomePetTrackVirtualFencesEdit.visibility = View.GONE
            }
        }
        mapDeviceBean.wifiZones?.apply {
            if (size > 0) {
                mZoneList.addAll(this)
                mZoneAdapter.setData(mZoneList, true)
                mViewBinding.btnHomePetTrackWifiZoneManage.visibility = View.VISIBLE
            } else {
                mViewBinding.btnHomePetTrackWifiZoneManage.visibility = View.GONE
            }
        }
    }

    /**
     * 设置固件信息
     */
    private fun setFirmwareData(firmware: FirmwareBean?) {
        if (null == firmware) {
            showToast(R.string.txt_latest_version)
            return
        }
        firmware.apply {
            val remark = if (TextUtils.isEmpty(remark)) {
                ""
            } else {
                "\n${getString(R.string.txt_release_notes)}：${remark}"
            }
            val message =
                "${getString(R.string.txt_firmware_name)}：$fileName\n${getString(R.string.txt_firmware_version)}：$version\n${
                    getString(R.string.txt_firmware_size)
                }：$firmwareSize$remark"
//            if (null == mTrackerDFUStateDialog) {
//                mDFUStateAdapter = DFUStateAdapter(mContext!!, null)
//                mTrackerDFUStateDialog = TrackerDFUStateDialog(mContext!!, mDFUStateAdapter)
//            }
            findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let {
                val localVersion = it.menuValue
                if (mDeviceDFUViewModel.checkVersionUpdate(localVersion, version)) {
//                mTrackerDFUStateDialog?.apply {
//                    show()
//                    setContent(message)
//                    startSureDFU {
//                        if (TextUtils.isEmpty(firmwareUrl)) {
//                            showToast(R.string.txt_no_down_url)
//                        } else {
//                            mDownLoadFileViewModel.downLoadFile(mContext, fileName, firmwareUrl)
//                        }
//                    }
//                }
                    if (null == mDFUNewDialogDialog) mDFUNewDialogDialog = DFUNewDialog(mContext!!)
                    mDFUNewDialogDialog?.apply {
                        show()
                        startDfuState(version) {
                            if (TextUtils.isEmpty(firmwareUrl)) {
                                showToast(R.string.txt_no_down_url)
                            } else {
                                mDownLoadFileViewModel.downLoadFile(
                                    mContext, fileName, firmwareUrl
                                )
                            }
                        }
                    }
                } else {
                    showToast(R.string.txt_latest_version)
                }
            }
        }
    }

    /**
     * 更新设备连接状态
     */
    private fun updateConState(trackBleDevice: BleTrackDeviceBean) {
        mBleTrackDeviceBean = trackBleDevice
        mMapDeviceBean?.apply {
            setLedControlState(this)
            mHomePetTrackStateAdapter.notifyItemChanged(5)
        }
        if (trackBleDevice.conState == ConState.CONNECTED) {
            if (isDFUCallback) {
                dfuEnd()
                showToast(R.string.txt_upgrade_success)
            }
            mHomePetTrackStateAdapter.notifyItemChanged(4)
            mTrackStateList[4].apply {
                menuValue = getString(R.string.txt_connected)
                isSwitch = false
                colorRedId = R.color.blue_color1
                mHomePetTrackStateAdapter.notifyItemChanged(4)
            }
            //获取固件版本号
            SRBleUtil.instance.writeData(
                trackBleDevice.bleDevice, SRBleCmdUtil.instance.getFirmwareVersion()
            )
        } else {
            if (isDFUCallback) {
                showToast(R.string.txt_connect_fail)
            }
            mTrackStateList[4].apply {
                menuValue = getString(R.string.txt_unconnect_no)
                isSwitch = false
                colorRedId = R.color.orange_color3
                mHomePetTrackStateAdapter.notifyItemChanged(4)
            }
            findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let { m ->
                m.menuValue = ""
                m.isSwitch = false
                mTrackMenuAdapter.notifyItemChanged(
                    findIndexOf(
                        mTrackMenuList, getString(R.string.txt_firmware_version)
                    )
                )
            }
        }
        //dfu升级成功 重新连接返回
        if (isDFUCallback) {
//            mTrackerDFUStateDialog?.dismiss()
            isDFUCallback = false
        }
    }

    /**
     * 解析数据
     */
    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 == 9) {
                if (data2 == 0) {
                    val strVersion = String(data.sliceArray(3..11))
                    LogUtil.e("设备固件版本号：$strVersion")
                    findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let {
                        it.menuValue = strVersion
                        it.isSwitch = false
                        mTrackMenuAdapter.notifyItemChanged(
                            findIndexOf(
                                mTrackMenuList, getString(R.string.txt_firmware_version)
                            )
                        )
                    }
                    getHomeV2Activity()?.let { m ->
                        m.getPet(false)?.let { p ->
                            mDeviceDFUViewModel.getFirmware(p.deviceType)
                        }
                    }
                    mBleTrackDeviceBean?.apply {
                        SRBleUtil.instance.writeData(
                            bleDevice, SRBleCmdUtil.instance.ledState(SRBleCmdUtil.CMD_READ, 0)
                        )
                    }
                }
            } else if (getHomeV2Activity()!!.isFrontRunning && data0 == 3 && data1 == 1) {
                val ledSwitch =
                    if (mTrackStateList[5].menuValue == getString(R.string.tracker_manage_set_led_on)) {
                        ConstantInt.Close
                    } else {
                        ConstantInt.Open
                    }
                val modeType = if (data2 == 0) {
                    val data3 = SRBleCmdUtil.instance.byteToInt(data[3])
                    if (data3 in 1..3) setLedState(ConstantInt.Open)
                    else setLedState(ConstantInt.Close)
                    ConstantInt.Type1
                } else {
                    ConstantInt.Type3
                }
                mMapDeviceBean?.let {
                    setLedState(ledSwitch)
                    //远程控制
                    mLedLightViewModel.setLedSwitch(
                        null, it.deviceServerId, ledSwitch, modeType
                    )
                }
            } else if (data0 == 4 && data1 == 1 && data2 == 0) {
//                mMapDeviceBean?.let {
//                    mTrackerSetViewModel.turnOff(it.deviceServerId)
//                }
//                mTrackMenuList[1].menuValue = ""
//                mTrackMenuList[2].menuValue = ""
//                mTrackMenuList[3].menuValue = ""
//                //取消红点显示
//                mTrackMenuList[3].isSwitch = false
//                mTrackMenuList[4].menuValue = ConstantInt.Close.toString()
//                mTrackMenuAdapter.notifyItemRangeChanged(1, 4)
            } else if (data0 == 0x18 && data1 == 1 && data2 == 0) {
                mBleTrackDeviceBean?.apply {
                    SRBleUtil.instance.disconnectToMac(mac)
                }
                mMapDeviceBean?.let { ble ->
                    mTrackerSetViewModel.turnOff(ble.deviceServerId)
                }
                findItem(mTrackMenuList, getString(R.string.txt_firmware_version))?.let {
                    it.menuValue = ""
                    //取消红点显示
                    it.isSwitch = false
                    mTrackMenuAdapter.notifyItemChanged(
                        findIndexOf(
                            mTrackMenuList, getString(R.string.txt_firmware_version)
                        )
                    )
                }
                findItem(mTrackMenuList, getString(R.string.txt_power_off))?.let {
                    it.menuValue = ConstantInt.Close.toString()
                    mTrackMenuAdapter.notifyItemChanged(
                        findIndexOf(
                            mTrackMenuList, getString(R.string.txt_power_off)
                        )
                    )
                }
            }
        }
    }

    fun goPetDataActivity(cls: Class<*>) {
        getHomeV2Activity()?.getPet()?.apply {
            val intent = Intent(mContext, cls)
            intent.putExtra(ConstantString.Pet, this)
            startActivity(intent)
        }
    }

    fun goMapDeviceDataActivity(cls: Class<*>) {
        mMapDeviceBean?.apply {
            val intent = Intent(mContext, cls)
            intent.putExtra(ConstantString.MapDeviceBean, this)
            startActivity(intent)
        }
    }

    /**
     * 获取当前宠物的连接设备
     */
    private fun getBleTrackDeviceBean(isShowBleUnConTip: Boolean = true): BleTrackDeviceBean? {
        getHomeV2Activity()?.getPet()?.apply {
            if (null == mBleTrackDeviceBean) {
                mBleTrackDeviceBean = SRBleUtil.instance.getConnectMacDevice(macID)
            } else {
                //判断是否切换了宠物
                mBleTrackDeviceBean?.let {
                    if (it.mac != macID) mBleTrackDeviceBean =
                        SRBleUtil.instance.getConnectMacDevice(macID)
                }
            }
        }

        if (isShowBleUnConTip && null == mBleTrackDeviceBean) {
            showToast(R.string.tracker_manage_set_ble_unconnect)
        }
        return mBleTrackDeviceBean
    }

    /**
     * 固件开始检查更新
     */
    fun firmwareCheckUpdate() {
        getBleTrackDeviceBean()?.let {
            if (BleManager.getInstance().isConnected(it.bleDevice)) {
                dfuStart()
                setFirmwareData(mFirmwareBean)
            } else {
                showToast(R.string.tracker_manage_set_ble_unconnect)
            }
        }
    }

    private fun dfuStart() {
        getHomeV2Activity()?.apply {
            //保持屏幕常亮
            window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            getPet(false)?.let {
                if (it.deviceType == ConstantInt.Type1) {
                    DfuServiceListenerHelper.registerProgressListener(
                        mContext, mDeviceDFUViewModel.mDfuProgressListener
                    )
                }
            }
        }
    }

    private fun dfuEnd() {
        getHomeV2Activity()?.apply {
            //清除屏幕常亮
            window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
            getPet(false)?.let {
                if (it.deviceType == ConstantInt.Type1) {
                    DfuServiceListenerHelper.unregisterProgressListener(
                        mContext, mDeviceDFUViewModel.mDfuProgressListener
                    )
                }
            }
        }
    }

    /**
     * 手动连接/断开设备
     */
    private fun connectionBtn(btnString: String) {
        if (btnString == getString(R.string.txt_unconnect_no)) {
            Util.checkBluetoothPermissionsEnabled(getHomeV2Activity()!!, {
                getHomeV2Activity()?.getPet()?.apply {
                    mConnectionDeviceViewModel.connectDeviceToMac(
                        getHomeV2Activity()!!, macID, false
                    )
                }
            })
        } else if (btnString == getString(R.string.txt_connected)) {
//            operateDeviceTips(R.string.txt_disconnect_tips, 1)
        }
    }

    /**
     * 设备关机/断开连接设备
     */
    fun operateDeviceTips(messageID: Int, type: Int) {
        if (type == ConstantInt.Type0) {
            getBleTrackDeviceBean()?.apply {
                if (!BleManager.getInstance().isConnected(mac)) {
                    showToast(R.string.tracker_manage_set_ble_unconnect)
                    return@apply
                }
            }
            if (null == mBleTrackDeviceBean) return
        }
        ViewUtil.instance.showDialog(
            mContext!!, messageID, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    when (type) {
                        0 -> mMapDeviceBean?.let {
//                            mTrackerSetViewModel.turnOff(mHomeV2Activity, it.deviceServerId)
                            bleTurnOff()
                        }

                        1 -> mBleTrackDeviceBean?.let {
                            mConnectionDeviceViewModel.disconnect(it.bleDevice)
                        }
                    }
                }
            }, okTextResId = R.string.start_txt_yes
        )
    }

    /**
     * 远程设置led开关
     */
    private fun setLedSwitch() {
        mTrackStateList[5].apply {
            val ledSwitch = if (menuValue == getString(R.string.tracker_manage_set_led_on)) {
                ConstantInt.Close
            } else {
                ConstantInt.Open
            }

            mMapDeviceBean?.let {
                state = ConstantInt.Type1
                type = ConstantInt.SpecialType
                mHomePetTrackStateAdapter.notifyItemChanged(5)
                mLedMac = it.deviceMacId
                if (BleManager.getInstance().isConnected(it.deviceMacId)) {
                    //蓝牙控制
                    getBleTrackDeviceBean(false)?.let { ble ->
                        SRBleUtil.instance.setBleLedSwitch(
                            getHomeV2Activity()!!, ble.bleDevice, ledSwitch
                        )
                    }
                } else {
//                    setLedState(ledSwitch)
                    //远程控制
                    mLedLightViewModel.setLedSwitch(
                        null, it.deviceServerId, ledSwitch, ConstantInt.Type2
                    )
                }
            }
        }
    }

    /**
     * 设置LED的状态
     */
    private fun setLedState(ledSwitch: Int) {
        mTrackStateList[5].apply {
            state = ConstantInt.Type0
            type = ConstantInt.Type0
            colorRedId = R.color.orange_color3
            menuValue = if (ledSwitch == ConstantInt.Open) {
                colorRedId = R.color.blue_color1
                getString(R.string.tracker_manage_set_led_on)
            } else {
                getString(R.string.tracker_manage_set_led_off)
            }
            mHomePetTrackStateAdapter.notifyItemChanged(5)
        }
    }

    private fun bleTurnOff() {
        //判断是否有蓝牙连接
        mBleTrackDeviceBean?.apply {
            if (BleManager.getInstance().isConnected(bleDevice)) {
                val cmd = SRBleCmdUtil.instance.shutdownDevice()
                SRBleUtil.instance.writeData(bleDevice, cmd)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnHomePetTrackWifiZoneManage -> goPetDataActivity(PowerSavingSetActivity::class.java)
                btnHomePetTrackVirtualFencesEdit -> goPetDataActivity(VirtualFencesActivity::class.java)
            }
        }
    }
}