package com.abbidot.tracker.ui

import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.MMKVKey
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.ChangePetListDialogAdapter
import com.abbidot.tracker.adapter.HowWorkAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.ActiveTimeBean
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.SleepTimeBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityDebugBinding
import com.abbidot.tracker.dialog.CommonListDialog
import com.abbidot.tracker.util.LonAndLatUtil
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.DataViewModel
import com.abbidot.tracker.vm.MapViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import com.qmuiteam.qmui.widget.QMUITopBar

class DebugActivity : BaseActivity<ActivityDebugBinding>(ActivityDebugBinding::inflate),
    ChangePetListDialogAdapter.OnChangeClickListener {

    private val mMapViewModel: MapViewModel by viewModels()
    private val mTrackerManageSetViewModel: TrackerInfoViewModel by viewModels()
    private val mDataViewModel: DataViewModel by viewModels()

    //    private var mDeviceId = "620e5c999e8f470cb5bd75d3"
//    private var mPet: PetBean? = null

    //宠物数据
    private var mPetList: MutableList<PetBean>? = null

    private lateinit var mMutableList: MutableList<MenuTxtBean>
    private lateinit var mAdapter: HowWorkAdapter
    private var mCommonListDialog: CommonListDialog? = null
    private lateinit var mChangePetListDialogAdapter: ChangePetListDialogAdapter

    //弹窗选中的宠物下标
    private var mPetSelectPosition = 0

    override fun getTopBar(): QMUITopBar = mViewBinding.qiNuoTestTopBar.titleTopBar

    override fun initData() {
        super.initData()

//        mPet = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        mPetList = intent.getParcelableArrayListExtra(ConstantString.Pet)
        mPetSelectPosition = intent.getIntExtra(ConstantString.Index, 0)

        setTopBarTitle("Debug")
        mMutableList = mutableListOf()

        mAdapter = HowWorkAdapter(mContext, mMutableList)
        ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
            mContext, mViewBinding.qiNuoTestRecyclerView, mAdapter, bottom = 20
        )

        initQMUICommonListItemView()

        LogUtil.e("${mPetList?.size}")
        if (null == mPetList) {
            return
        }
//        if (null == mPet) {
//            return
//        }

        mViewBinding.llDebugPet.setOnClickListener(this)
        val rightTextButton =
            mTopBar!!.addRightTextButton("刷新", R.id.topbar_right_change_textview)
        rightTextButton.setOnClickListener(this)

        mChangePetListDialogAdapter = ChangePetListDialogAdapter(mContext, mPetList)
        mChangePetListDialogAdapter.setSelectPetPos(mPetSelectPosition)
        mChangePetListDialogAdapter.setOnChangeClickListener(this)

        setPetData()
        mMapViewModel.getMapDeviceStatus(mPetList!![mPetSelectPosition].deviceId)
    }

    private fun initQMUICommonListItemView() {
        mViewBinding.switchBaseUrl.let {
            it.text = "国内服务器"
            it.switch.isChecked = MMKVUtil.getBoolean(MMKVKey.DebugIp, true)
            it.switch.setOnCheckedChangeListener { _, isChecked ->
                MMKVUtil.putBoolean(MMKVKey.DebugIp, isChecked)
                showToast("修改成功,注销登录并重启APP生效")
            }
        }
        mViewBinding.switchOnlyGoogleMap.let {
            it.text = "只启用谷歌地图"
            it.switch.isChecked = MMKVUtil.getBoolean(MMKVKey.OnlyGoogleMap, false)
            it.switch.setOnCheckedChangeListener { _, isChecked ->
                MMKVUtil.putBoolean(MMKVKey.OnlyGoogleMap, isChecked)
                showToast("修改成功,重启APP生效")
            }
        }
        mViewBinding.switchGoogleLatLonConversion.let {
            it.text = "谷歌地图经纬度转换"
            it.switch.isChecked = MMKVUtil.getBoolean(MMKVKey.isGpsToGCJ02, false)
            it.switch.setOnCheckedChangeListener { _, isChecked ->
                MMKVUtil.putBoolean(MMKVKey.isGpsToGCJ02, isChecked)
                showToast("修改成功,下次刷新位置生效")
            }
        }
    }

    /**
     * 设置宠物头像 名字
     */
    private fun setPetData() {
        val pet = mPetList!![mPetSelectPosition]
        mViewBinding.debugPetName.text = pet.petName
        ViewUtil.instance.setPetTypeHead(
            mViewBinding.debugPetHead.appHeadImage, pet.imgurl, pet.petType
        )

        ViewUtil.instance.viewAlphaAndRotationObjectAnimator(
            mViewBinding.debugPetHead.appHeadImage
        )
    }

    override fun liveDataObserve() {
        //获取当前宠物位置和围栏信息
        mMapViewModel.mMapDeviceLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    mMutableList.clear()
                    mAdapter.notifyDataSetChanged()
                    val data = it.getOrNull()
                    data?.apply {
                        ViewUtil.instance.addMenuBean(mMutableList, "设备Mac地址", data.deviceMacId)
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "deviceServerId", data.deviceServerId
                        )
                        var time =
                            Utils.formatTime(data.updateTime * 1000, Utils.DATE_FORMAT_PATTERN_CN2)
                        ViewUtil.instance.addMenuBean(mMutableList, "设备状态上报时间", time)
                        time = Utils.formatTime(
                            data.latLonUpdateTime * 1000, Utils.DATE_FORMAT_PATTERN_CN2
                        )
                        ViewUtil.instance.addMenuBean(mMutableList, "经纬度上报时间", time)
                        if (MMKVUtil.getBoolean(MMKVKey.isGpsToGCJ02)) {
                            val convertLatLon =
                                LonAndLatUtil.convertFromWGS84ToGCJ02(data.latitude, data.longitude)
                            ViewUtil.instance.addMenuBean(
                                mMutableList, "longitude", convertLatLon[1].toString()
                            )
                            ViewUtil.instance.addMenuBean(
                                mMutableList, "latitude", convertLatLon[0].toString()
                            )
                        } else {
                            ViewUtil.instance.addMenuBean(
                                mMutableList, "longitude", data.longitude.toString()
                            )
                            ViewUtil.instance.addMenuBean(
                                mMutableList, "latitude", data.latitude.toString()
                            )
                        }
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "安全围栏中inSafeZone(0=是)", data.inSafeZone.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "危险区域中inNoGoZone(0=不在)", data.inNoGoZone.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "inWifiZone", data.inWifiZone.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "当前速度", data.speed.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "gps信号gnssSignal", data.gpsSignal.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList,
                            "设备开关机状态(0关1开2眠3电)",
                            data.powerSwitch.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "电量batteryLevel", data.batteryLevel.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "设备led开关", data.ledSwitch.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "定位周期gnssInterval", "${data.gnssInterval / 60}分钟"
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "直播时间liveTime", "${data.liveTime / 60}分钟"
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "直播liveFlag", data.liveFlag.toString()
                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "LTE网络信号", "${data.lteSignal}"
                        )

                        mTrackerManageSetViewModel.getDeviceDetail(
                            this@DebugActivity, mPetList!![mPetSelectPosition].deviceId
                        )
                    }
                }
            })
        }


        mTrackerManageSetViewModel.mDeviceDetailLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!.deviceInfo
                    data?.let {
                        ViewUtil.instance.addMenuBean(mMutableList, "red", data.red.toString())
                        ViewUtil.instance.addMenuBean(mMutableList, "green", data.green.toString())
                        ViewUtil.instance.addMenuBean(mMutableList, "blue", data.blue.toString())
//                        ViewUtil.instance.addMenuBean(
//                            mMutableList, "设备开关机", data.turnOff.toString()
//                        )
                        ViewUtil.instance.addMenuBean(
                            mMutableList, "LED灯光模式lightMode", data.lightMode.toString()
                        )
                    }
                    val today = Utils.getCurrentTime(Utils.DATE_FORMAT_PATTERN_CN)
                    //请求该设备宠物的数据
                    mDataViewModel.getHomeDeviceData(
                        mPetList!![mPetSelectPosition].deviceId,
                        today,
                        mPetList!![mPetSelectPosition].petId
                    )
                }
            })
        }

        //获取首页Data模块的设备数据
        mDataViewModel.mHomeDataLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    val activeTime = data.activeTime
                    val sleepTime = data.sleepTime
                    setHomeData(activeTime!!, sleepTime!!)
                }
            })
        }
    }

    private fun setHomeData(activeTimeBean: ActiveTimeBean, sleepTimeBean: SleepTimeBean) {
        ViewUtil.instance.addMenuBean(
            mMutableList, "睡眠和运动数据", "日期：${activeTimeBean.dayTime}"
        )
        ViewUtil.instance.addMenuBean(mMutableList, "步数", "${activeTimeBean.steps}")
        ViewUtil.instance.addMenuBean(mMutableList, "运动总时间", "${activeTimeBean.activeTime}秒")
        ViewUtil.instance.addMenuBean(mMutableList, "运动数据", activeTimeBean.activeValue)
        ViewUtil.instance.addMenuBean(mMutableList, "睡眠总时间", "${sleepTimeBean.sleepTime}秒")
        ViewUtil.instance.addMenuBean(mMutableList, "睡眠数据", sleepTimeBean.sleepValue)
        mAdapter.setData(mMutableList, true)
    }

    //列表弹窗点击事件回调
    override fun onCurrentClick() {
        mCommonListDialog!!.dismiss()
    }

    override fun onChangeClick(position: Int) {
        mCommonListDialog!!.dismiss()
        mPetSelectPosition = position
        setPetData()
        mMapViewModel.getMapDeviceStatus(mPetList!![mPetSelectPosition].deviceId)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.topbar_right_change_textview -> mMapViewModel.getMapDeviceStatus(mPetList!![mPetSelectPosition].deviceId)
            R.id.ll_debug_pet -> {
                if (null == mCommonListDialog) {
                    mCommonListDialog =
                        CommonListDialog(mContext, mChangePetListDialogAdapter, 18, 0, 18)
                }
                mCommonListDialog!!.show()
            }
        }
    }
}