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

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.FencesZoneAdapter
import com.abbidot.tracker.base.BaseActivity
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.ActivityVirtualFencesBinding
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.FencesManageViewModel
import com.clj.fastble.BleManager
import com.qmuiteam.qmui.util.QMUIDisplayHelper

/**
 * 虚拟围栏列表
 */
class VirtualFencesActivity :
    BaseActivity<ActivityVirtualFencesBinding>(ActivityVirtualFencesBinding::inflate) {

    private val mFencesManageViewModel: FencesManageViewModel by viewModels()
    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()

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

    private lateinit var mFencesNoGoAdapter: FencesZoneAdapter
    private lateinit var mFencesNoGoList: MutableList<FencesBean>
    private var mPetBean: PetBean? = null
    private var mGetFencesBean: GetFencesBean? = null

    //需要同步设备的围栏数据
    private lateinit var mNeedSyncFencesList: MutableList<FencesBean>

    override fun getTopBar() = mViewBinding.virtualFencesTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_my_pet_fence)
        setLeftBackImage(R.drawable.icon_white_back_svg)
        mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)

        mFencesList = mutableListOf()
        mFencesNoGoList = mutableListOf()
        mNeedSyncFencesList = mutableListOf()

        mViewBinding.apply {

            mFencesAdapter = FencesZoneAdapter(mContext, mFencesList).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        goPreviewFencesZone(mFencesList[pos])
                    }
                })
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        if (mFencesList.size + mFencesNoGoList.size >= 5) {
                            return
                        }
                        goAddSafeZone()
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvFencesSafeZone, mFencesAdapter, top = QMUIDisplayHelper.dpToPx(18)
            )
            mFencesNoGoAdapter = FencesZoneAdapter(mContext, mFencesNoGoList).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        goPreviewFencesZone(mFencesNoGoList[pos])
                    }
                })
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        if (mFencesList.size + mFencesNoGoList.size >= 5) {
                            return
                        }
                        goAddNoGoZone()
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext, rvFencesNoGoZone, mFencesNoGoAdapter, top = QMUIDisplayHelper.dpToPx(18)
            )

            setOnClickListenerViews(btnAddFencesNoGoZone, btnAddFencesSafeZone)

            val share = MMKVUtil.getInt(MMKVKey.Shared)
            if (share != ConstantInt.NoShare) {
                btnAddFencesNoGoZone.visibility = View.INVISIBLE
                btnAddFencesSafeZone.visibility = View.INVISIBLE
            }

            val fencesCount = String.format(getString(R.string.txt_fences_set), "0/5")
            tvVirtualFencesCount.text = fencesCount
        }

        mPetBean?.apply {
            mFencesManageViewModel.getFenceList(this@VirtualFencesActivity, deviceId)
        }
    }

    override fun liveDataObserve() {
        //防止蓝牙同步超时
        mCountDownTimerViewModel.mCountDownEndLiveData.observe(this) {
            showNoCancelableLoading(false)
        }
        //接收更新围栏返回通知
        XEventBus.observe(this, EventName.RefreshFences) {
            mPetBean?.apply {
                mFencesManageViewModel.getFenceList(this@VirtualFencesActivity, deviceId)
            }
        }
        //接收删除围栏返回通知
        XEventBus.observe(this, EventName.DeleteFences) {
            mPetBean?.apply {
                mFencesManageViewModel.getFenceList(this@VirtualFencesActivity, deviceId)
            }
        }
        //获取所有围栏返回
        mFencesManageViewModel.mFencesLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mGetFencesBean = it.getOrNull()
                    mGetFencesBean?.apply {
                        setFencesData(this)
                    }
                }
            })
            val share = MMKVUtil.getInt(MMKVKey.Shared)
            if (share != ConstantInt.NoShare) {
                mFencesAdapter.showNoDataAddButton(false)
                mFencesNoGoAdapter.showNoDataAddButton(false)
            }
        }

        //接收发送指令后设备返回的数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receive: ReceiveDeviceData ->
            mPetBean?.let {
                //防止编辑围栏,重复执行
                if (it.macID == receive.mac && isFrontRunning) {
                    val data = receive.data
                    parseData(data)
                }
            }
        }
    }

    private fun setFencesData(getFencesBean: GetFencesBean) {
        mFencesList.clear()
        mFencesNoGoList.clear()
        mFencesAdapter.setData(mFencesList, true)
        mFencesNoGoAdapter.setData(mFencesNoGoList, true)
//        mSelectLabelsAdapter.notifyItemRangeChanged(0, mSelectLabelList.size)
        getFencesBean.normalFenceList?.apply {
            mFencesList.addAll(this.toList())
            mFencesAdapter.setData(mFencesList, true)
        }
        getFencesBean.nogoFenceList?.apply {
            mFencesNoGoList.addAll(this.toList())
            mFencesNoGoAdapter.setData(mFencesNoGoList, true)
        }

        val fencesCount = mFencesList.size + mFencesNoGoList.size

        mViewBinding.apply {
            svVirtualFencesLayout.visibility = View.VISIBLE

            val share = MMKVUtil.getInt(MMKVKey.Shared)
            if (share == ConstantInt.NoShare) {
                if (mFencesList.size == 0) btnAddFencesSafeZone.visibility = View.INVISIBLE
                else btnAddFencesSafeZone.visibility = View.VISIBLE

                if (mFencesNoGoList.size == 0) btnAddFencesNoGoZone.visibility = View.INVISIBLE
                else btnAddFencesNoGoZone.visibility = View.VISIBLE

                //围栏有一种超过5个，另外一种不能创建
                if (mFencesList.size >= 5) {
                    mFencesNoGoAdapter.showNoDataAddButton(false)
                    btnAddFencesNoGoZone.visibility = View.INVISIBLE
                } else {
                    mFencesNoGoAdapter.showNoDataAddButton(true)
                    btnAddFencesNoGoZone.visibility = View.VISIBLE
                }
                if (mFencesNoGoList.size >= 5) {
                    mFencesAdapter.showNoDataAddButton(false)
                    btnAddFencesSafeZone.visibility = View.INVISIBLE
                } else {
                    mFencesAdapter.showNoDataAddButton(true)
                    btnAddFencesSafeZone.visibility = View.VISIBLE
                }

                if (fencesCount >= 5) {
                    btnAddFencesNoGoZone.visibility = View.INVISIBLE
                    btnAddFencesSafeZone.visibility = View.INVISIBLE
                } else {
                    btnAddFencesNoGoZone.visibility = View.VISIBLE
                    btnAddFencesSafeZone.visibility = View.VISIBLE
                }
            }

            val countString = String.format(getString(R.string.txt_fences_set), "$fencesCount/5")
            tvVirtualFencesCount.text = countString
        }

        mPetBean?.apply {
            if (BleManager.getInstance().isConnected(macID)) {
                //设置8秒超时同步
                mCountDownTimerViewModel.startCountDown(8)
                showNoCancelableLoading(true, "")
                SRBleUtil.instance.isConnectBleSendCmdData(macID, SRBleCmdUtil.instance.getFences())
            }
        }
    }

    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) {
                if (data1 == 0) {
                    //围栏查询
                    verifyBleFences(data2, sliceArray(3..size - 2))
                } else if (data1 == 1 && data2 == 0) {
                    //围栏设置
                    mNeedSyncFencesList.removeAt(0)
                    if (mNeedSyncFencesList.size > 0) {
                        mPetBean?.apply {
                            SRBleUtil.instance.isConnectBleSendCmdData(
                                macID, SRBleCmdUtil.instance.setFences(mNeedSyncFencesList[0])
                            )
                        }
                    } else {
                        mCountDownTimerViewModel.stopCountDown()
                        showNoCancelableLoading(false)
                    }
                } else {
                    showNoCancelableLoading(false)
                }
            }
        }
    }

    /**
     * 检验设备里的围栏
     */
    private fun verifyBleFences(bleFencesCount: Int, data: ByteArray) {
        val bleFencesIdList = mutableListOf<String>()
        mNeedSyncFencesList.clear()
        //先把设备里存在的，服务器不存在的删除
        for (i in 0 until bleFencesCount) {
            //是否存在设备里的围栏id
            var bleFencesIdExist = false
            val step = i * 4
            val fenceId = data.sliceArray(step..step + 3).toHexString()
            bleFencesIdList.add(fenceId)
            for (fence in mFencesList) {
                if (fence.fenceId.takeLast(8) == fenceId) {
                    bleFencesIdExist = true
                    break
                }
            }
            if (!bleFencesIdExist) {
                for (fence in mFencesNoGoList) {
                    if (fence.fenceId.takeLast(8) == fenceId) {
                        bleFencesIdExist = true
                        break
                    }
                }
            }
            if (!bleFencesIdExist) {
                FencesBean().apply {
                    this.fenceId = fenceId
                    //删除
                    isOn = ConstantInt.Type2
                    mNeedSyncFencesList.add(this)
                }
            }
        }

        for (fence in mFencesList) {
            //是否存在服务器里的围栏id
            var serverFencesIdExist = false
            for (bleFenceId in bleFencesIdList) {
                if (fence.fenceId.takeLast(8) == bleFenceId) {
                    serverFencesIdExist = true
                    break
                }
            }
            if (!serverFencesIdExist) {
                mNeedSyncFencesList.add(fence)
            }
        }
        for (fence in mFencesNoGoList) {
            //是否存在服务器里的围栏id
            var serverFencesIdExist = false
            for (bleFenceId in bleFencesIdList) {
                if (fence.fenceId.takeLast(8) == bleFenceId) {
                    serverFencesIdExist = true
                    break
                }
            }
            if (!serverFencesIdExist) {
                mNeedSyncFencesList.add(fence)
            }
        }
        LogUtil.e("需要同步的围栏个数:${mNeedSyncFencesList.size}")
        for (a in mNeedSyncFencesList) LogUtil.e(a.toString())

        if (mNeedSyncFencesList.size > 0) {
            mPetBean?.apply {
                SRBleUtil.instance.isConnectBleSendCmdData(
                    macID, SRBleCmdUtil.instance.setFences(mNeedSyncFencesList[0])
                )
            }
        } else {
            mCountDownTimerViewModel.stopCountDown()
            showNoCancelableLoading(false)
        }
    }

    private fun goPreviewFencesZone(fencesBean: FencesBean) {
        Util.checkLocationPermissionsGpsEnabled(this, {
            mPetBean?.apply {
                val intent = Intent(mContext, PreviewFencesZoneActivity::class.java)
                intent.putExtra(ConstantString.Fence, fencesBean)
                intent.putExtra(ConstantString.Pet, mPetBean)
                startActivity(intent)
            }
        })
    }

    private fun goAddSafeZone() {
        val share = MMKVUtil.getInt(MMKVKey.Shared)
        if (share != ConstantInt.NoShare) return
        Util.checkLocationPermissionsGpsEnabled(this, {
            val intent = Intent(mContext, AddSafeZoneActivity::class.java)
            intent.putExtra(ConstantString.Pet, mPetBean)
            intent.putExtra(ConstantString.Fence, mGetFencesBean)
            startActivity(intent)
        })
    }

    private fun goAddNoGoZone() {
        val share = MMKVUtil.getInt(MMKVKey.Shared)
        if (share != ConstantInt.NoShare) return
        Util.checkLocationPermissionsGpsEnabled(this, {
            val intent = Intent(mContext, AddNoGoZoneActivity::class.java)
            intent.putExtra(ConstantString.Pet, mPetBean)
            intent.putExtra(ConstantString.Fence, mGetFencesBean)
            startActivity(intent)
        })
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnAddFencesSafeZone -> {
                    if (mFencesList.size + mFencesNoGoList.size >= 5) {
                        showToast(R.string.txt_created_many_fences)
                        return
                    }
                    goAddSafeZone()
                }

                btnAddFencesNoGoZone -> {
                    if (mFencesList.size + mFencesNoGoList.size >= 5) {
                        showToast(R.string.txt_created_many_fences)
                        return
                    }
                    goAddNoGoZone()
                }
            }
        }
    }
}