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

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.fragment.app.viewModels
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
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.HomePetFamilyAdapter
import com.abbidot.tracker.adapter.PetLabelsAdapter
import com.abbidot.tracker.adapter.PetsBadgesAdapter
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.PetAllInfoBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentHomePetBinding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.data.DataBoardActivity
import com.abbidot.tracker.ui.activity.pet.BadgesListActivity
import com.abbidot.tracker.ui.activity.pet.FamilyMembersActivity
import com.abbidot.tracker.ui.activity.pet.InviteFamilyActivity
import com.abbidot.tracker.ui.activity.pet.PetProfileActivity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.PetInfoViewModel
import com.qmuiteam.qmui.util.QMUIDisplayHelper


/**
 * 首页宠物切换页面
 * create an instance of this fragment.
 */
class HomePetFragment : BaseFragment<FragmentHomePetBinding>(FragmentHomePetBinding::inflate) {

    private val mPetViewModel: PetInfoViewModel by viewModels()

    private lateinit var mPetLabelsAdapter: PetLabelsAdapter
    private lateinit var mPetsBadgesAdapter: PetsBadgesAdapter
    private lateinit var mFamilyAdapter: HomePetFamilyAdapter

    private var mPetAllInfoBean: PetAllInfoBean? = null

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

    override fun initData() {
        mViewBinding.apply {
            root.setBackgroundResource(R.color.transparent)
            mPetLabelsAdapter = PetLabelsAdapter(mContext!!, null)
            ViewUtil.instance.setRecyclerViewFlexboxLayout(
                mContext!!,
                rvHomePetV2Label,
                mPetLabelsAdapter,
                top = QMUIDisplayHelper.dpToPx(8),
                right = AppUtils.dpToPx(10)
            )

            //宠物勋章
            val badges = mutableListOf<DataBean>()
            for (i in 0 until 4) badges.add(DataBean())
            mPetsBadgesAdapter = PetsBadgesAdapter(mContext!!, badges, 60)
            ViewUtil.instance.setRecyclerViewGridLayout(
                mContext!!,
                rvHomePetV2Badges,
                mPetsBadgesAdapter,
                spanCount = 4,
                AppUtils.dpToPx(60),
                offset = AppUtils.dpToPx(48)
            )

            mFamilyAdapter = HomePetFamilyAdapter(mContext!!, null).apply {
                setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
                    override fun onAgainListener() {
                        getHomeV2Activity()?.getPet()?.let { pet ->
                            if (Util.checkPackageLimit(getHomeV2Activity()!!, pet.deviceId)) {
                                return
                            }
                        }
                        goActivityNeedPet(InviteFamilyActivity::class.java)
                    }
                })
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        goActivityNeedPet(FamilyMembersActivity::class.java)
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvHomePetV2Family, mFamilyAdapter, top = QMUIDisplayHelper.dpToPx(16)
            )

            setOnClickListenerViews(
                btnHomePetManageActivity,
                btnHomePetFamilyManage,
                btnHomePetMoreAbout,
                btnHomePetBadgesViewAll
            )
        }

        getPetAllInfoData()
    }

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

    fun getPetAllInfoData() {
        getHomeV2Activity()?.let {
            it.getPet(false)?.apply {
                val share = MMKVUtil.getInt(MMKVKey.Shared)
                //被邀请的不显示家庭邀请信息
                mViewBinding.apply {
                    if (share == ConstantInt.NoShare) {
                        btnHomePetMoreAbout.visibility = View.VISIBLE
                        btnHomePetManageActivity.visibility = View.VISIBLE
                        rlHomePetV2FamilyLayout.visibility = View.VISIBLE
                    } else {
                        btnHomePetMoreAbout.visibility = View.GONE
                        btnHomePetManageActivity.visibility = View.GONE
                        rlHomePetV2FamilyLayout.visibility = View.GONE
                    }
                }
                mPetViewModel.getPetAllInfo(it, petId)
            }
        }
    }

    override fun liveDataObserve() {
//        XEventBus.observe(viewLifecycleOwner, EventName.RefreshPet) {
//            getPetAllInfoData()
//        }
        XEventBus.observe(viewLifecycleOwner, EventName.SetGoal) {
            getPetAllInfoData()
        }
        XEventBus.observe(viewLifecycleOwner, EventName.RefreshFamily) {
            getPetAllInfoData()
        }
        XEventBus.observe(viewLifecycleOwner, EventName.DeleteFamily) {
            getPetAllInfoData()
        }

        mPetViewModel.apply {
            mPetAllInfoLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            mPetAllInfoBean = this
                            setInfoData(this)
                        }
                    }
                })
            }
        }
    }

    private fun setLottieViewData(assetName: String) {
        mViewBinding.homePetTopLottieView.apply {
            if (isAnimating) cancelAnimation()
            if (TextUtils.isEmpty(assetName)) {
                cancelAnimation()
                visibility = View.GONE
            } else {
                visibility = View.VISIBLE
                setAnimation(assetName)
                playAnimation()
            }
        }
    }

    private fun setInfoData(petAllInfoBean: PetAllInfoBean) {
        mViewBinding.apply {
            petAllInfoBean.let {
                it.petInfo?.let { pet ->
                    when (pet.petType) {
                        ConstantInt.DogPetType -> setLottieViewData("lottie/active_dog.json")
                        ConstantInt.CatPetType -> setLottieViewData("lottie/cat_and_ball.json")
                        else -> setLottieViewData("")
                    }
                    tvHomePetV2Type.text = mPetViewModel.getTypeName(mContext!!, pet.petType)
                    tvHomePetV2Breed.text = pet.breed
                    tvHomePetV2Birthday.text = Utils.stringToDate(
                        pet.birthdayDate,
                        Utils.DATE_FORMAT_PATTERN_CN,
                        Utils.DATE_FORMAT_PATTERN_CN
                    )
                    tvHomePetV2Sex.text = mPetViewModel.getSexName(mContext!!, pet.gender)
                    val sexImage = if (pet.gender == ConstantInt.Man) {
                        R.drawable.icon_male_svg
                    } else {
                        R.drawable.icon_female_svg
                    }
                    tvHomePetV2Sex.setCompoundDrawablesWithIntrinsicBounds(
                        sexImage, 0, 0, 0
                    )
                    val labels = mPetViewModel.getLabelData(pet.labels)
                    mPetLabelsAdapter.setData(labels, true)
                    val badgeList = mPetViewModel.getBadges(mContext!!, pet.createDate, true)
                    mPetsBadgesAdapter.setData(badgeList, true)
                }
                it.activity?.let { act ->
                    //直接单位是min,不需要转换
                    val goal = if (act.goal >= ConstantInt.MinSportGoal) act.goal
                    else ConstantInt.DefaultSportGoal
                    MMKVUtil.putInt(MMKVKey.ActivityGoal, goal)
                    val goalStr =
                        getString(R.string.txt_activity_goal) + ": $goal" + getString(R.string.txt_min)
                    tvHomePetV2ActivityGoal.text = goalStr
                    //单位是秒，需要转换min
                    tvHomePetV2ActivityTime.text = "${act.activeTime / 60}"
                    tvHomePetV2ActivityCalories.text = Utils.formatDecimal(act.calories, 2)
                }

                mFamilyAdapter.setData(null)
                it.invites?.let { family ->
                    mFamilyAdapter.setData(family, true)
                    if (family.size > 0) {
                        btnHomePetFamilyManage.visibility = View.VISIBLE
                    } else {
                        btnHomePetFamilyManage.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun goActivityNeedDeviceId(cls: Class<*>) {
        mPetAllInfoBean?.petInfo?.apply {
            Intent(mContext, cls).let {
                it.putExtra(ConstantString.DeviceId, deviceId)
                startActivity(it)
            }
        }
    }

    private fun goActivityNeedPet(cls: Class<*>) {
        mPetAllInfoBean?.petInfo?.apply {
            Intent(mContext, cls).let {
                it.putExtra(ConstantString.Pet, this)
                startActivity(it)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnHomePetManageActivity -> goActivityNeedPet(DataBoardActivity::class.java)

                btnHomePetFamilyManage -> goActivityNeedPet(FamilyMembersActivity::class.java)

                btnHomePetMoreAbout -> {
                    mPetAllInfoBean?.petInfo?.let {
                        val intent = Intent(
                            mContext, PetProfileActivity::class.java
                        )
                        intent.putExtra(ConstantString.Edit, true)
                        intent.putExtra(ConstantString.Pet, it)
                        startActivity(intent)
                    }
                }

                btnHomePetBadgesViewAll -> goActivityNeedPet(BadgesListActivity::class.java)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBinding.homePetTopLottieView.cancelAnimation()
    }
}