package com.abbidot.tracker.ui.fragment.pet

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.ViewPagerAdapter
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentPetV2Binding
import com.abbidot.tracker.deprecated.ui.activity.vm.NotificationsViewModel
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.account.NotificationV2Activity
import com.abbidot.tracker.ui.fragment.device.HomeTrackFragment
import com.abbidot.tracker.util.ViewUtil


/**
 * 首页pet
 * create an instance of this fragment.
 */
class PetV2Fragment : BaseFragment<FragmentPetV2Binding>(FragmentPetV2Binding::inflate) {

    private lateinit var mNotificationsViewModel: NotificationsViewModel

    private lateinit var mFragments: MutableList<Fragment>

    //当前这个页面显示的宠物下标
    private var mCurrentShowPetPos = -1

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = PetV2Fragment().apply {
            mContext = context
        }
    }

    override fun initData() {
        mFragments = mutableListOf(
            HomePetFragment.newInstance(mContext!!), HomeTrackFragment.newInstance(mContext!!)
        )

        mViewBinding.apply {
            getHomeV2Activity()?.edgeToEdgeAdapterBars(
                root, WindowInsetsCompat.Type.statusBars()
            )
            ilHomePetTopBar.ivTopPetBtnSmall.setImageResource(R.drawable.icon_noti_svg)

            rgSwitchPetTrack.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    rbPetSwitch.id -> {
                        vp2SwitchPetTrack.currentItem = 0
                    }

                    rbTrackSwitch.id -> {
                        vp2SwitchPetTrack.currentItem = 1
                    }
                }
            }

            getHomeV2Activity()?.let { ac ->
                vp2SwitchPetTrack.let {
                    it.adapter = ViewPagerAdapter(mFragments, ac)
                    ViewUtil.instance.setViewPager2Config(
                        it, object : ViewPager2.OnPageChangeCallback() {
                            override fun onPageSelected(position: Int) {
                                super.onPageSelected(position)
                                when (position) {
                                    0 -> rgSwitchPetTrack.check(rbPetSwitch.id)
                                    1 -> rgSwitchPetTrack.check(rbTrackSwitch.id)
                                }
                            }
                        })
                    setOnClickListenerViews(
                        ilHomePetTopBar.homeDataPetNameSmall,
                        ilHomePetTopBar.homeDataPetHeadSmall.root,
                        ilHomePetTopBar.ivTopPetBtnSmall
                    )
                }
            }
            if (AppUtils.isDebug()) {
                ilHomePetTopBar.homeDataPetHeadSmall.appHeadImage.setOnLongClickListener {
                    getHomeV2Activity()?.goToDebugActivity()
                    true
                }
            }
        }

        mNotificationsViewModel = ViewModelProvider(this)[NotificationsViewModel::class.java]
    }

    override fun liveDataObserve() {
        mNotificationsViewModel.mMessageCountLiveData.observe(viewLifecycleOwner) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        getMessageCount(unReadCount)
                    }
                }
            }, isRequestErrorTip = false, isShowNoDataTip = false)
        }
    }

    private fun getHomeV2Activity(): HomeV2Activity? {
        return if (null == activity) {
            LogUtil.e("PetV2Fragment,getHomeV2Activity,null == activity")
            null
        } else {
            activity as HomeV2Activity
        }
    }

    override fun onResume() {
        super.onResume()
        mNotificationsViewModel.getMessageUnReadCount()
        (mFragments[1] as HomeTrackFragment).onResume()
        getHomeV2Activity()?.apply {
            //其他页面是否选择了宠物
            if (mCurrentShowPetPos != mSelectPetPosition) {
                showPetNameAndHead(mSelectPetPosition)
            } else {
                (mFragments[1] as HomeTrackFragment).getPetTrackerInfoData()
            }
        }
        checkNotifyLocationState()
    }

    fun checkNotifyLocationState() {
        getHomeV2Activity()?.apply {
            checkNotifyRefreshLocation(mViewBinding.ilHomePetTopBar.homeDataPetNameSmall)
        }
    }

    override fun onPause() {
        super.onPause()
        (mFragments[1] as HomeTrackFragment).onPause()
    }

    private fun getMessageCount(unReadCount: Long) {
        var noReadNum = unReadCount
        mViewBinding.homePetMessageCountText.let {
            if (unReadCount > 0) {
                if (unReadCount > 99) noReadNum = 99
                it.visibility = View.VISIBLE
            } else it.visibility = View.GONE
            it.text = "$noReadNum"
        }
    }

    /**
     * 设置需要更新的标识
     */
    fun setNeedUpdateTag() {
        mCurrentShowPetPos = -1
    }

    /**
     * 显示选择宠物
     */
    fun showPetNameAndHead(position: Int) {
        getHomeV2Activity()?.let {
            if (it.mPetList.size == 0) {
                return
            }
            mCurrentShowPetPos = position

//        showLoading(true)

            ViewUtil.instance.selectPetDialogShow(
                mContext!!,
                it.mPetList,
                position,
                mViewBinding.ilHomePetTopBar.homeDataPetNameSmall,
                mViewBinding.ilHomePetTopBar.homeDataPetHeadSmall.appHeadImage
            )

            (mFragments[0] as HomePetFragment).getPetAllInfoData()
            (mFragments[1] as HomeTrackFragment).getPetTrackerInfoData(true)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilHomePetTopBar.homeDataPetNameSmall, ilHomePetTopBar.homeDataPetHeadSmall.root -> {
                    getHomeV2Activity()?.let {
                        if (!it.isNotifyRefreshLocation) it.selectPetDialog()
                    }
                }

                ilHomePetTopBar.ivTopPetBtnSmall -> startActivity(
                    Intent(mContext, NotificationV2Activity::class.java)
                )
            }
        }
    }
}