package com.abbidot.tracker.ui.activity.pet

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.FamilyBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityShowInviteDeviceBinding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.vm.FamilyViewModel

class ShowInviteDeviceActivity :
    BaseActivity<ActivityShowInviteDeviceBinding>(ActivityShowInviteDeviceBinding::inflate) {

    private val mFamilyViewModel: FamilyViewModel by viewModels()

    override fun getTopBar() = mViewBinding.ilShowInviteDeviceTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")
        setLeftBackImage(R.drawable.icon_white_back_svg)

        mViewBinding.apply {
            setOnClickListenerViews(btnShowInviteDeviceOk)
        }

        val inviteArray = Util.getParcelableArrayListAdaptive(
            intent, ConstantString.Type, FamilyBean::class.java
        )
        if (inviteArray.isNullOrEmpty()) {
            mFamilyViewModel.getDeviceInviteInfo(this)
        } else {
            showInviteDialog(inviteArray)
        }
    }

    override fun liveDataObserve() {
        //获取设备邀请信息
        mFamilyViewModel.mInviteInfoLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    MMKVUtil.putInt(MMKVKey.isExistNewInvite, 0)
                    it.getOrNull()?.apply {
                        if (inviteArray.isNotEmpty()) showInviteDialog(inviteArray)
                    }
                }
            })
        }
    }

    private fun showInviteDialog(inviteArray: MutableList<FamilyBean>) {
        MMKVUtil.putInt(MMKVKey.isBindDevice, ConstantInt.Type1)
        MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.Type1)
        for (item in inviteArray) {
            val content = String.format(
                getString(R.string.txt_invites_you_check), item.userName, item.petName
            )
            mViewBinding.tvShowInviteDeviceName.text = content
            break
        }
    }


    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnShowInviteDeviceOk -> startActivityFinish(
                    Intent(
                        mContext, HomeV2Activity::class.java
                    )
                )
            }
        }
    }
}