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

import android.content.Intent
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
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.ActivityPreviewFencesZoneBinding
import com.abbidot.tracker.ui.common.map.PreviewFencesZoneCommon
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.clj.fastble.BleManager
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo

/**
 * 预览查看围栏
 */
class PreviewFencesZoneActivity :
    BaseActivity<ActivityPreviewFencesZoneBinding>(ActivityPreviewFencesZoneBinding::inflate) {

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

    private var mCurrentFences: FencesBean? = null
    private var mGetFencesBean: GetFencesBean? = null
    private var mPetBean: PetBean? = null
    private var mCurrentDeviceId = ""

    private lateinit var mFragment: Fragment
    private lateinit var mPreviewFencesMapCommon: PreviewFencesZoneCommon
    private var mShowCenterLocationType = ConstantInt.OtherLocationType

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

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

    //冻结点击
    private var isBlockedClick = false

    override fun getTopBar() = mViewBinding.previewFencesZoneTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")
        val share = MMKVUtil.getInt(MMKVKey.Shared)
        if (share == ConstantInt.NoShare) {
            mRightImageButton = addRightImageButton(R.drawable.icon_gray_delete_svg)
        }

        mFencesList = mutableListOf()

        intent?.apply {
            extras?.let {
                mCurrentFences =
                    Util.getParcelableAdaptive(intent, ConstantString.Fence, FencesBean::class.java)
                mPetBean =
                    Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
                        ?.apply {
                            mCurrentDeviceId = deviceId
                            mCurrentFences?.deviceServiceId = deviceServiceId
                            mCurrentFences?.deviceId = deviceId
                        }
            }
        }

        mPreviewFencesMapCommon = PreviewFencesZoneCommon()
        mFragment = mPreviewFencesMapCommon.getMapFragment(
            mContext,
        ) {
            mCurrentFences?.apply {
                setCurrentFencesInfo(this)
            }
            mFencesManageViewModel.getFenceList(
                this@PreviewFencesZoneActivity, mCurrentDeviceId
            )
        }
        supportFragmentManager.commit {
            add(R.id.fc_preview_fences_map_fragment, mFragment)
        }

        mViewBinding.apply {
            root.setBackgroundResource(R.color.white)
            mCurrentFences?.apply {
                deviceId = mCurrentDeviceId
            }
//            ViewUtil.instance.setMapSwitchLocationButtonImage(
//                ivPreviewFencesRefreshBtn, mShowCenterLocationType
//            )
            val duration = 600L
            YoYo.with(Techniques.FadeIn).duration(duration).onEnd {
                ivPreviewFencesMapSwitchBtn.visibility = View.VISIBLE
//                ivPreviewFencesRefreshBtn.visibility = View.VISIBLE
            }.playOn(rlPreviewFencesInfoLayout)

            setOnClickListenerViews(
                btnPreviewFencesEdit,
                ivPreviewFencesMapSwitchBtn,
                ivPreviewFencesRefreshBtn,
                mRightImageButton,
                cbPreviewFencesSwitch
            )

            if (share != ConstantInt.NoShare) {
                btnPreviewFencesEdit.visibility = View.GONE
                btnPreviewFencesActive.visibility = View.GONE
                cbPreviewFencesSwitch.visibility = View.GONE
                tvPreviewFencesActiveTxt.visibility = View.GONE
            }
        }
    }

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

    override fun liveDataObserve() {
        //获取所有围栏返回
        mFencesManageViewModel.mFencesLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mGetFencesBean = it.getOrNull()
                    mGetFencesBean?.apply {
                        setFencesData(this)
                    }
                }
            })
        }

        mFencesManageViewModel.mUpdateFenceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    XEventBus.post(EventName.RefreshFences)
                    mViewBinding.cbPreviewFencesSwitch.isChecked =
                        !mViewBinding.cbPreviewFencesSwitch.isChecked
                    showToast(R.string.txt_change_successful, gravity = Gravity.CENTER)
//                    mCurrentFences?.apply {
//                        isOn =
//                            if (mViewBinding.cbPreviewFencesSwitch.isChecked) ConstantInt.Open else ConstantInt.Close
//
//                    }
                    mFencesManageViewModel.getFenceList(
                        this@PreviewFencesZoneActivity, mCurrentDeviceId
                    )
                }
            })
        }

        mFencesManageViewModel.mDeleteFenceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    XEventBus.post(EventName.DeleteFences)
                    showToast(R.string.txt_delete_success, true, gravity = Gravity.CENTER)
                }

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

        //接收更新围栏返回通知
        XEventBus.observe(this, EventName.RefreshFences) {
            mFencesManageViewModel.getFenceList(
                this@PreviewFencesZoneActivity, mCurrentDeviceId
            )
        }

        //接收删除围栏返回通知
        XEventBus.observe(this, EventName.DeleteFences) {
            //是否是当前页面删除，放在重复收到本页面删除通知
            if (!isFrontRunning) finish()
        }

        //接收发送指令后设备返回的数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receive: ReceiveDeviceData ->
            mPetBean?.let {
                //防止编辑围栏页面,重复执行
                if (it.macID == receive.mac && isFrontRunning) {
                    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) {
                mCurrentFences?.let {
                    if (data2 == 0) {
                        //成功
                        it.modeType = ConstantInt.Type1
                        when (mActionType) {
                            ConstantInt.Type1 -> changeOnNetAndOff(it)
                            ConstantInt.Type2 -> deleteNetFences()
                        }
                    } else {
                        //失败
                        it.modeType = ConstantInt.Type3
                        when (mActionType) {
                            ConstantInt.Type1 -> changeOnNetAndOff(it)
                            ConstantInt.Type2 -> deleteNetFences()
                        }
                    }
                }
            }
        }
    }

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


    /**
     * 设置当前围栏的信息
     */
    private fun setCurrentFencesInfo(fencesBean: FencesBean) {
        mViewBinding.apply {
            val fenceNameTypeImage =
                ViewUtil.instance.getFenceNameImageType(fencesBean.fenceNameType)
            ilPreviewFencesTypeImage.ivSelectTypeImage.setImageResource(fenceNameTypeImage)
            tvPreviewFencesName.text = fencesBean.name
            tvPreviewFencesLocation.text = fencesBean.address
            cbPreviewFencesSwitch.isChecked = fencesBean.isOn == ConstantInt.Open
            mPreviewFencesMapCommon.restorePreviewFencesSetMapZoom(mContext, fencesBean)

            mShowCenterLocationType = ConstantInt.OtherLocationType
            ViewUtil.instance.setMapSwitchLocationButtonImage(
                ivPreviewFencesRefreshBtn, mShowCenterLocationType
            )
            mPreviewFencesMapCommon.switchShowLocation(
                mShowCenterLocationType, fencesBean.latitudeCenter, fencesBean.longitudeCenter
            )
        }
    }

    private fun setFencesData(getFencesBean: GetFencesBean) {
        getFencesBean.apply {
            mFencesList.clear()
            normalFenceList?.apply {
                for (fencesBean in this) {
                    if (fencesBean.fenceId == mCurrentFences?.fenceId) {
                        mCurrentFences = fencesBean
                        break
                    }
                }
                mFencesList.addAll(this.toList())
            }
            nogoFenceList?.apply {
                for (fencesBean in this) {
                    if (fencesBean.fenceId == mCurrentFences?.fenceId) {
                        mCurrentFences = fencesBean
                        break
                    }
                }
                mFencesList.addAll(this.toList())
            }

            mCurrentFences?.apply {
                setCurrentFencesInfo(this)
                setFencesAndPetData()
            }
        }
    }

    private fun setFencesAndPetData() {
        var currentFencesId = ""
        val mapTypeSp = Util.getMapTypeSp()
        isSatelliteMap = mapTypeSp == ConstantInt.Type1
        mCurrentFences?.apply {
            currentFencesId = fenceId
            mFencesMapViewModel.setImageFencesData(
                mContext, mFencesList, mFragment, currentFencesId, isSatelliteMap
            )
        }
        mGetFencesBean?.apply {
            mPetBean?.let {
                mCurrentFences?.deviceServiceId = it.deviceServiceId
                mCurrentFences?.deviceId = it.deviceId
                mPreviewFencesMapCommon.setPetCurrentLocation(
                    it.imgurl, it.petType, latitude, longitude
                )
            }
        }
    }

    /**
     * 修改开关状态
     */
    private fun changeOnAndOff(fencesBean: FencesBean) {
        mViewBinding.cbPreviewFencesSwitch.isChecked = !mViewBinding.cbPreviewFencesSwitch.isChecked
        fencesBean.apply {
            isOn = if (isOn == ConstantInt.Open) {
                ConstantInt.Close
            } else {
                ConstantInt.Open
            }
            mPetBean?.let {
                mActionType = ConstantInt.Type1
                if (modeType == ConstantInt.Type3) fencesBean.modeType = ConstantInt.Type3
                else if (BleManager.getInstance().isConnected(it.macID)) {
                    sendFenceData()
                } else {
                    fencesBean.modeType = ConstantInt.Type2
                    changeOnNetAndOff(fencesBean)
                }
            }
        }
    }

    /**
     * 修改开关状态
     */
    private fun changeOnNetAndOff(fencesBean: FencesBean) {
        fencesBean.apply {
            when (fenceShapeType) {
                ConstantInt.CircleShapeType -> {
                    mFencesManageViewModel.updateCircleFence(
                        this@PreviewFencesZoneActivity, this
                    )
                }

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

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

    }


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

    /**
     * 删除围栏
     */
    private fun deleteNetFences() {
        mCurrentFences?.apply {
            mFencesManageViewModel.deleteFence(
                this@PreviewFencesZoneActivity, fenceId, deviceServiceId, modeType
            )
        }
    }

    private fun goEditFences() {
        if (isBlockedClick) return
        Util.checkLocationPermissionsGpsEnabled(this, {
            mCurrentFences?.apply {
                val intent = if (fenceType == ConstantInt.SafeZone) Intent(
                    mContext, EditSafeZoneActivity::class.java
                )
                else Intent(mContext, EditNoGoZoneActivity::class.java)
                intent.putExtra(ConstantString.Pet, mPetBean)
                intent.putExtra(ConstantString.Fence, mGetFencesBean)
                intent.putExtra(ConstantString.CurrentFence, mCurrentFences)
                startActivity(intent)
            }
        })
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnPreviewFencesEdit -> goEditFences()

                mRightImageButton -> deleteFences()
                cbPreviewFencesSwitch -> {
                    if (isBlockedClick) return
                    mCurrentFences?.apply { changeOnAndOff(this) }
                }

                ivPreviewFencesMapSwitchBtn -> {
                    mPreviewFencesMapCommon.switchSatelliteAndNormalMapType()
                    //切换卫星地图，围栏换颜色
                    mCurrentFences?.apply {
                        setFencesAndPetData()
                    }
                }

                ivPreviewFencesRefreshBtn -> {
                    when (mShowCenterLocationType) {
                        ConstantInt.PetLocationType -> {
                            mShowCenterLocationType = ConstantInt.UserLocationType
                        }

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

                        ConstantInt.OtherLocationType -> {
                            mShowCenterLocationType = ConstantInt.PetLocationType
                        }
                    }
                    mCurrentFences?.apply {
                        mPreviewFencesMapCommon.switchShowLocation(
                            mShowCenterLocationType, latitudeCenter, longitudeCenter
                        )
                    }
                    ViewUtil.instance.setMapSwitchLocationButtonImage(
                        ivPreviewFencesRefreshBtn, mShowCenterLocationType
                    )
                }
            }
        }
    }
}