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

import android.content.Intent
import android.text.TextUtils
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.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.SubscriptionsOrderBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityAddPairedSuccessBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.AddTrackerDeviceViewModel
import com.abbidot.tracker.ui.activity.device.wifi.AddWifiPowerZone1Activity
import com.abbidot.tracker.ui.activity.subscribe.SubscriptionPlanActivity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.vm.PetInfoViewModel
import com.abbidot.tracker.vm.PetRelationViewModel
import com.abbidot.tracker.vm.UserProfileViewModel

class AddPairedSuccessActivity :
    BaseActivity<ActivityAddPairedSuccessBinding>(ActivityAddPairedSuccessBinding::inflate) {

    private val mAddTrackerViewModel: AddTrackerDeviceViewModel by viewModels()
    private val mPetViewModel: PetInfoViewModel by viewModels()
    private val mUserProfileViewModel: UserProfileViewModel by viewModels()
    private val mPetRelationViewModel: PetRelationViewModel by viewModels()

    private lateinit var mSubscriptionsOrderBean: SubscriptionsOrderBean

    private var isFirstBind = false
    private var mDeviceOutId = ""
    private var mDeviceId = ""
    private var mMac = ""
    private var mPetBean: PetBean? = null

    override fun getTopBar() = mViewBinding.ilAddPairedSuccessTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mDeviceId = getString(ConstantString.DeviceId, "")
            mMac = getString(ConstantString.Mac, "")
            mDeviceOutId = getString(ConstantString.DeviceOutId, "")
        }

        mSubscriptionsOrderBean = SubscriptionsOrderBean()

        mViewBinding.apply {
            tvPairSuccessDeviceOutId.text = mDeviceOutId
            setOnClickListenerViews(btnPairSuccessActivate)
        }
    }

    override fun liveDataObserve() {
        mAddTrackerViewModel.apply {
            //获取设备套餐可用状态
            mDeviceOrderStatusLiveData.observe(this@AddPairedSuccessActivity) {
                setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {

                            MMKVUtil.putString(MMKVKey.FirstDeviceId, mDeviceId)
                            MMKVUtil.putString(MMKVKey.FirstDeviceOutId, mDeviceOutId)
                            MMKVUtil.putString(MMKVKey.FirstDeviceMac, mMac)

                            mSubscriptionsOrderBean.let { o ->
                                o.deviceId = mDeviceId
                                o.userId = MMKVUtil.getString(MMKVKey.UserId)
                            }

                            //判断设备是否有可用套餐
                            if (availableOrder == ConstantInt.Type1) {
                                setButtonEnabled(
                                    mViewBinding.btnPairSuccessActivate, ConstantInt.Type0
                                )
                                //刷新设备绑定
                                mAddTrackerViewModel.updatePayDeviceState(
                                    this@AddPairedSuccessActivity, mDeviceId
                                )
                            } else {
                                mAddTrackerViewModel.getIccId(
                                    this@AddPairedSuccessActivity, mDeviceOutId
                                )
                            }
                        }
                    }
                })
            }

            //获取设备sim卡IccId
            mGetIccIdLiveData.observe(this@AddPairedSuccessActivity) {
                setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mSubscriptionsOrderBean.deviceOutId = mDeviceOutId
                            mSubscriptionsOrderBean.iccid = iccid
                            setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type0)

                            val intent = Intent(mContext, SubscriptionPlanActivity::class.java)
                            intent.putExtra(ConstantString.LkSetMeal, mSubscriptionsOrderBean)
                            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                            startActivityFinish(intent)
                        }
                    }
                })
            }

            //更新设备绑定状态
            mUpdatePayDeviceStateLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.isBind)
                        XEventBus.post(EventName.RefreshDevice)

                        mUserProfileViewModel.updateMeasureUnit(ConstantInt.Type1)
//                        if (isFirstBind) {
//                            mUserProfileViewModel.updateMeasureUnit(ConstantInt.Type1)
////                            val intent = Intent(mContext, FirstSetPetTypeActivity::class.java)
////                            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
////                            startActivityFinish(intent)
//                        } else finish()
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        LogUtil.e("支付成功后，更新绑定状态------->请求宠物数据错误onRequestError，再次请求")
                        if (exceptionCode == mNetworkRequestsFailLimit) {
                        } else {
                            setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type0)
                            mAddTrackerViewModel.updatePayDeviceState(
                                this@AddPairedSuccessActivity, mSubscriptionsOrderBean.deviceId
                            )
                        }
                    }
                })
            }

            //默认单位设置
            mUserProfileViewModel.mUpdateMeasureUnitLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            MMKVUtil.putInt(MMKVKey.MeasureUnit, ConstantInt.Type1)
                            PetBean().let { pet ->
                                pet.petName = "My Pet"
                                pet.deviceId = mDeviceId
                                pet.petType = ConstantInt.DogPetType
                                pet.gender = ConstantInt.WoMan
                                pet.macID = mMac
                                pet.birthdayDate = "2024-01-01"
                                pet.height = Utils.formatDecimal(Util.inToCm(20.0), 1).toFloat()
                                pet.weight = Utils.formatDecimal(Util.lbsToKg(25.0), 1).toFloat()
                                mPetBean = pet
                                mPetViewModel.addPet(this@AddPairedSuccessActivity, pet)
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }
            //添加默认宠物
            mPetViewModel.mAddPetLiveData.observe(this@AddPairedSuccessActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { pet ->
                            mPetBean?.let { petBean ->
                                petBean.petId = pet.petId
                                mPetRelationViewModel.bindPet(
                                    this@AddPairedSuccessActivity, petBean.deviceId, petBean.petId
                                )
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }
            //绑定默认宠物
            mPetRelationViewModel.mBindPetLiveData.observe(this@AddPairedSuccessActivity) {
                setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.RefreshPet)
                        showToast(R.string.txt_bind_success, isFinish = true)
                        mViewBinding.root.postDelayed({
                            MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.isBind)
                            if (isFirstBind) {
                                mPetBean?.apply {
                                    val intent =
                                        Intent(mContext, AddWifiPowerZone1Activity::class.java)
                                    intent.putExtra(ConstantString.Pet, this)
                                    intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                                    startActivity(intent)
                                }
                            }
                        }, 1500)
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type1)
                    }
                })
            }
        }
    }


    private fun addBindActivateDevice() {
        if (TextUtils.isEmpty(mDeviceOutId)) {
            showToast(R.string.txt_no_dfu)
            return
        }
        setButtonEnabled(mViewBinding.btnPairSuccessActivate, ConstantInt.Type0)
        mAddTrackerViewModel.getDeviceOrderStatus(
            this@AddPairedSuccessActivity, mDeviceOutId
        )
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnPairSuccessActivate -> addBindActivateDevice()
            }
        }
    }
}