package com.abbidot.tracker.deprecated.ui.activity.map

import android.animation.ValueAnimator
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import coil.load
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.HistoryDataBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityMapLiveBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.LedLightViewModel
import com.abbidot.tracker.ui.common.map.MapLiveCommon
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.FindBleDeviceViewModel
import com.abbidot.tracker.vm.MapLiveViewModel
import com.clj.fastble.BleManager
import com.clj.fastble.data.BleDevice
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.qmuiteam.qmui.widget.QMUITopBar

/**
 *MapLive实时监测位置
 */
class MapLiveActivity : BaseActivity<ActivityMapLiveBinding>(ActivityMapLiveBinding::inflate) {

    private val mMapLiveViewModel: MapLiveViewModel by viewModels()
    val mFencesMapViewModel: FencesMapViewModel by viewModels()
    val mFencesManageViewModel: FencesManageViewModel by viewModels()
    private val mLedLightViewModel: LedLightViewModel by viewModels()
    private val mFindBleDeviceViewModel: FindBleDeviceViewModel by viewModels()
    lateinit var mPet: PetBean

    private lateinit var mFragment: Fragment
    private lateinit var mMapLiveCommon: MapLiveCommon

    //宠物是否在围栏里
    private var isInFence = -1

    //围栏数据集
    private val mFencesList = mutableListOf<FencesBean>()
    private var mHistoryDataBean: HistoryDataBean? = null
    private var mBleDevice: BleDevice? = null

    //动画效果,方便清除动画
    private var mGpsYoYoAnimString: YoYo.YoYoString? = null
    private var mBatteryYoYoAnimString: YoYo.YoYoString? = null
    private var mLiveStatus = 1

    override fun getTopBar(): QMUITopBar? = null

    override fun initData() {
        super.initData()

        mPet = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)!!

        mMapLiveCommon = MapLiveCommon()
        mFragment = mMapLiveCommon.getMapFragment(mContext, mPet.imgurl)
        supportFragmentManager.commit {
            add(R.id.map_live_map_view, mFragment)
        }

        mViewBinding.apply {
            setOnClickListenerViews(
                btnStopMapLive, mapLiveDeviceLedSwitch, mapLiveRefreshLocationBtn, btnFindDevice
            )
        }

        mMapLiveViewModel.setupDeviceLiveStatus(this, mPet.deviceId, mLiveStatus,0)
    }

    override fun liveDataObserve() {
        mMapLiveViewModel.mMapLiveStatusLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    showLoading(false)
                    if (mLiveStatus == 0) finish()
                }
            })
        }

        mMapLiveViewModel.mMapLiveLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
//                    setData(data)
                }
            })
        }

        mFencesManageViewModel.mFencesLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
//                    mFencesList.addAll(data)
                    //获取完围栏数据 再获取宠物 经纬度点 的数据
                    mMapLiveViewModel.getPetLivePoint(mPet.deviceId)
                }
            })
        }


        mLedLightViewModel.mLedSwitchLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mViewBinding.mapLiveDeviceLedSwitch.isChecked =
                        !mViewBinding.mapLiveDeviceLedSwitch.isChecked
                }
            })
        }
    }

    /**
     * 测试经纬度移动
     */
    private var indexX = 0.0
    private var indexY = 0.0

    private fun setData(historyDataBean: HistoryDataBean) {
        mHistoryDataBean = historyDataBean
        if (isInFence != historyDataBean.inFance) {
            isInFence = historyDataBean.inFance
            mFencesMapViewModel.setFencesData(mContext, mFencesList, mFragment)
        }
        //测试经纬度移动
//        mFencesViewModel.setFencesData(mContext!!, isInFence, mFencesList, mFragment)

        mViewBinding.apply {
            mapLivePetLayout.mapPetName.text = historyDataBean.petName
            ViewUtil.instance.imageLoadUrl(
                mapLivePetLayout.mapPetHead.appHeadImage, historyDataBean.petImgurl
            )
            val batteryString =
                String.format(getString(R.string.txt_battery_unit), historyDataBean.batteryLevel)
            mapLivePetLayout.mapPetBattery.text = batteryString

            val batteryResId = if (historyDataBean.batteryLevel > ConstantInt.LowBattery20) {
                mBatteryYoYoAnimString?.stop()
                R.drawable.ico_map_battery
            } else {
                mBatteryYoYoAnimString = null
                mBatteryYoYoAnimString =
                    YoYo.with(Techniques.FadeIn).repeat(ValueAnimator.INFINITE).duration(1000)
                        .playOn(mapLivePetLayout.mapPetBatteryImage)
                R.drawable.ico_map_battery_low
            }
            mapLivePetLayout.mapPetBatteryImage.load(batteryResId)

            val drawableResId = if (historyDataBean.gnssSignal > ConstantInt.NoSignal) {
                mGpsYoYoAnimString?.stop()
                mapLivePetLayout.mapPetGps.text = getString(R.string.txt_online)
                R.drawable.ico_map_gps
            } else {
                mapLivePetLayout.mapPetGps.text = getString(R.string.txt_offline)
                mGpsYoYoAnimString = null
                mGpsYoYoAnimString =
                    YoYo.with(Techniques.FadeIn).repeat(ValueAnimator.INFINITE).duration(1000)
                        .playOn(mapLivePetLayout.mapPetGpsImage)
                R.drawable.ico_gps_no
            }
            mapLivePetLayout.mapPetGpsImage.load(drawableResId)

            mapLiveDeviceLedSwitch.isChecked = historyDataBean.ledSwitch == ConstantInt.Open

            mMapLiveCommon.addLine(historyDataBean.latitude, historyDataBean.longitude)
        }

        //测试经纬度移动
//        if ((Math.random() * 100).toInt() % 2 == 0) {
//            indexX += (Math.random() * 0.02)
//            indexY -= (Math.random() * 0.02)
//            isInFence = ConstantInt.InFence
//        } else {
//            indexX -= (Math.random() * 0.03)
//            indexY += (Math.random() * 0.03)
//            isInFence = ConstantInt.OutFence
//        }
//        mMapLiveBaiduMapFragment?.addLine(indexX, indexY)
//        mMapLiveGoogleMapFragment?.addLine(LatLng(indexX, indexY))
    }

    override fun onBackPressed() {
        super.onBackPressed()
        stopMapLive()
    }

    private fun stopMapLive() {
        ViewUtil.instance.showDialog(
            mContext, R.string.txt_stop_live_tips, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    mLiveStatus = 0
                    mMapLiveViewModel.setupDeviceLiveStatus(
                        this@MapLiveActivity, mPet.deviceId, mLiveStatus,0
                    )
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    /**
     * 设置led开关
     */
    private fun setLedSwitch() {
        //屏蔽点击就变状态
        mViewBinding.mapLiveDeviceLedSwitch.isChecked =
            !mViewBinding.mapLiveDeviceLedSwitch.isChecked
        val ledSwitch = if (mViewBinding.mapLiveDeviceLedSwitch.isChecked) {
            setBleLedMode(mPet.macID, 0)
            ConstantInt.Close
        } else {
            setBleLedMode(mPet.macID, mHistoryDataBean!!.lightMode)
            ConstantInt.Open
        }
        mLedLightViewModel.setLedSwitch(this, mHistoryDataBean!!.deviceInfoId, ledSwitch,0)
    }

    /**
     *发送设备蓝牙指令
     */
    private fun setBleLedMode(macId: String, mode: Int) {
        if (null == mBleDevice) {
            SRBleUtil.instance.getConnectMacDevice(macId)?.apply {
                mBleDevice = bleDevice
            }
        }
        mBleDevice?.let {
            if (BleManager.getInstance().isConnected(it)) {
                SRBleUtil.instance.writeData(
                    it, SRBleCmdUtil.instance.ledState(SRBleCmdUtil.CMD_WRITE, mode)
                )
            }
        }
    }

    override fun onClick(v: View?) {
        when (v!!) {
            mViewBinding.btnStopMapLive -> {
                stopMapLive()
            }

            mViewBinding.btnFindDevice -> {
//                mFindBleDeviceViewModel.startScanFind(this, mPet.macID)
            }

            mViewBinding.mapLiveDeviceLedSwitch -> {
                setLedSwitch()
            }

            mViewBinding.mapLiveRefreshLocationBtn -> {
                ViewUtil.instance.viewAlphaAndRotationObjectAnimator(
                    mViewBinding.mapLiveRefreshLocationBtn
                )
                mMapLiveCommon.refreshPetCurrentLocation()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBatteryYoYoAnimString?.stop()
        mGpsYoYoAnimString?.stop()
    }
}