package com.abbidot.tracker.ui.activity.device.fences

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import com.abbidot.baselibrary.constant.EventName
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.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.SelectFencesTypeCardShadeAdapter
import com.abbidot.tracker.adapter.VirtualFencesZoneShadeAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.FencesBean
import com.abbidot.tracker.bean.GetFencesBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityAddEditFencesZoneBinding
import com.abbidot.tracker.ui.common.map.FencesAddEditMapCommon
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.FencesManageViewModel
import com.abbidot.tracker.vm.FencesMapViewModel
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.widget.OnCircleViewScaleClickListener
import com.abbidot.tracker.widget.OnPolygonViewPointPullClickListener
import com.abbidot.tracker.widget.OnRectViewRotateScaleClickListener
import com.clj.fastble.BleManager
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo

/**
 * 添加编辑围栏
 */
open class AddAndEditFencesZoneBaseActivity :
    BaseActivity<ActivityAddEditFencesZoneBinding>(ActivityAddEditFencesZoneBinding::inflate),
    FencesAddEditMapCommon.OnActivityCallBack, OnRectViewRotateScaleClickListener,
    OnCircleViewScaleClickListener, OnPolygonViewPointPullClickListener {

    val mGeoCoderViewModel: GeoCoderViewModel by viewModels()
    private val mFencesManageViewModel: FencesManageViewModel by viewModels()
    private val mFencesMapViewModel: FencesMapViewModel by viewModels()

    private lateinit var mFragment: Fragment
    lateinit var mFencesMapCommon: FencesAddEditMapCommon

    lateinit var mFencesZoneShapeList: MutableList<DataBean>

    lateinit var mFencesZoneShapeAdapter: VirtualFencesZoneShadeAdapter
    lateinit var mFencesZoneTypeList: MutableList<DataBean>

    lateinit var mSelectTypeShadeAdapter: SelectFencesTypeCardShadeAdapter

    lateinit var mFencesBean: FencesBean
    var mPetBean: PetBean? = null
    var mFencesList: GetFencesBean? = null
    var isEditFences = false

    //冻结点击
    private var isBlockedClick = false

    private var mShowCenterLocationType = ConstantInt.OtherLocationType
    private val mDefaultFencesName =
        arrayOf("Home", "Office", "Garden", "Park", "Play", "Unsafe", "Vegetable Garden", "Water")

    //是否是卫星地图
    private var isSatelliteMap = false
    private lateinit var mHaveFencesList: MutableList<FencesBean>

    private lateinit var mDistanceUnit: String

    //操作类型，0增加，1编辑，2删除
    private var mActionType = ConstantInt.Type0

    override fun getTopBar() = mViewBinding.addEditFencesZoneTopBar.titleTopBar

    @SuppressLint("ClickableViewAccessibility")
    override fun initData() {
        super.initData()
//        setLeftBackImage(R.drawable.icon_white_back_svg)
        val mapTypeSp = Util.getMapTypeSp()
        isSatelliteMap = mapTypeSp == ConstantInt.Type1

        mDistanceUnit = Util.getMetricUnits(mContext, ConstantInt.Type3)

        mHaveFencesList = mutableListOf()
        mPetBean =
            Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)?.apply {
                mFencesBean.deviceId = deviceId
                mFencesBean.deviceServiceId = deviceServiceId
            }
        mFencesList =
            Util.getParcelableAdaptive(intent, ConstantString.Fence, GetFencesBean::class.java)

        mViewBinding.apply {
            root.setBackgroundResource(R.color.white)
            ViewUtil.instance.setMapSwitchLocationButtonImage(
                ivFencesZoneRefreshBtn, mShowCenterLocationType
            )
            ilFencesZoneNameInput.tvInputNameTitle.text = getString(R.string.txt_fence_name)
            fencesZoneCircleView.setOnCircleViewScaleClickListener(this@AddAndEditFencesZoneBaseActivity)
            fencesZoneRectView.setOnRectViewRotateScaleClickListener(this@AddAndEditFencesZoneBaseActivity)
            fencesZonePolygonView.setOnPolygonViewPointPullClickListener(this@AddAndEditFencesZoneBaseActivity)

            mFencesMapCommon = FencesAddEditMapCommon()
            mFragment = mFencesMapCommon.getMapFragment(
                mContext,
                mFencesBean,
                fencesZoneCircleView,
                fencesZoneRectView,
                fencesZonePolygonView,
                isEditFences,
                this@AddAndEditFencesZoneBaseActivity
            ) {
                mapLoadOk()
            }
            supportFragmentManager.commit {
                add(R.id.fc_fences_map_fragment, mFragment)
            }

            addListData()

            mFencesZoneShapeAdapter =
                VirtualFencesZoneShadeAdapter(mContext, mFencesZoneShapeList).apply {
                    setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                        override fun onItemClick(itemView: View?, pos: Int) {
                            if (mFencesZoneShapeList[pos].selected) return
                            ViewUtil.instance.updateDataBeanOnlySelectedItem(
                                this@apply, mFencesZoneShapeList, pos
                            )
                            setFenceShape(pos + 1)
                            mFencesMapCommon.calculateDistanceAndGetPointLatLng(
                                this@AddAndEditFencesZoneBaseActivity, 600
                            )
                        }
                    })
                }
            ViewUtil.instance.setRecyclerViewFlexboxLayout(
                mContext, rvFencesZoneShapeList, mFencesZoneShapeAdapter
            )

            mSelectTypeShadeAdapter =
                SelectFencesTypeCardShadeAdapter(mContext, mFencesZoneTypeList).apply {
                    setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                        override fun onItemClick(itemView: View?, pos: Int) {
                            ViewUtil.instance.updateDataBeanOnlySelectedItem(
                                this@apply, mFencesZoneTypeList, pos
                            )
                            if (mFencesBean.fenceType == 2) mFencesBean.fenceNameType = pos + 6
                            else mFencesBean.fenceNameType = pos + 1
                            setFenceName()
                        }
                    })
                }
            ViewUtil.instance.setRecyclerViewGridLayout(
                mContext, rvFencesZoneImageTypeList, mSelectTypeShadeAdapter, 5
            )

            setOnClickListenerViews(
                ivFencesZoneRefreshBtn,
                ivFencesZoneMapSwitchBtn,
                tvFencesZoneShapeResetBtn,
                btnCancelFencesZone,
                btnSaveFencesZone
            )

            var oldY = 0f
            val slideDis = 50
            rlAddEditFencesZoneInfoLayout.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        hideInputMethod(v)
                        oldY = event.y
                    }

                    MotionEvent.ACTION_MOVE -> {
                    }

                    MotionEvent.ACTION_UP -> {
                        if (!isKeyboardTranslate) {
                            if (event.y - oldY > slideDis) {
                                downLayout()
                            } else if (event.y - oldY < -slideDis) {
                                slideUpLayout()
                            }
                        }
                    }
                }
                false
            }
            //监听布局变化
            rlAddEditFencesZoneInfoLayout.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
                bottomMarginOverlap()
            }
        }

        setListenKeyboardChange(methodType = ConstantInt.Type1)

        setFenceName()
    }

    override fun leftBackOnClick() {
        if (isBlockedClick) return
        super.leftBackOnClick()
    }

    open fun mapLoadOk() {
        drawFences()
    }

    /**
     * 设置围栏名字
     */
    private fun setFenceName() {
        mViewBinding.ilFencesZoneNameInput.apply {
            val inputContent = etInputContent.text.toString()
            if (TextUtils.isEmpty(inputContent)) {
                etInputContent.setText(mDefaultFencesName[mFencesBean.fenceNameType - 1])
            } else {
                var isDefaultFencesName = false
                for (str in mDefaultFencesName) {
                    if (str == inputContent) {
                        isDefaultFencesName = true
                        break
                    }
                }
                if (isDefaultFencesName) etInputContent.setText(mDefaultFencesName[mFencesBean.fenceNameType - 1])
            }
        }
    }

    /**
     * 设置显示哪种围栏样式
     */
    fun setFenceShape(shapeType: Int) {
        if (mFencesMapCommon.isMapLoadOk()) showLoading(true)
        mViewBinding.fencesZoneCircleView.visibility = View.GONE
        mViewBinding.fencesZoneRectView.visibility = View.GONE
        mViewBinding.fencesZonePolygonView.visibility = View.GONE
        when (shapeType) {
            ConstantInt.CircleShapeType -> mViewBinding.fencesZoneCircleView.visibility =
                View.VISIBLE

            ConstantInt.RectangleShapeType -> mViewBinding.fencesZoneRectView.visibility =
                View.VISIBLE

            ConstantInt.PolygonShapeType -> mViewBinding.fencesZonePolygonView.visibility =
                View.VISIBLE
        }
        mFencesBean.fenceShapeType = shapeType
    }

    override fun liveDataObserve() {
        //反地理编码
        mGeoCoderViewModel.mLatLonAddressLiveData.observe(this) {
            if (mFencesBean.startDrag) return@observe
            mViewBinding.tvFencesZoneGpsLocation.apply {
                mFencesBean.address = it
//                visibility = if (TextUtils.isEmpty(it)) {
//                    View.INVISIBLE
//                } else {
//                    mFencesBean.address = it
//                    if (mViewBinding.ilFencesZoneNameInput.root.visibility == View.GONE) View.GONE
//                    else View.VISIBLE
//                }
//                text = it
            }
        }

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

    private fun parseData(data: ByteArray?) {
        data?.apply {
            val data0 = SRBleCmdUtil.instance.byteToInt(data[0])
            val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
            val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
            //围栏设置
            if (data0 == 0x13 && data1 == 1) {
                //成功
                if (data2 == 0) {
                    mFencesBean.modeType = ConstantInt.Type1
                    when (mActionType) {
                        ConstantInt.Type0 -> successTips(R.string.txt_save_successful)
                        ConstantInt.Type1 -> updateNetFences(mFencesBean)
                        ConstantInt.Type2 -> deleteNetFences(mFencesBean)
                    }
                } else {
                    //失败
                    mFencesBean.modeType = ConstantInt.Type3
                    when (mActionType) {
                        ConstantInt.Type0 -> saveFences(mFencesBean)
                        ConstantInt.Type1 -> updateNetFences(mFencesBean)
                        ConstantInt.Type2 -> deleteNetFences(mFencesBean)
                    }
                }
            }
        }
    }

    /**
     * 地图上画已添加的围栏
     */
    fun drawFences() {
        mFencesList?.apply {
            nogoFenceList?.let {
                mHaveFencesList.addAll(it.toList())
            }
            normalFenceList?.let {
                mHaveFencesList.addAll(it.toList())
            }

            if (mHaveFencesList.size > 0) mFencesMapViewModel.setImageFencesData(
                mContext, mHaveFencesList, mFragment, isSatelliteMap = isSatelliteMap
            )
        }
    }

    /**
     * 添加围栏通知
     */
    fun addLiveDataObserve() {
        mFencesManageViewModel.mFencesAddLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        //ble失败
                        if (mFencesBean.modeType == ConstantInt.Type3) {
                            successTips()
                        } else {
                            mFencesBean.fenceId = fenceId
                            mPetBean?.let { p ->
                                //有连接蓝牙
                                if (BleManager.getInstance().isConnected(p.macID)) {
                                    sendFenceData()
                                } else {
                                    successTips()
                                }
                            }
                        }
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setDisableState(false)
                }
            })
        }
    }

    /**
     * 删除、编辑更新围栏通知
     */
    fun editLiveDataObserve() {
        mFencesManageViewModel.mDeleteFenceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    XEventBus.post(EventName.DeleteFences)
                    showToast(
                        R.string.txt_delete_success, isFinish = true, gravity = Gravity.CENTER
                    )
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setDisableState(false)
                }
            })
        }
        mFencesManageViewModel.mUpdateFenceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    //失败
                    if (mFencesBean.modeType == ConstantInt.Type3) {
                        successTips()
                    } else {
                        successTips(R.string.txt_save_successful)
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setDisableState(false)
                }
            })
        }
    }

    /**
     * 发送围栏数据
     */
    private fun sendFenceData() {
        mPetBean?.apply {
            SRBleUtil.instance.isConnectBleSendCmdData(
                macID, SRBleCmdUtil.instance.setFences(mFencesBean)
            )
        }
    }

    /**
     * 修改成功提示
     */
    private fun successTips(resStringId: Int = R.string.txt_fence_saved) {
        XEventBus.post(EventName.RefreshFences)
        showToast(resStringId, isFinish = true, gravity = Gravity.CENTER)
    }

    /**
     * 设置禁止状态
     */
    private fun setDisableState(isDisable: Boolean) {
        isBlockedClick = isDisable
        mViewBinding.apply {
            if (isDisable) {
                ilFencesZoneNameInput.etInputContent.isEnabled = false
                setButtonEnabled(btnSaveFencesZone, ConstantInt.Type0)
            } else {
                ilFencesZoneNameInput.etInputContent.isEnabled = true
                setButtonEnabled(btnSaveFencesZone, ConstantInt.Type1)
            }
        }

    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        bottomMarginOverlap()
    }

    private fun slideUpLayout() {
        mViewBinding.apply {
            LogUtil.i("上滑")
//            tvFencesZoneGpsLocation.visibility = View.VISIBLE
//            tvFencesZoneShapeResetBtn.visibility = View.VISIBLE
            ilFencesZoneNameInput.root.visibility = View.VISIBLE
            rvFencesZoneImageTypeList.visibility = View.VISIBLE
            tvFencesZoneShapeTitle.visibility = View.VISIBLE
            rvFencesZoneShapeList.visibility = View.VISIBLE
            ivFencesZoneRefreshBtn.visibility = View.GONE
            ivFencesZoneMapSwitchBtn.visibility = View.GONE

//            mFencesMapCommon.resetFencesCentre(mFencesBean)

            YoYo.with(Techniques.BounceInUp).duration(800).onEnd {
                ViewUtil.instance.viewShowFadeInAnimation(ivFencesZoneRefreshBtn)
                ViewUtil.instance.viewShowFadeInAnimation(ivFencesZoneMapSwitchBtn)
            }.playOn(rlAddEditFencesZoneInfoLayout)
        }
    }

    private fun downLayout() {
        mViewBinding.apply {
            LogUtil.i("下滑")
            tvFencesZoneGpsLocation.visibility = View.GONE
            tvFencesZoneShapeResetBtn.visibility = View.GONE
            ilFencesZoneNameInput.root.visibility = View.GONE
            rvFencesZoneImageTypeList.visibility = View.GONE
            tvFencesZoneShapeTitle.visibility = View.GONE
            rvFencesZoneShapeList.visibility = View.GONE
            rlAddEditFencesZoneInfoLayout.visibility = View.GONE
            ivFencesZoneRefreshBtn.visibility = View.GONE
            ivFencesZoneMapSwitchBtn.visibility = View.GONE

//            mFencesMapCommon.resetFencesCentre(mFencesBean)

            YoYo.with(Techniques.BounceIn).onStart {
                rlAddEditFencesZoneInfoLayout.visibility = View.VISIBLE
            }.onEnd {
                ViewUtil.instance.viewShowFadeInAnimation(ivFencesZoneRefreshBtn)
                ViewUtil.instance.viewShowFadeInAnimation(ivFencesZoneMapSwitchBtn)
            }.duration(800).playOn(rlAddEditFencesZoneInfoLayout)
        }
    }

    /**
     * 重新设置布局位置
     */
    private fun bottomMarginOverlap() {
        mViewBinding.apply {
            ViewUtil.instance.setMapViewBottomMarginOverlap(
                rlAddEditFencesZoneMapLayout,
                rlAddEditFencesZoneInfoLayout.height,
                AppUtils.dpToPx(20)
            )

            //重新设置围栏中心
            mFencesMapCommon.resetFencesCentre(
                this@AddAndEditFencesZoneBaseActivity, fencesZoneCircleView, mFencesBean
            )
        }
    }

    private fun addListData() {
        mFencesZoneShapeList = mutableListOf()
        with(DataBean()) {
            imageId = R.drawable.icon_fence_circle_shape_svg
            selectImageId = R.drawable.icon_fence_circle_shape_select_svg
            selected = true
            mFencesZoneShapeList.add(this)
        }
        with(DataBean()) {
            imageId = R.drawable.icon_fence_rect_shape_svg
            selectImageId = R.drawable.icon_fence_rect_shape_select_svg
            mFencesZoneShapeList.add(this)
        }
        with(DataBean()) {
            imageId = R.drawable.icon_fence_polygon_shape_svg
            selectImageId = R.drawable.icon_fence_polygon_shape_select_svg
            mFencesZoneShapeList.add(this)
        }

        mFencesZoneTypeList = mutableListOf()
    }

    /**
     * 安全区域围栏数据初始化
     * @param isEditFences 编辑围栏不需要初始化大小
     */
    fun safeZoneInitData(isEditFences: Boolean = false) {
        mViewBinding.apply {
            safeZoneToMapTypeChangeColor()

            if (!isEditFences) {
                fencesZoneCircleView.initDefaultRadius()
                fencesZoneRectView.initDefaultWidthHeight()
                fencesZonePolygonView.initDefaultWidthHeightSize()
            }

            with(DataBean()) {
                imageId = R.drawable.icon_save_zone_type1_svg
                selected = true
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_save_zone_type2_svg
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_save_zone_type3_svg
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_save_zone_type4_svg
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_save_zone_type5_svg
                mFencesZoneTypeList.add(this)
            }
            mSelectTypeShadeAdapter.setData(mFencesZoneTypeList, true)
        }
    }

    /**
     * 危险区域围栏数据初始化
     * @param isEditFences 编辑围栏不需要初始化大小
     */
    fun noGoZoneInitData(isEditFences: Boolean = false) {
        mViewBinding.apply {
            fencesZoneCircleView.setColorAndImage(
                mContext,
                R.color.red_color2,
                R.color.red_color3,
                R.drawable.icon_fences_zone_gps_red_svg,
                R.drawable.icon_fence_circle_scale_red_svg
            )
            fencesZoneRectView.setColorAndImage(
                mContext,
                R.color.red_color2,
                R.color.red_color3,
                R.drawable.icon_fences_zone_gps_red_svg,
                R.drawable.icon_fence_rect_zoom_red_svg,
                R.drawable.icon_fence_dot_red_svg,
                R.drawable.icon_fence_rect_red_rotate_svg
            )
            fencesZonePolygonView.setColorAndImage(
                mContext,
                R.color.red_color2,
                R.color.red_color3,
                R.drawable.icon_fences_zone_gps_red_svg,
                R.drawable.icon_fence_polygon_operate_red_svg
            )

            if (!isEditFences) {
                fencesZoneCircleView.initDefaultRadius()
                fencesZoneRectView.initDefaultWidthHeight()
                fencesZonePolygonView.initDefaultWidthHeightSize()
            }

            with(DataBean()) {
                imageId = R.drawable.icon_no_zone_type1_svg
                selected = true
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_no_zone_type2_svg
                mFencesZoneTypeList.add(this)
            }
            with(DataBean()) {
                imageId = R.drawable.icon_no_zone_type3_svg
                mFencesZoneTypeList.add(this)
            }
            mSelectTypeShadeAdapter.setData(mFencesZoneTypeList, true)
        }
    }

    /**
     * 安全围栏根据地图类型改变颜色
     */
    private fun safeZoneToMapTypeChangeColor() {
        mViewBinding.apply {
            if (isSatelliteMap) {
                fencesZoneCircleView.setColorAndImage(
                    mContext,
                    R.color.select_color2,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_green_svg,
                    disTextColorRes = R.color.white
                )
                fencesZoneRectView.setColorAndImage(
                    mContext,
                    R.color.select_color2,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_green_svg,
                    disTextColorRes = R.color.white
                )
                fencesZonePolygonView.setColorAndImage(
                    mContext,
                    R.color.select_color2,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_green_svg
                )
            } else {
                fencesZoneCircleView.setColorAndImage(
                    mContext,
                    R.color.select_color,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_svg,
                    disTextColorRes = R.color.black
                )
                fencesZoneRectView.setColorAndImage(
                    mContext,
                    R.color.select_color,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_svg,
                    disTextColorRes = R.color.black
                )
                fencesZonePolygonView.setColorAndImage(
                    mContext,
                    R.color.select_color,
                    locationDrawableRes = R.drawable.icon_fences_zone_gps_svg
                )
            }
        }
    }

    /**
     * 保存围栏`
     */
    fun saveFences(fencesBean: FencesBean) {
        val fenceName = mViewBinding.ilFencesZoneNameInput.etInputContent.text.toString()
        if (TextUtils.isEmpty(fenceName)) {
            showToast(R.string.txt_not_null, gravity = Gravity.CENTER)
            return
        }
        fencesBean.apply {
            mPetBean?.let {
                modeType = if (modeType == ConstantInt.Type3) ConstantInt.Type3
                else if (BleManager.getInstance().isConnected(it.macID)) ConstantInt.Type1
                else ConstantInt.Type2
            }
            mActionType = ConstantInt.Type0
            setDisableState(true)
            name = fenceName
            when (fenceShapeType) {
                ConstantInt.CircleShapeType -> {
                    mFencesManageViewModel.addCircleFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }

                ConstantInt.RectangleShapeType -> {
                    mFencesManageViewModel.addRectFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }

                else -> {
                    mFencesManageViewModel.addPolygonFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }
            }
        }
    }

    /**
     * 更新围栏
     */
    fun updateFences(fencesBean: FencesBean) {
        if (isBlockedClick) return
        val fenceName = mViewBinding.ilFencesZoneNameInput.etInputContent.text.toString()
        if (TextUtils.isEmpty(fenceName)) {
            showToast(R.string.txt_not_null, gravity = Gravity.CENTER)
            return
        }
        mActionType = ConstantInt.Type1
        setDisableState(true)
        mPetBean?.let {
            if (BleManager.getInstance().isConnected(it.macID)) {
                sendFenceData()
            } else {
                fencesBean.modeType = ConstantInt.Type2
                updateNetFences(fencesBean)
            }
        }
    }

    /**
     * 更新接口围栏
     */
    private fun updateNetFences(fencesBean: FencesBean) {
        val fenceName = mViewBinding.ilFencesZoneNameInput.etInputContent.text.toString()
        if (TextUtils.isEmpty(fenceName)) {
            showToast(R.string.txt_not_null, gravity = Gravity.CENTER)
            return
        }
        fencesBean.apply {
            name = fenceName
            mPetBean?.let {
                modeType = if (modeType == ConstantInt.Type3) ConstantInt.Type3
                else if (BleManager.getInstance().isConnected(it.macID)) ConstantInt.Type1
                else ConstantInt.Type2
            }
            when (fenceShapeType) {
                ConstantInt.CircleShapeType -> {
                    mFencesManageViewModel.updateCircleFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }

                ConstantInt.RectangleShapeType -> {
                    mFencesManageViewModel.updateRectFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }

                else -> {
                    mFencesManageViewModel.updatePolygonFence(
                        this@AddAndEditFencesZoneBaseActivity, fencesBean
                    )
                }
            }
        }
    }

    /**
     * 删除围栏
     */
    fun deleteFences(fencesBean: FencesBean) {
        if (isBlockedClick) return
        ViewUtil.instance.showDialog(
            this, R.string.txt_delete_tips, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    mPetBean?.let {
                        mActionType = ConstantInt.Type2
                        setDisableState(true)
                        if (BleManager.getInstance().isConnected(it.macID)) {
                            //删除蓝牙标志
                            fencesBean.isOn = ConstantInt.Type2
                            sendFenceData()
                        } else {
                            fencesBean.modeType = ConstantInt.Type2
                            deleteNetFences(fencesBean)
                        }
                    }
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    /**
     * 删除围栏
     */
    private fun deleteNetFences(fencesBean: FencesBean) {
        fencesBean.apply {
            mFencesManageViewModel.deleteFence(
                this@AddAndEditFencesZoneBaseActivity, fenceId, deviceServiceId, modeType
            )
        }
    }

    /**
     * 恢复默认围栏大小
     */
    private fun recoverDefaultFencesView() {
        mViewBinding.apply {
            if (fencesZoneCircleView.isVisible) fencesZoneCircleView.initDefaultRadius()
            if (fencesZoneRectView.isVisible) fencesZoneRectView.initDefaultWidthHeight()
            if (fencesZonePolygonView.isVisible) fencesZonePolygonView.initDefaultWidthHeightSize()
            mFencesMapCommon.calculateDistanceAndGetPointLatLng(this@AddAndEditFencesZoneBaseActivity)
        }
    }

    override fun rectRotateClick() {
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun rectScaleEndClick() {
//        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun rectScalingClick() {
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun rectStartDragClick() {
        mFencesBean.startDrag = true
    }

    override fun rectEndDragClick() {
        mFencesBean.startDrag = false
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun circleScaleEndClick() {
//        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun circleStartDragClick() {
        mFencesBean.startDrag = true
    }

    override fun circleScalingClick() {
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun circleEndDragClick() {
        mFencesBean.startDrag = false
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun polygonPointPullClick() {
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    override fun polygonStartDragClick() {
        mFencesBean.startDrag = true
    }

    override fun polygonEndDragClick() {
        mFencesBean.startDrag = false
        mFencesMapCommon.calculateDistanceAndGetPointLatLng(delayMillis = 0)
    }

    /**
     * 切换地图类型
     */
    private fun switchMapType() {
        mViewBinding.apply {
            isSatelliteMap = !isSatelliteMap
            mFencesMapCommon.switchSatelliteAndNormalMapType()
            if (mHaveFencesList.size > 0) mFencesMapViewModel.setImageFencesData(
                mContext, mHaveFencesList, mFragment, isSatelliteMap = isSatelliteMap
            )
            if (mFencesBean.fenceType == ConstantInt.SafeZone) {
                safeZoneToMapTypeChangeColor()
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ivFencesZoneRefreshBtn -> {
                    when (mShowCenterLocationType) {
//                        ConstantInt.PetLocationType -> {
//                            mShowCenterLocationType = ConstantInt.UserLocationType
//                        }

                        ConstantInt.UserLocationType -> {
                            mShowCenterLocationType = ConstantInt.OtherLocationType
                        }

                        ConstantInt.OtherLocationType -> {
                            mShowCenterLocationType = ConstantInt.UserLocationType
                        }
                    }
                    mFencesBean.let {
                        mFencesMapCommon.switchShowLocation(
                            mShowCenterLocationType, it.latitudeCenter, it.longitudeCenter
                        )
                    }
                    ViewUtil.instance.setMapSwitchLocationButtonImage(
                        ivFencesZoneRefreshBtn, mShowCenterLocationType
                    )
                }

                tvFencesZoneShapeResetBtn -> recoverDefaultFencesView()
                btnCancelFencesZone -> if (!isBlockedClick) finish()
                ivFencesZoneMapSwitchBtn -> switchMapType()
            }
        }
    }

    override fun calculationDistance(distances: Array<String>) {
        if (mFencesBean.startDrag) return
        LogUtil.e("选点计算距离返回${distances.toList()}")
        if (distances[0].toDouble() <= 0) return
        when (mFencesBean.fenceShapeType) {
            ConstantInt.CircleShapeType -> {
                mFencesBean.radius = Utils.roundOffToInt(distances[0].toDouble())
                val r = Util.metricConvertUnits(distances[1].toFloat(), ConstantInt.Type3, 2)
                val radiusStr = Utils.roundOffToInt(r.toDouble()).toString() + mDistanceUnit
                mViewBinding.fencesZoneCircleView.setShowDisDistance(radiusStr)
            }

            ConstantInt.RectangleShapeType -> {
                mFencesBean.longDistance = Utils.roundOffToInt(distances[0].toDouble())
                mFencesBean.shortDistance = Utils.roundOffToInt(distances[1].toDouble())
                val l = Util.metricConvertUnits(distances[2].toFloat(), ConstantInt.Type3, 2)
                val s = Util.metricConvertUnits(distances[3].toFloat(), ConstantInt.Type3, 2)
                val longStr = Utils.roundOffToInt(l.toDouble()).toString() + mDistanceUnit
                val shortStr = Utils.roundOffToInt(s.toDouble()).toString() + mDistanceUnit
                mViewBinding.fencesZoneRectView.setShowDisDistance(longStr, shortStr)
            }

            else -> {
            }
        }
        //经纬度转成地址显示
        mFencesMapCommon.getLatLonAddress(mGeoCoderViewModel, mFencesBean)
        showLoading(false)
    }
}