package com.abbidot.tracker.ui.activity

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.text.TextUtils
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
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.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.ChangePetListDialogAdapter
import com.abbidot.tracker.adapter.ViewPagerAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.FamilyBean
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.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityHomeV2Binding
import com.abbidot.tracker.dialog.CommonDialog1
import com.abbidot.tracker.dialog.CommonListDialog
import com.abbidot.tracker.receiver.BluetoothMonitorReceiver
import com.abbidot.tracker.ui.DebugActivity
import com.abbidot.tracker.ui.activity.device.AddNewTracker1Activity
import com.abbidot.tracker.ui.activity.device.MyTrackerV2Activity
import com.abbidot.tracker.ui.fragment.account.AccountV2Fragment
import com.abbidot.tracker.ui.fragment.data.ActivityV2Fragment
import com.abbidot.tracker.ui.fragment.data.RouteV3Fragment
import com.abbidot.tracker.ui.fragment.map.MapV3Fragment
import com.abbidot.tracker.ui.fragment.pet.PetV2Fragment
import com.abbidot.tracker.util.SocketUtilManage
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.ConnectionDeviceViewModel
import com.abbidot.tracker.vm.CountDownTimerViewModel
import com.abbidot.tracker.vm.DataViewModel
import com.abbidot.tracker.vm.FamilyViewModel
import com.abbidot.tracker.vm.LogBleReportViewModel
import com.abbidot.tracker.vm.SocketSendMessageViewModel
import com.clj.fastble.BleManager
import com.google.android.material.navigation.NavigationBarView
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.huantansheng.easyphotos.EasyPhotos
import com.qmuiteam.qmui.widget.QMUITopBar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * v2版主页
 */
@AndroidEntryPoint
class HomeV2Activity : BaseActivity<ActivityHomeV2Binding>(ActivityHomeV2Binding::inflate),
    NavigationBarView.OnItemSelectedListener, ChangePetListDialogAdapter.OnChangeClickListener {

    val mDataViewModel: DataViewModel by viewModels()
    private val mAutomaticConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()
    private val mLogBleReportViewModel: LogBleReportViewModel by viewModels()
    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()
    private val mSocketSendMessageViewModel: SocketSendMessageViewModel by viewModels()
    private val mFamilyViewModel: FamilyViewModel by viewModels()

    private var mChangePetDialog: CommonListDialog? = null

    private lateinit var mChangePetListDialogAdapter: ChangePetListDialogAdapter

    //弹窗选中的宠物下标
    var mSelectPetPosition = 0

    //宠物数据
    lateinit var mPetList: MutableList<PetBean>
    private var isFirst = true

    //是否请求过宠物数据
    var isRequestPetData = false
    private var mCountdownType = ConstantInt.SpecialType

    //是否已经触发倒计时自动连接设备
    private var isCountdownAutoConnBle = false

    //是否检查套餐过期
    private var isCheckPackageExpire = true

    //是否一键定位
    var isNotifyRefreshLocation = false

    private val mFragments = mutableListOf<Fragment>(
        ActivityV2Fragment.newInstance(this),
        RouteV3Fragment.newInstance(this),
        MapV3Fragment.newInstance(this),
        PetV2Fragment.newInstance(this),
        AccountV2Fragment.newInstance(this)
    )
    private var mBleListenerReceiver: BluetoothMonitorReceiver? = null

    private var mSocketUtilManage: SocketUtilManage? = null
//    private val mBleReportManage: BleReportManage by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
//        mSocketUtilManage = SocketUtilManage()
//        mSocketUtilManage?.initEasySocket(mContext)
//        LogUtil.e("创建Socket连接")
//        BleReportManage(mSocketSendMessageViewModel, mSocketUtilManage!!)
//    }

    override fun getTopBar(): QMUITopBar? = null

    override fun initData() {
        isEdgeToEdgeAdapterNavigationBars = false
        checkCrash = false
        super.initData()
        setStatusBarLight()

        mSelectPetPosition = MMKVUtil.getInt(MMKVKey.PetSelectPosition)

        mViewBinding.homeV2ViewPager2.let {
            it.adapter = ViewPagerAdapter(mFragments, this).apply {
                saveState()
            }
            ViewUtil.instance.setViewPager2Config(it, object : ViewPager2.OnPageChangeCallback() {
                override fun onPageScrolled(
                    position: Int, positionOffset: Float, positionOffsetPixels: Int
                ) {
                    super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                    val menuItem = mViewBinding.homeV2BottomTabLayout.menu[position]
                    menuItem.isChecked = true
                }
            }, 1)

            //解决异常 https://blog.csdn.net/w_lin/article/details/123872656
            it.isSaveEnabled = false

            edgeToEdgeAdapterBars(it)
        }

        mViewBinding.homeV2BottomTabLayout.let {
            // 不使用图标默认变色
            it.itemIconTintList = null
            it.setOnItemSelectedListener(this)
        }
        mPetList = mutableListOf()
        mChangePetListDialogAdapter = ChangePetListDialogAdapter(mContext, mPetList).apply {
            setOnChangeClickListener(this@HomeV2Activity)
        }
        //smoothScroll设为false,不显示动画，关闭预加载? true显示过渡动画
        mViewBinding.homeV2ViewPager2.setCurrentItem(2, false)
        setLineShow(2)

        //出现闪退,5秒退出APP
        val isCrash = MMKVUtil.getBoolean(MMKVKey.isCrash, false)
        if (isCrash) {
            MMKVUtil.putBoolean(MMKVKey.isCrash, false)
            showToast(R.string.txt_show_crash)
            mCountdownType = ConstantInt.Type0
            mCountDownTimerViewModel.startCountDown(4)
        } else {
            //清除首次绑定设备信息
            MMKVUtil.putString(MMKVKey.FirstDeviceMac, "")
            val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkCallback: ConnectivityManager.NetworkCallback =
                object : ConnectivityManager.NetworkCallback() {
                    override fun onAvailable(network: Network) {
                        // 当网络可用时调用
                        super.onAvailable(network)
                        LogUtil.e("当网络可用时,onAvailable")
                        if (mNetworkRequestsFailRetryCount == mNetworkRequestsFailMaxCount && mPetList.size == 0) {
                            mNetworkRequestsFailRetryCount = 0
                            isFirst = false
                            mDataViewModel.getHomeBindPetList(this@HomeV2Activity)
                        }
                    }
                }
            val networkRequest =
                NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                    .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
                    .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).build()
            connectivityManager.registerNetworkCallback(networkRequest, networkCallback)

            //注册监听蓝牙开关广播
            mBleListenerReceiver = BluetoothMonitorReceiver()
            val intentFilter = IntentFilter()
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
            // 注册广播
            registerReceiver(mBleListenerReceiver, intentFilter)

            checkPermissions()

            mDataViewModel.getHomeBindPetList(this@HomeV2Activity)

            //设置bugly的用户id
//            CrashReport.setUserId(MMKVUtil.getString(MMKVKey.Email))
            //预先加载相册，防止上传头像几千张照片加载慢
            XXPermissions.with(this).permission(PermissionLists.getReadMediaImagesPermission())
                .request { _, deniedList ->
                    val allGranted = deniedList.isEmpty()
                    if (allGranted) {
                        EasyPhotos.preLoad(this)
//                    {
//                        runOnUiThread {
//                            showToast("相册加载完成")
//                        }
//                    }
                    }
                }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isCountdownAutoConnBle && mCountdownType == ConstantInt.Type1) {
            LogUtil.e("onResume,自动连接设备20秒计时开始")
            mCountDownTimerViewModel.startCountDown(20)
        }
    }

    override fun onPause() {
        super.onPause()
        if (isCountdownAutoConnBle && mCountdownType == ConstantInt.Type1) {
            LogUtil.e("onPause,自动连接设备倒计时停止")
            mCountDownTimerViewModel.stopCountDown()
        }
    }

    override fun liveDataObserve() {/*
        Dispatchers.IO 在Android中主要用于执行输入输出操作，如文件读写和网络请求
        Dispatchers.Main‌：适用于处理与UI相关的操作，如更新UI界面、响应用户输入等。
        Dispatchers.Default‌：适用于执行CPU密集型任务，如算法计算、数据处理等
        Dispatchers.Unconfined‌：不对协程的执行环境做任何限制，协程将在调用它的线程中执行，直到遇到挂起函数为止，之后会在恢复执行时继续在之前的线程中执行‌
         */

        mCountDownTimerViewModel.apply {
            mCountDowningLiveData.observe(this@HomeV2Activity) {
                if (mCountdownType == ConstantInt.Type1) {
                    isCountdownAutoConnBle = true
                }
            }
            mCountDownEndLiveData.observe(this@HomeV2Activity) {
                //自动重启APP
//            val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
//            //与正常页面跳转一样可传递序列化数据,在Launch页面内获得
//            intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            intent.putExtra("REBOOT", "reboot")
//            startActivity(intent)

                //出现闪退,5秒退出APP
                if (mCountdownType == ConstantInt.Type0) {
                    finish()
                    System.gc()
                } else if (mCountdownType == ConstantInt.Type1) {
                    LogUtil.e("自动连接蓝牙倒计时结束")
                    isCountdownAutoConnBle = false
                    if (SRBleUtil.instance.isBleEnable(mContext)) {
                        autoConnectDevice()
                    }
                }
            }
        }
        //退出登录
        XEventBus.observe(this, EventName.LogOut) {
            finish()
        }
        //修改密码成功返回
        XEventBus.observe(this, EventName.ChangePassword) {
            finish()
        }
        //接收开蓝牙操作,然后搜索连接设备
        XEventBus.observe(this, EventName.BluetoothSwitch) { conState: Int ->
            if (conState == ConState.BLUETOOTH_ON) {
                autoConnectDevice()
            } else if (conState == ConState.BLUETOOTH_OFF) {
                //处理高版本关闭蓝牙开关，不断开蓝牙连接的情况
                getPet(false)?.apply {
                    BleTrackDeviceBean().let { trackBle ->
                        trackBle.mac = macID
                        XEventBus.post(EventName.ConnectDeviceState, trackBle)
                    }
                }
            }
        }
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            getPet(false)?.apply {
                //蓝牙连接断开上传日志
                if (ble.mac == macID) {
                    if (ble.conState == ConState.CONNECTED) {
                        stopCountDownConBle()
                        //蓝牙连接就去连接socket
//                        mBleReportManage.dealBleReportData(macID, null)
                    } else {
                        mLogBleReportViewModel.uploadLog(mContext, macID, deviceOutId)
                        startCountDownConBle(15)
                    }
                }
            }
        }

        //更新套餐数据
        XEventBus.observe(this, EventName.RefreshPackage) {
            mDataViewModel.getHomeBindPetList(this)
        }
        //更新宠物信息,添加/编辑宠物
        XEventBus.observe(this, EventName.RefreshPet) {
            mDataViewModel.getHomeBindPetList(this)
        }
        //刷新下邀请家人数据
        XEventBus.observe(this, EventName.RefreshHomeList) {
            mDataViewModel.getHomeBindPetList(this)
        }
        //删除宠物
        XEventBus.observe(this, EventName.DeletePet) {
            mSelectPetPosition = 0
            mDataViewModel.getHomeBindPetList(this)
        }
        //删除设备
        XEventBus.observe(this, EventName.DeleteDevice) {
            mSelectPetPosition = 0
            mDataViewModel.getHomeBindPetList(this)
        }
        //获取蓝牙上报数据
        XEventBus.observe(this, EventName.BleReport) { receiveData: ReceiveDeviceData ->
            lifecycleScope.launch(Dispatchers.IO) {
                getPet(false)?.apply {
//                    if (macID == receiveData.mac) {
//                        mBleReportManage.dealBleReportData(receiveData.mac, receiveData.data)
//                    }
                }
            }
        }
        //获取日志上报数据
        XEventBus.observe(this, EventName.LogReport) { receiveData: ReceiveDeviceData ->
            getPet(false)?.apply {
                if (macID == receiveData.mac) {
                    mLogBleReportViewModel.dealLogReportData(mContext, receiveData)
                }
            }
        }

        //蓝牙上报的设备日志
        mLogBleReportViewModel.apply {
            mUploadLogLiveData.observe(this@HomeV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { data ->
                            getPet(false)?.let { pet ->
                                val time = Utils.formatTime(
                                    System.currentTimeMillis(), Utils.DATE_FORMAT_PATTERN_CN2
                                )
                                uploadDeviceLog(pet.deviceOutId, time, pet.macID, data)
                            }
                        }
                    }
                })
            }
            mUploadDeviceLogLiveData.observe(this@HomeV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
//                        Toaster.show("日志上传成功")
                        LogUtil.e("日志上传成功")
                    }
                })
            }
        }
        //获取所有宠物数据
        mDataViewModel.mHomePetLiveData.observe(this) {
            dealRequestResult(
                it,
                object : GetResultCallback {
                    override fun onResult(any: Any) {
                        LogUtil.e("HomeV2Activity------>>获取所有绑定宠物数据")
                        isRequestPetData = true
                        mPetList.clear()
                        mChangePetListDialogAdapter.setData(null)
                        it.getOrNull()?.apply {
                            setPetData(this)
                        }
                        mFamilyViewModel.getDeviceInviteInfo(this@HomeV2Activity)
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        LogUtil.e("HomeV2Activity------->请求宠物数据错误onRequestError，再次请求")
                        if (exceptionCode == mNetworkRequestsFailLimit) {
                        } else {
                            mDataViewModel.getHomeBindPetList(this@HomeV2Activity)
                        }
                    }
                },
                isShowNoDataTip = false,
                isShowRequestErrorTip = mNetworkRequestsFailRetryCount == mNetworkRequestsFailMaxCount
            )
        }
        //获取设备邀请信息
        mFamilyViewModel.mInviteInfoLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        if (deleteArray.isNotEmpty()) showDeleteInviteDialog(deleteArray)
                        if (inviteArray.isNotEmpty()) showInviteDialog(inviteArray)
                    }
                }
            })
        }
    }

    private fun startCountDownConBle(second: Long) {
        LogUtil.e("${second}秒监听蓝牙自动连接")
        mCountdownType = ConstantInt.Type1
        mCountDownTimerViewModel.startCountDown(second)
    }

    private fun stopCountDownConBle() {
        isCountdownAutoConnBle = false
        mCountDownTimerViewModel.stopCountDown()
    }

    private fun setPetData(petList: MutableList<PetBean>) {
        mPetList.addAll(petList)
        if (mSelectPetPosition > mPetList.size - 1) {
            mSelectPetPosition = 0
        }
        if (petList.isEmpty()) {
            noSharePet()
            return
        }
        mChangePetListDialogAdapter.apply {
            setData(mPetList, true)
            (mFragments[2] as MapV3Fragment).showPetNameAndHead(mSelectPetPosition)
            if (isFirst) {
                isFirst = false
                setSelectPetPos(mSelectPetPosition)
                //判断套餐有没有到期
                packageUnavailableState()
                //刚开始打开APP上传日志
                getPet(false)?.apply {
                    mLogBleReportViewModel.uploadLog(mContext, macID, deviceOutId)
                }
            } else {
                onChangeClick(mSelectPetPosition)
                when (mViewBinding.homeV2ViewPager2.currentItem) {
                    0 -> {
                        (mFragments[1] as RouteV3Fragment).setNeedUpdateTag()
                        (mFragments[3] as PetV2Fragment).setNeedUpdateTag()
                    }

                    1 -> {
                        (mFragments[0] as ActivityV2Fragment).setNeedUpdateTag()
                        (mFragments[3] as PetV2Fragment).setNeedUpdateTag()
                    }

                    2, 4 -> {
                        (mFragments[0] as ActivityV2Fragment).setNeedUpdateTag()
                        (mFragments[1] as RouteV3Fragment).setNeedUpdateTag()
                        (mFragments[3] as PetV2Fragment).setNeedUpdateTag()
                    }

                    3 -> {
                        (mFragments[0] as ActivityV2Fragment).setNeedUpdateTag()
                        (mFragments[1] as RouteV3Fragment).setNeedUpdateTag()
                    }
                }
            }
        }
    }

    /**
     * 显示被删除邀请的弹窗
     */
    private fun showDeleteInviteDialog(deleteArray: MutableList<FamilyBean>) {
        lifecycleScope.launch(Dispatchers.IO) {
            val myDeviceDb = MyDatabase.deviceDao().findAll(MyDatabase.DEVICE_TABLE)
            myDeviceDb?.apply {
                for (deviceDb in myDeviceDb) {
                    for (item in deleteArray) {
                        if (deviceDb.deviceId == item.deviceId) {
                            MyDatabase.deviceDao().delete(deviceDb)
                            LogUtil.e("删除了邀请的设备")
                        }
                    }
                }
            }
            val newDeviceDb = MyDatabase.deviceDao().findAll(MyDatabase.DEVICE_TABLE)
            newDeviceDb?.apply {
                LogUtil.e("删去了邀请，还剩${newDeviceDb.size}下个设备")
            }
        }
        CommonDialog1(
            mContext,
            getString(R.string.txt_setting_notification),
            getString(R.string.txt_view_access),
            false,
            okClickListener = object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    if (mPetList.size == 0) {
                        noSharePet()
                    } else {
                        onChangeClick(0)
                    }
                }
            }).show()
    }

    /**
     * 显示被邀请通知弹窗
     */
    private fun showInviteDialog(inviteArray: MutableList<FamilyBean>) {
        for (item in inviteArray) {
            val content = String.format(
                getString(R.string.txt_invites_you_check), item.userName, item.petName
            )
            CommonDialog1(
                mContext,
                getString(R.string.txt_setting_notification),
                content,
                false,
                okClickListener = object : BaseDialog.OnDialogOkListener {
                    override fun onOkClick(dialog: BaseDialog<*>) {
                        startActivity(Intent(mContext, MyTrackerV2Activity::class.java))
                    }
                }).show()
        }
    }


    /**
     * 套餐不可用状态
     */
    private fun packageUnavailableState() {
        getPet(false)?.apply {
            //判断套餐有没有到期
            if (isCheckPackageExpire && shared == ConstantInt.NoShare && availableOrder == ConstantInt.Type0) {
                Util.checkPackageExpired(this@HomeV2Activity, deviceId)
            }
        }
        autoConnectDevice()
    }

    /**
     * 处理多个手机登录(特别是获取设备邀请信息)。没有绑定的宠物情况
     */
    fun noSharePet() {
        MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.Type0)
        MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.Type0)
        val intent = Intent(mContext, AddNewTracker1Activity::class.java)
        intent.putExtra(ConstantString.isFirstBind, true)
        startActivityFinish(intent)
    }

    /**
     * 检查获取定位蓝牙权限
     */
    private fun checkPermissions() {
        val checkBleOpen = MMKVUtil.getBoolean(MMKVKey.isFirstCheckBleOpen, true)
        if (checkBleOpen) MMKVUtil.putBoolean(MMKVKey.isFirstCheckBleOpen, false)
        Util.checkBluetoothPermissionsEnabled(this, {
//            mAutomaticConnectionDeviceViewModel.autoConnectBleDevice(mContext)
        }, isCheckBleOpen = checkBleOpen)
    }

    /**
     * 选择宠物弹窗
     */
    fun selectPetDialog(checkPackageExpire: Boolean = true) {
        isCheckPackageExpire = checkPackageExpire
        if (mPetList.size == 0) {
            showToast(R.string.no_bind_pet)
            return
        }
        if (null == mChangePetDialog) {
            mChangePetDialog = CommonListDialog(mContext, mChangePetListDialogAdapter, 18, 0, 18)
        }
        mChangePetDialog?.show()
    }

    fun getPet(showNoPetTip: Boolean = true): PetBean? {
        return if (mPetList.size > 0) mPetList[mSelectPetPosition]
        else {
            if (isRequestPetData && showNoPetTip) showToast(R.string.no_bind_pet)
            null
        }
    }

    /**
     * 跳转debug调试页面
     */
    fun goToDebugActivity() {
        val intent = Intent(mContext, DebugActivity::class.java)
        if (mPetList.size > mSelectPetPosition) {
            intent.putParcelableArrayListExtra(
                ConstantString.Pet, mPetList as ArrayList<PetBean>
            )
            intent.putExtra(ConstantString.Index, mSelectPetPosition)
        }
        startActivity(intent)
    }


    /**
     * 检测一键定位状态
     */
    fun checkNotifyRefreshLocation(textView: AppCompatTextView) {
        textView.let {
            if (isNotifyRefreshLocation) {
                it.setText(R.string.txt_locating)
                it.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
            } else {
                getPet(false)?.let { pet ->
                    it.text = pet.petName
                    it.setCompoundDrawablesWithIntrinsicBounds(
                        0, 0, R.drawable.icon_gray_down_arrow, 0
                    )
                }
            }
        }
    }

    fun refreshLocationBtnState() {
        when (mViewBinding.homeV2ViewPager2.currentItem) {
            0 -> (mFragments[0] as ActivityV2Fragment).checkNotifyLocationState()
            1 -> (mFragments[1] as RouteV3Fragment).checkNotifyLocationState()
            3 -> (mFragments[3] as PetV2Fragment).checkNotifyLocationState()
        }
    }

    override fun onCurrentClick() {
        mChangePetDialog?.dismiss()
    }

    override fun onChangeClick(position: Int) {
        if (mPetList.size == 0) return
        mChangePetDialog?.dismiss()
        mSelectPetPosition = position
        mChangePetListDialogAdapter.setSelectPetPos(mSelectPetPosition)
        when (mViewBinding.homeV2ViewPager2.currentItem) {
            0 -> (mFragments[0] as ActivityV2Fragment).showPetNameAndHead(position)
            1 -> (mFragments[1] as RouteV3Fragment).showPetNameAndHead(position)
            2 -> (mFragments[2] as MapV3Fragment).showPetNameAndHead(position)
            3 -> (mFragments[3] as PetV2Fragment).showPetNameAndHead(position)
        }
        //判断套餐有没有到期
        packageUnavailableState()
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        if (!AppUtils.isDarkThemeEnabled(mContext)) setStatusBarLight()
        else setStatusBarDark()
        return when (item.itemId) {
            R.id.tab_menu_activity_v2 -> {
                mViewBinding.homeV2ViewPager2.currentItem = 0
                setLineShow(0)
                true
            }

            R.id.tab_home_route_v2 -> {
                mViewBinding.homeV2ViewPager2.currentItem = 1
                setLineShow(1)
                true
            }

            R.id.tab_home_map_v2 -> {
                setStatusBarLight()
                mViewBinding.homeV2ViewPager2.currentItem = 2
                setLineShow(2)
                true
            }

            R.id.tab_home_pet_v2 -> {
                mViewBinding.homeV2ViewPager2.currentItem = 3
                setLineShow(3)
                true
            }

            R.id.tab_home_account_v2 -> {
                mViewBinding.homeV2ViewPager2.currentItem = 4
                setLineShow(4)
                true
            }

            else -> false
        }
    }

    private fun setLineShow(which: Int) {
        mViewBinding.homeActivityV2Line.visibility = View.INVISIBLE
        mViewBinding.homeRouteV2Line.visibility = View.INVISIBLE
        mViewBinding.homeMapV2Line.visibility = View.INVISIBLE
        mViewBinding.homePetV2Line.visibility = View.INVISIBLE
        mViewBinding.homeAccountV2Line.visibility = View.INVISIBLE
        when (which) {
            0 -> mViewBinding.homeActivityV2Line.visibility = View.VISIBLE
            1 -> mViewBinding.homeRouteV2Line.visibility = View.VISIBLE
            2 -> mViewBinding.homeMapV2Line.visibility = View.VISIBLE
            3 -> mViewBinding.homePetV2Line.visibility = View.VISIBLE
            4 -> mViewBinding.homeAccountV2Line.visibility = View.VISIBLE
        }
    }

    /**
     * 自动连接设备
     */
    private fun autoConnectDevice() {
        val share = MMKVUtil.getInt(MMKVKey.Shared)
        if (share != ConstantInt.NoShare) {
            LogUtil.e("分享的设备,不连接设备")
            return
        }
        getPet(false)?.apply {
            if (TextUtils.isEmpty(macID)) return@apply
            if (SRBleUtil.instance.isBleEnable(mContext)) {
                if (BleManager.getInstance().isConnected(macID)) {
                    LogUtil.e("已连接设备,不用再次自动连接设备")
//                    SRBleUtil.instance.cancelBleScan("已连接设备，取消其他连接扫描")
//                    val bleTrack = SRBleUtil.instance.getConnectMacDevice(macID)
//                    XEventBus.post(EventName.ConnectDeviceState, bleTrack)
                } else {
                    mAutomaticConnectionDeviceViewModel.connectDeviceToMac(
                        this@HomeV2Activity, macID, false
                    )
                    startCountDownConBle(30)
                }
            }
        }
    }

//    override fun onTrimMemory(level: Int) {
//        super.onTrimMemory(level)
//        LogUtil.e("系统级别：$level"+printLevel(level))
//    }
//    private fun printLevel( level:Int) :String{
//        var desc=""
//        when (level) {
//             TRIM_MEMORY_COMPLETE->//80
//            desc = "进程在LRU尾部,如果没有足够的内存, 将很快被杀死";
//             TRIM_MEMORY_MODERATE->//60
//            desc = "进程在LRU中部,如果系统进一步需要内存, 可能会被杀死";
//             TRIM_MEMORY_BACKGROUND->//40
//            desc = "进程在LRU头部,虽然本进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程";
//             TRIM_MEMORY_UI_HIDDEN->//20
//            desc = "界面不可见，建议释放UI资源";
//             TRIM_MEMORY_RUNNING_CRITICAL->//15
//            desc = "虽然进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程，应该释放无用资源以防止性能下降";
//             TRIM_MEMORY_RUNNING_LOW->//10
//            desc = "虽然进程不会被高优杀死, 但系统已经开始准备杀死LRU列表中的其他进程，应该释放不必要的资源来提供系统性能";
//             TRIM_MEMORY_RUNNING_MODERATE->//5
//            desc = "系统已经进入了低内存的状态，进程正在运行但是不会被杀死";
//        }
//        return desc;
//    }

    private var mTempTime = 0L
    override fun listenBackPressed() {
        // 2s内再次选择back键有效
        if (System.currentTimeMillis() - mTempTime > 2000) {
            showToast(R.string.txt_exit_return)
            mTempTime = System.currentTimeMillis()
        } else {
            finish()
            System.gc()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.e("HomeV2Activity---------------onDestroy")
        stopCountDownConBle()
        mSocketUtilManage?.destroy()
        mBleListenerReceiver?.let {
            unregisterReceiver(it)
        }
        BleManager.getInstance().apply {
            disconnectAllDevice()
            destroy()
        }
    }
}