package com.abbidot.tracker.ui.fragment.map

import android.animation.AnimatorSet
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.location.LocationManager
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.widget.CompoundButton
import android.widget.CompoundButton.OnCheckedChangeListener
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
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.constant.ResultCode
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.HomeMapDeviceStateAdapter
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.BleReportDataBean
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentMapV3Binding
import com.abbidot.tracker.dialog.CommonDialog1
import com.abbidot.tracker.dialog.SelectMapTypeDialog
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.map.LiveActivityV3
import com.abbidot.tracker.ui.common.map.HomeMapCommonV3
import com.abbidot.tracker.util.LonAndLatUtil
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.CountDownTimerViewModel
import com.abbidot.tracker.vm.FencesMapViewModel
import com.abbidot.tracker.vm.MapViewModel
import com.clj.fastble.BleManager
import com.google.android.gms.maps.model.LatLng
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject


/**
 * 首页map
 * create an instance of this fragment.
 */
@AndroidEntryPoint
class MapV3Fragment : BaseFragment<FragmentMapV3Binding>(FragmentMapV3Binding::inflate),
    OnCheckedChangeListener {

    private val mFencesMapViewModel: FencesMapViewModel by viewModels()
    private val mMapViewModel: MapViewModel by viewModels()
    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()

    private lateinit var mLocationManager: LocationManager

    private var mSelectMapTypeDialog: SelectMapTypeDialog? = null

    //当前这个页面显示的宠物下标
    private var mCurrentShowPetPos = -1

    @Inject
    lateinit var mHomeMapCommon: HomeMapCommonV3
    private lateinit var mFragment: Fragment
    private var mMapDeviceBean: MapDeviceBean? = null

    private lateinit var mDeviceStateList: MutableList<DataBean>
    private lateinit var mDeviceStateAdapter: HomeMapDeviceStateAdapter
//    private lateinit var mDeviceMsgList: MutableList<DataBean>
//    private lateinit var mDeviceMsgAdapter: HomeMapDeviceMsgAdapter

    //启动移动地图摄像机
    private var isMoveCamera = true
    private var mShowCenterLocationType = ConstantInt.PetLocationType

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

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

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

    //是否可用直播
    private var isCanLive = false

    //是否需要gps坐标转火星坐标
    private var needGpsToGCJ02 = true
    private var mAnimatorSet: AnimatorSet? = null

    //一键定位开始的时间戳
    private var notifyRefreshLocationTimestamp = 0L

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

    override fun initData() {
        mLocationManager = mContext!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        getHomeV2Activity()?.apply {
            mCurrentShowPetPos = mSelectPetPosition
        }

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

        mViewBinding.apply {
            getHomeV2Activity()?.edgeToEdgeAdapterBars(
                root, WindowInsetsCompat.Type.statusBars()
            )
            mFragment = mHomeMapCommon.getMapFragment(
                mContext!!,
                ilHomeMapPetLocation,
                llHomeMapDeviceBatteryLayout,
                Utils.DATE_FORMAT_PATTERN_EN15,
                true
            ) { mapLoadOk() }

            llHomeMapTopPet.ivTopPetBtnSmall.setImageResource(R.drawable.icon_map_type)

            ViewUtil.instance.setMapSwitchLocationButtonImage(
                homeMapRefreshBtn, mShowCenterLocationType
            )

            mDeviceStateList = mutableListOf()
            mMapViewModel.addDeviceDefaultStateData(mContext!!, mDeviceStateList)
            mDeviceStateAdapter = HomeMapDeviceStateAdapter(mContext!!, mDeviceStateList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvHomeMapDeviceState, mDeviceStateAdapter, bottom = 10
            )

//            mDeviceMsgAdapter = HomeMapDeviceMsgAdapter(mContext!!, mDeviceMsgList)
//            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
//                mContext!!, rvHomeMapDeviceMsg, mDeviceMsgAdapter, bottom = 10
//            )


//            rlHomeMapTopLayout.setOnTouchListener { _, _ ->
//                if (mShowCenterLocationType == ConstantInt.PetLocationType) {
//                    mShowCenterLocationType = ConstantInt.PetSpecialType
//                    ViewUtil.instance.setMapSwitchLocationButtonImage(
//                        homeMapRefreshBtn, mShowCenterLocationType
//                    )
//                }
//                false
//            }

            setOnClickListenerViews(
                homeMapRefreshBtn,
                homeMapBluetoothBtn,
                homeMapLiveBtn,
                ivHomeMapRefreshLocation,
                llHomeMapTopPet.ivTopPetBtnSmall,
                llHomeMapTopPet.homeDataPetNameSmall,
                llHomeMapTopPet.homeDataPetHeadSmall.root,
                ilHomeMapDeviceBatteryLayout.ivDeviceCloseBtn,
                ilHomeMapDeviceMsg.ivDeviceMsgCloseBtn,
                ilHomeMapPetLocation.ivPetLocationNavigationBtn
            )

            if (AppUtils.isDebug()) {
                llHomeMapTopPet.homeDataPetHeadSmall.appHeadImage.setOnLongClickListener {
                    getHomeV2Activity()?.goToDebugActivity()
                    true
                }
            }
        }

        //解决报错java.lang.IllegalArgumentException
        //No view found for id 0x7f090254 (com.abbidot.tracker:id/fc_home_map_fragment) for fragment HomeMapGoogleMapFragment
        //https://www.jianshu.com/p/9235092f407a
        childFragmentManager.commit {
            add(R.id.fc_home_map_fragment, mFragment)
        }
//        (mActivity as FragmentActivity).supportFragmentManager.commit {
//            add(R.id.fc_home_map_fragment, mFragment)
//        }
        locationPermissionsTip(1)
    }

    override fun onResume() {
        super.onResume()
        if (mShowCenterLocationType == ConstantInt.PetLocationType) {
            isMoveCamera = true
        }
        getHomeV2Activity()?.apply {
            //其他页面是否选择了宠物
            if (mCurrentShowPetPos != mSelectPetPosition) {
                showPetNameAndHead(mSelectPetPosition)
            }
        }

        val showFence = Util.getShowFenceSp()
        val showDashed = MMKVUtil.getBoolean(MMKVKey.ShowDashedLine, false)
        //检测直播页面有没有修改围栏显示
        if (isShowFence != showFence) {
            if (null == mSelectMapTypeDialog) {
                setFencesShow(showFence)
            } else {
                mSelectMapTypeDialog?.setFencesSwitch(showFence)
            }
        }
        if (isShowDashed != showDashed) {
            if (null == mSelectMapTypeDialog) {
                setDashedShow(showDashed)
            } else {
                mSelectMapTypeDialog?.setDashedSwitch(showDashed)
            }
        }
    }

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

    /**
     * 地图加载好了
     */
    private fun mapLoadOk() {
        LogUtil.e("MapV2Fragment 地图加载好了${getHomeV2Activity()?.mPetList}")
//        mHomeV2Activity.mDataViewModel.getHomeBindPetList(mHomeV2Activity)
        getHomeV2Activity()?.apply {
            if (mPetList.size > 0) showPetNameAndHead(mSelectPetPosition)
        }
    }

    override fun liveDataObserve() {
        //获取当前宠物位置和围栏信息
        mMapViewModel.apply {
            mMapDeviceLiveData.observe(this@MapV3Fragment) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { data ->
                            dealMapData(data)
                        }
                    }
                }, showLoading = false, isRequestErrorTip = false)
            }
            mRefreshLocationLiveData.observe(this@MapV3Fragment) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        mMapViewModel.updateMillisInFuture(0.05f)
                    }

                    override fun onInterceptCode() {
                        stopRefreshLocation()
                    }

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

        mCountDownTimerViewModel.mCountDownEndLiveData.observe(this) {
            mCountDownTimerViewModel.isStartCountDown = true
            mViewBinding.llHomeMapTopPet.homeDataPetNameSmall.text =
                getHomeV2Activity()?.getPet()?.petName
        }
        //删除围栏通知
        XEventBus.observe(this, EventName.DeleteFences) {
            updateMapDeviceStatus()
        }
        //添加编辑围栏通知
        XEventBus.observe(this, EventName.RefreshFences) {
            updateMapDeviceStatus()
        }
        //删除设备
        XEventBus.observe(this, EventName.DeleteDevice) {
            mMapViewModel.stopGetData()
        }
        //直播自动结束提示
        XEventBus.observe(this, EventName.LiveAutoEnd) {
            CommonDialog1(
                mContext!!,
                "",
                getString(R.string.txt_live_ended),
                false,
                5f,
                Typeface.BOLD,
                R.color.data_black_color
            ).show()
        }
        //直播超时
        XEventBus.observe(this, EventName.LiveOpenTimeOut) {
            ViewUtil.instance.showDialog(
                mContext!!,
                R.string.txt_time_out_try_again,
                object : BaseDialog.OnDialogOkListener {
                    override fun onOkClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        locationPermissionsTip()
                    }
                },
                okTextResId = R.string.txt_sure
            )
        }
        //蓝牙上报的数据
        XEventBus.observe(this, EventName.BleReportData) { reportData: BleReportDataBean ->
            getHomeV2Activity()?.getPet(false)?.apply {
                if (macID == reportData.mac) updateBleReportData(reportData)
            }
        }
        //设备获取手机位置
        XEventBus.observe(this, EventName.BleGetLocation) { mac: String ->
            getHomeV2Activity()?.getPet(false)?.apply {
                if (macID == mac) {
                    mHomeMapCommon.getUserGoogleLatLng()?.let { latLng: LatLng ->
                        SRBleUtil.instance.getConnectMacDevice(mac)?.let { ble ->
                            SRBleUtil.instance.writeData(
                                ble.bleDevice, SRBleCmdUtil.instance.getPhoneLocation(
                                    latLng.latitude, latLng.longitude
                                )
                            )
                        }
                    }
                }
            }
        }
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { trackBle: BleTrackDeviceBean ->
            getHomeV2Activity()?.getPet(false)?.apply {
                if (trackBle.mac == macID) {
                    if (trackBle.conState == ConState.CONNECTED) {
                        mViewBinding.ivHomeMapBleConState.setImageResource(R.drawable.icon_map_online)
                        mMapDeviceBean?.let {
                            //连接上蓝牙，关机不显示
                            if (it.powerSwitch == ConstantInt.Type0) {
                                it.canShowBattery = false
                                it.isCloseBattery = true
                                mViewBinding.llHomeMapDeviceBatteryLayout.visibility =
                                    View.INVISIBLE
                            }
                            mMapViewModel.setDeviceStateAndWarningData(
                                mContext!!,
                                getHomeV2Activity()?.getPet(),
                                it,
                                mViewBinding.ilHomeMapDeviceMsg.root,
                                mViewBinding.ilHomeMapDeviceMsg.tvDeviceMsgContent,
                                mViewBinding.ilHomeMapDeviceMsg.ivDeviceMsgCloseBtn,
                                mDeviceStateList,
                                mDeviceStateAdapter
                            )
                        }
                    } else {
                        mMapDeviceBean?.let {
                            if (it.powerSwitch == ConstantInt.Type0) {
                                it.canShowBattery = true
                                it.isCloseBattery = false
                            }
                        }
                        //隐藏蓝牙nearby
                        mViewBinding.ilHomeMapDeviceMsg.root.visibility = View.GONE
                        mViewBinding.ivHomeMapBleConState.setImageResource(R.drawable.icon_map_offline)
                        //蓝牙断开就重新获取服务器数据，蓝牙数据上报断开
                        updateMapDeviceStatus()
                    }
                    setRefreshLocationBtnState()
                }
            }
        }
        //接收开蓝牙操作,然后搜索连接设备
//        XEventBus.observe(this, EventName.BluetoothSwitch) { conState: Int ->
//            if (conState == ConState.BLUETOOTH_OFF) {
//                //隐藏蓝牙nearby
//                mViewBinding.ilHomeMapDeviceMsg.root.visibility = View.GONE
//                //蓝牙断开就重新获取服务器数据，蓝牙数据上报断开
//                updateMapDeviceStatus()
//            }
//        }
    }

    private fun dealMapData(data: MapDeviceBean) {
        mMapDeviceBean?.let { m ->
            data.notifyLocationFail = m.notifyLocationFail
            data.isCloseMsg = m.isCloseMsg
            data.isCloseBattery = m.isCloseBattery
            data.canShowBattery = m.canShowBattery
        }
        mMapDeviceBean = data

        getHomeV2Activity()?.apply {
            if (isNotifyRefreshLocation) {
                if (data.liveFlag == 0) {
                    stopRefreshLocation()
                    setMapData(data)
                    mMapViewModel.setDeviceStateAndWarningData(
                        mContext,
                        getPet(),
                        data,
                        mViewBinding.ilHomeMapDeviceMsg.root,
                        mViewBinding.ilHomeMapDeviceMsg.tvDeviceMsgContent,
                        mViewBinding.ilHomeMapDeviceMsg.ivDeviceMsgCloseBtn,
                        mDeviceStateList,
                        mDeviceStateAdapter
                    )
                } else {
                    //60秒超时
//                    val isRefreshTimeOut =
//                        (System.currentTimeMillis() - notifyRefreshLocationTimestamp) / 1000 >= 0
//                    if (isRefreshTimeOut) {
//                        stopRefreshLocation()
//                        mMapDeviceBean!!.notifyLocationFail = true
//                        mMapDeviceBean!!.isCloseBattery = false
//                        mMapDeviceBean!!.canShowBattery = true
//                        mViewBinding.ilHomeMapDeviceBatteryLayout.let {
//                            mMapViewModel.setMapDeviceBattery(
//                                mContext,
//                                mMapDeviceBean!!,
//                                it.root,
//                                it.tvDeviceBatteryInfo,
//                                it.ivDeviceCloseBtn
//                            )
//                        }
//                    }
                }
            } else {
                setMapData(data)
                mMapViewModel.setDeviceStateAndWarningData(
                    mContext,
                    getPet(),
                    data,
                    mViewBinding.ilHomeMapDeviceMsg.root,
                    mViewBinding.ilHomeMapDeviceMsg.tvDeviceMsgContent,
                    mViewBinding.ilHomeMapDeviceMsg.ivDeviceMsgCloseBtn,
                    mDeviceStateList,
                    mDeviceStateAdapter
                )
            }
        }
    }

    /**
     * 更新蓝牙上报的数据
     */
    private fun updateBleReportData(bleReportDataBean: BleReportDataBean) {
        bleReportDataBean.apply {
            if (haveDeviceStateData) {
                mMapViewModel.stopGetData()
                if (null == mMapDeviceBean) mMapDeviceBean = MapDeviceBean()
                mMapDeviceBean?.let {
                    Util.bleReportDataToMapDevice(it, bleReportDataBean)
                    if (haveLocationData) {
                        locationList?.let { list ->
                            val location = list[list.size - 1]
                            it.longitude = location.longitude
                            it.latitude = location.latitude
                        }
                        setMapDeviceBean(it)
                        mHomeMapCommon.refreshPetCurrentLocation(
                            it.latitude, it.longitude, isMoveCamera
                        )
                        mHomeMapCommon.startRefreshUserLocation()
                    }
                    mMapViewModel.setDeviceStateAndWarningData(
                        mContext!!,
                        getHomeV2Activity()?.getPet(),
                        it,
                        mViewBinding.ilHomeMapDeviceMsg.root,
                        mViewBinding.ilHomeMapDeviceMsg.tvDeviceMsgContent,
                        mViewBinding.ilHomeMapDeviceMsg.ivDeviceMsgCloseBtn,
                        mDeviceStateList,
                        mDeviceStateAdapter
                    )
                }
            }
        }
    }

    /**
     * 弹窗说明需要位置权限做什么，上架市场需要
     */
    private fun locationPermissionsTip(type: Int = 0) {
        if (XXPermissions.isGrantedPermissions(
                mContext!!, mutableListOf(
                    PermissionLists.getAccessFineLocationPermission(),
                    PermissionLists.getAccessCoarseLocationPermission()
                )
            )
        ) {
            if (type == 0) checkPermissions(type)
        } else {
            ViewUtil.instance.showDialog(
                mContext!!,
                getString(R.string.txt_location_tip),
                object : BaseDialog.OnDialogOkListener {
                    override fun onOkClick(dialog: BaseDialog<*>) {
                        dialog.dismiss()
                        if (type == 0) checkPermissions(type)
                        else Util.checkLocationPermissionsGpsEnabled(getHomeV2Activity()!!, {})
                    }
                },
                okTextResId = R.string.txt_accept,
                cancelTextResId = R.string.txt_deny
            )
        }
    }

    /**
     * 更新首页设备状态数据
     */
    private fun updateMapDeviceStatus(
        isNeedCountDown: Boolean = true, useBleLocation: Boolean = false
    ) {
        getHomeV2Activity()?.apply {
            if (mPetList.size <= mCurrentShowPetPos) return
            getPet()?.apply {
                //蓝牙连接上，就直接用蓝牙上报的位置刷新
                if (useBleLocation && BleManager.getInstance().isConnected(macID)) {
                    mMapDeviceBean?.let {
                        mHomeMapCommon.refreshPetCurrentLocation(
                            it.latitude, it.longitude, isMoveCamera
                        )
                        mHomeMapCommon.startRefreshUserLocation()
                    }
                } else {
                    mMapViewModel.getMapDeviceStatus(deviceId, isNeedCountDown)
                }
            }
        }
    }

    /**
     * 显示地图类型选择弹窗
     */
    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()
                }
            }, this, this
        )
        else {
            mSelectMapTypeDialog!!.mapTypeSpToUpdate()
        }
        mSelectMapTypeDialog?.show()
    }

    /**
     * 设置围栏显示
     */
    private fun setFencesShow(isShow: Boolean) {
        isShowFence = isShow
        MMKVUtil.putBoolean(MMKVKey.ShowFence, isShow)
        if (isShow) {
            mMapDeviceBean?.fences?.let { fences ->
                mFencesMapViewModel.setFencesData(mContext!!, fences, mFragment)
            }
        } else {
            mFencesMapViewModel.setFencesData(mContext!!, null, mFragment)
        }
    }

    /**
     * 设置虚线显示
     */
    private fun setDashedShow(isShow: Boolean) {
        isShowDashed = isShow
        MMKVUtil.putBoolean(MMKVKey.ShowDashedLine, isShow)
        if (isShow) {
            mHomeMapCommon.addUserAndPetLine()
        } else {
            mHomeMapCommon.removeUserAndPetLine()
        }
    }

    /**
     * 设置需要更新的标识
     */
    fun setNeedUpdateTag() {
        mCurrentShowPetPos = -1
    }

    /**
     * 显示选择宠物
     */
    fun showPetNameAndHead(position: Int) {
        //变量初始化
//        if (!::mHomeV2Activity.isInitialized) {
//            return
//        }
        getHomeV2Activity()?.apply {
            if (mPetList.size == 0) {
                return
            }
            needGpsToGCJ02 = true
            mCountDownTimerViewModel.isStartCountDown = false
            mCurrentShowPetPos = position

            //隐藏蓝牙nearby
            mViewBinding.ilHomeMapDeviceMsg.root.visibility = View.GONE
            mViewBinding.homeMapLiveBtn.visibility = View.GONE
            mViewBinding.llHomeMapDeviceBatteryLayout.visibility = View.INVISIBLE
            mViewBinding.ilHomeMapPetLocation.root.visibility = View.INVISIBLE
            mViewBinding.ivHomeMapBleConState.setImageResource(R.drawable.icon_map_offline)
            isCanLive = false
            setRefreshLocationBtnState()

            ViewUtil.instance.selectPetDialogShow(
                mContext,
                mPetList,
                position,
                mViewBinding.llHomeMapTopPet.homeDataPetNameSmall,
                mViewBinding.llHomeMapTopPet.homeDataPetHeadSmall.appHeadImage
            )

            if (mHomeMapCommon.isMapLoadOk()) {
                isMoveCamera = true
                mHomeMapCommon.clearMarker()
                mMapDeviceBean?.let {
                    it.isCloseMsg = false
                    it.isCloseBattery = false
                    it.canShowBattery = false
                }
                showLoading(true)
                val pet = mPetList[position]
                //重新设置地图宠物头像
                mHomeMapCommon.setPetHeadIcon(pet.imgurl, pet.petType)

                //获取首页设备信息状态
                updateMapDeviceStatus()
            }
        }
    }


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

            getHomeV2Activity()?.let {
                it.getPet(false)?.let { pet ->
                    if (SRBleUtil.instance.isMacConnect(pet.macID)) {
                        mViewBinding.ivHomeMapBleConState.setImageResource(R.drawable.icon_map_online)
                    }
                }
            }

            setMapDeviceBean(this)
            //设置循环查询时间间隔 30秒
//            mMapViewModel.updateMillisInFuture(0.5f)

            if (latitude == 0.0 && longitude == 0.0) {
                if (!mCountDownTimerViewModel.isStartCountDown) {
                    mHomeMapCommon.clearMarker()
                    isMoveCamera = true
                    mCountDownTimerViewModel.startCountDown(30)
                    mViewBinding.llHomeMapTopPet.homeDataPetNameSmall.setText(R.string.txt_locating)
                    mViewBinding.ilHomeMapPetLocation.root.visibility = View.INVISIBLE
                }
                mHomeMapCommon.switchShowLocation(ConstantInt.UserLocationType)
            } else {
                //判断是否国内经纬度，需要坐标转换
                if (needGpsToGCJ02) {
                    needGpsToGCJ02 = false
                    val isOutOfChina = LonAndLatUtil.isLocationOutOfChina(latitude, longitude)
                    MMKVUtil.putBoolean(MMKVKey.isGpsToGCJ02, !isOutOfChina)
                }
                mHomeMapCommon.refreshPetCurrentLocation(latitude, longitude, isMoveCamera)
                isMoveCamera = false
            }
            mHomeMapCommon.startRefreshUserLocation()

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

    private fun setRefreshLocationBtnState() {
        getHomeV2Activity()?.apply {
            getPet(false)?.let { pet ->
                mViewBinding.ivHomeMapRefreshLocation.let {
                    val tintColor = if (SRBleUtil.instance.isMacConnect(pet.macID)) {
                        it.setBackgroundResource(R.drawable.shape_yellow_circle_bg)
                        R.color.select_color3
                    } else if (!isCanLive) {
                        it.setBackgroundResource(R.drawable.shape_white_circle_bg)
                        R.color.grey_color_91
                    } else {
                        it.setBackgroundResource(R.drawable.shape_yellow_circle_bg)
                        R.color.select_color3
                    }
                    it.imageTintList =
                        ColorStateList.valueOf(ContextCompat.getColor(mContext, tintColor))
                }
            }
        }
    }

    private fun setLiveBtnState(canLive: Boolean) {
        mViewBinding.apply {
            ViewUtil.instance.viewShow(homeMapLiveBtn)
            val tColor = if (canLive) {
                homeMapLiveBtn.setBackgroundResource(R.drawable.shape38_green_alpha_circle_bg)
                R.color.data_black_color
            } else {
                homeMapLiveBtn.setBackgroundResource(R.drawable.shape38_gray_alpha_circle_bg)
                R.color.grey_color
            }
            tvHomeMapLiveTitle.setTextColor(ContextCompat.getColor(mContext!!, tColor))

            ivHomeMapLiveImage.let {
                val bg = if (canLive) {
                    it.imageTintList = ColorStateList.valueOf(0)
                    it.setImageResource(R.drawable.icon_red_dot)
                    R.drawable.icon_black_cir_ring
                } else {
                    it.imageTintList = ColorStateList.valueOf(
                        ContextCompat.getColor(
                            mContext!!, R.color.grey_color
                        )
                    )
                    R.drawable.icon_gray_cir_ring
                }
                it.setBackgroundResource(bg)
            }
        }
    }

    private fun setMapDeviceBean(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            val share = MMKVUtil.getInt(MMKVKey.Shared)
            //分钟后无上报、没有lte信号或在wifi中隐藏直播按钮
            isCanLive = !(Util.isTimeoutReport(
                updateTime, gnssInterval
            ) || powerSwitch == ConstantInt.Type0 || powerSwitch == ConstantInt.Type2 || powerSwitch == ConstantInt.Type3 || inWifiZone == ConstantInt.Type1)
            mViewBinding.homeMapLiveBtn.visibility =
                if (share != ConstantInt.NoShare || deviceType == ConstantInt.Type1) {
                    View.GONE
                } else {
                    if (liveFlag == ConstantInt.Type1) View.GONE
                    else {
                        setLiveBtnState(isCanLive)
                        View.VISIBLE
                    }
                }

            setRefreshLocationBtnState()

            mViewBinding.ilHomeMapDeviceBatteryLayout.let {
                mMapViewModel.setMapDeviceBattery(
                    mContext!!, mapDeviceBean, it.root, it.tvDeviceBatteryInfo, it.ivDeviceCloseBtn
                )
            }
            mViewBinding.ilHomeMapPetLocation.let {
                mMapViewModel.setPetLocationReverseGeocode(
                    mContext!!, mapDeviceBean, it.root, it.tvPetLocationReverseGeocode
                )
            }
            mHomeMapCommon.setMapDeviceBean(this)
        }
    }

    /**
     * 接收直播页面宠物弹窗操作
     */
    private val mActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            it.data?.apply {
                extras?.let { intent ->
                    if (it.resultCode == ResultCode.ResultCode_1) {
                        val isCloseBattery = intent.getBoolean(ConstantString.DeviceAuthorized)
                        val isCloseMsg = intent.getBoolean(ConstantString.PetAuthorized)
                        mMapViewModel.mDeviceMsgType =
                            intent.getInt(ConstantString.Type, mMapViewModel.mDeviceMsgType)
                        mMapDeviceBean?.let { m ->
                            if (isCloseBattery != m.isCloseBattery) {
                                m.isCloseBattery = isCloseBattery
                                mViewBinding.llHomeMapDeviceBatteryLayout.visibility =
                                    if (isCloseBattery) View.INVISIBLE else View.VISIBLE
                            }
                            if (isCloseMsg != m.isCloseMsg) {
                                m.isCloseMsg = isCloseMsg
                                mViewBinding.ilHomeMapDeviceMsg.root.visibility =
                                    if (isCloseMsg) View.GONE else View.VISIBLE
                            }
                        }
                    }
                }
            }
        }

    /**
     * 检查获取定位,蓝牙权限
     */
    private fun checkPermissions(type: Int) {
        getHomeV2Activity()?.apply {
            Util.checkBluetoothPermissionsEnabled(this, {
                if (type == 0) {
                    if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                        startActivity(intent)
                    } else if (isRequestPetData && mPetList.size == 0) {
                        showToast(R.string.no_bind_pet)
                    } else {
                        goLive(true)
                    }
                } else if (type == 1) {
                    if (!SRBleUtil.instance.isBleEnable(mContext)) {
                        SRBleUtil.instance.openBluetooth(mContext)
                    } else if (isRequestPetData && mPetList.size == 0) {
                        showToast(R.string.no_bind_pet)
                    } else {
                        goLive(false)
                    }
                }
            })
        }
    }

    private fun goLive(isLiveJump: Boolean) {
        getHomeV2Activity()?.apply {
            getPet()?.apply {
                val intent = Intent(mContext, LiveActivityV3::class.java)
                intent.putExtra(ConstantString.JumpActivity, isLiveJump)
                intent.putExtra(ConstantString.Pet, this)
                mMapDeviceBean?.let {
                    intent.putExtra(ConstantString.DeviceAuthorized, it.isCloseBattery)
                    intent.putExtra(ConstantString.PetAuthorized, it.isCloseMsg)
                    intent.putExtra(ConstantString.Type, mMapViewModel.mDeviceMsgType)
                }
//                            startActivity(intent)
                launchActivity(mActivityResultLauncher, intent)
            }
        }
    }

    /**
     * 开始通知一键定位
     */
    private fun notifyRefreshLocation() {
        getHomeV2Activity()?.apply {
            getPet()?.let { pet ->
                if (SRBleUtil.instance.isMacConnect(pet.macID)) {
                    showToast(R.string.txt_pet_close, gravity = Gravity.CENTER)
                } else if (null != mMapDeviceBean && mMapDeviceBean!!.powerSwitch == ConstantInt.Type2) {
                    val string = String.format(getString(R.string.txt_move_wake_up), pet.petName)
                    showToast(string, gravity = Gravity.CENTER)
                } else if (!isCanLive) {
                    showToast(R.string.txt_locate_works, gravity = Gravity.CENTER)
                } else if (!isNotifyRefreshLocation) {
                    isNotifyRefreshLocation = true
                    isMoveCamera = true
                    mViewBinding.llHomeMapTopPet.homeDataPetNameSmall.let {
                        it.setText(R.string.txt_locating)
                        it.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
                    }
                    notifyRefreshLocationTimestamp = System.currentTimeMillis()
                    mHomeMapCommon.greenRippleCircleAnim()
                    mViewBinding.ivHomeMapRefreshLocation.let {
                        it.isEnabled = false
                        it.imageTintList = ColorStateList.valueOf(
                            ContextCompat.getColor(
                                mContext, R.color.grey_color
                            )
                        )
                        mAnimatorSet = ViewUtil.instance.viewRotationAnimator(it, true)
                    }
                    mMapViewModel.stopGetData()
                    mMapViewModel.setupRefreshLocation(pet.deviceId)
                }
            }
        }
    }

    /**
     * 停止一键定位
     */
    private fun stopRefreshLocation() {
        getHomeV2Activity()?.apply {
            if (isNotifyRefreshLocation) {
                isNotifyRefreshLocation = false
                mHomeMapCommon.clearRippleCircleAnim()
                mViewBinding.ivHomeMapRefreshLocation.let {
                    it.isEnabled = true
                    it.imageTintList = ColorStateList.valueOf(
                        ContextCompat.getColor(
                            mContext, R.color.select_color3
                        )
                    )
                    mAnimatorSet?.cancel()
                }
                getPet(false)?.let { pet ->
                    mMapViewModel.updateMillisInFuture(0.35f)
                    mViewBinding.llHomeMapTopPet.homeDataPetNameSmall.let {
                        it.text = pet.petName
                        it.setCompoundDrawablesWithIntrinsicBounds(
                            0, 0, R.drawable.icon_gray_down_arrow, 0
                        )
                    }
                }
                refreshLocationBtnState()
            }
        }
    }

//    private fun goNavigation() {
//        mMapDeviceBean?.let { m ->
//            try {
//                //自动弹出手机中已经有安装地图的应用
//                val uri = if (MMKVUtil.getBoolean(MMKVKey.isGpsToGCJ02)) {
//                    val convertLatLon =
//                        LonAndLatUtil.convertFromWGS84ToGCJ02(m.latitude, m.longitude)
//                    "google.navigation:q=${convertLatLon[0]},${convertLatLon[1]}&mode=w".toUri()
//                } else {
//                    "google.navigation:q=${m.latitude},${m.longitude}&mode=w".toUri()
//                }
//                val intent = Intent(Intent.ACTION_VIEW, uri)
//                intent.setPackage("com.google.android.apps.maps")
//                startActivity(intent)
//            } catch (e: Exception) {
//                showToast(getString(R.string.txt_no_install))
//            }
//        }
//    }

    override fun onCheckedChanged(v: CompoundButton, isChecked: Boolean) {
        when (v.id) {
            R.id.cb_dialog_map_fences_switch -> setFencesShow(isChecked)
            R.id.cb_dialog_map_dashed_line_switch -> setDashedShow(isChecked)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                homeMapRefreshBtn -> {
                    getHomeV2Activity()?.let {
                        if (it.isRequestPetData && it.mPetList.size == 0) {
                            showToast(R.string.no_bind_pet)
                            return
                        }
                        when (mShowCenterLocationType) {
//                            ConstantInt.PetSpecialType -> {
//                                mShowCenterLocationType = ConstantInt.PetLocationType
//                                mHomeMapCommon.switchShowLocation(mShowCenterLocationType)
//                            }

                            ConstantInt.PetLocationType -> {
                                mShowCenterLocationType = ConstantInt.UserLocationType
                                mHomeMapCommon.switchShowLocation(mShowCenterLocationType)
                            }

                            ConstantInt.UserLocationType -> {
                                mShowCenterLocationType = ConstantInt.PetLocationType
//                                isMoveCamera = true
//                                updateMapDeviceStatus(useBleLocation = false)
                                mHomeMapCommon.switchShowLocation(mShowCenterLocationType)
                            }
                        }
                        ViewUtil.instance.setMapSwitchLocationButtonImage(
                            homeMapRefreshBtn, mShowCenterLocationType
                        )
                    }
                }

                homeMapLiveBtn -> {
                    if (isLimitClick()) return
                    if (!isCanLive) {
                        showToast(R.string.txt_live_works_cellular, gravity = Gravity.CENTER)
                        return
                    }
//                    locationPermissionsTip()
                    goLive(true)
                }

                ivHomeMapRefreshLocation -> notifyRefreshLocation()
                llHomeMapTopPet.ivTopPetBtnSmall -> showMapTypeDialog()
                homeMapBluetoothBtn -> {
                    if (isLimitClick()) return
                    checkPermissions(1)
                }

                llHomeMapTopPet.homeDataPetNameSmall, llHomeMapTopPet.homeDataPetHeadSmall.root -> {
                    getHomeV2Activity()?.let {
                        if (!it.isNotifyRefreshLocation) {
                            getHomeV2Activity()?.selectPetDialog()
                        }
                    }
                }

                ilHomeMapDeviceBatteryLayout.ivDeviceCloseBtn -> {
                    mMapDeviceBean?.isCloseBattery = true
                    llHomeMapDeviceBatteryLayout.visibility = View.INVISIBLE
                }

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

                ilHomeMapPetLocation.ivPetLocationNavigationBtn -> {
                    if (isLimitClick()) return
//                    goNavigation()
                    getHomeV2Activity()?.let {
                        mMapViewModel.showNavigationDialog(it, mMapDeviceBean)
                    }
                }
            }
        }
    }
}