package com.abbidot.tracker.ui.fragment.account

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
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.tracker.R
import com.abbidot.tracker.adapter.HomeAccountMenuAdapter
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.constant.MultipleEntity
import com.abbidot.tracker.databinding.FragmentAccountV2Binding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.activity.account.UserProfileActivity
import com.abbidot.tracker.ui.activity.device.MyTrackerV2Activity
import com.abbidot.tracker.ui.activity.subscribe.MySubscriptionActivity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.UserProfileViewModel
import com.qmuiteam.qmui.util.QMUIDisplayHelper


/**
 * 首页Account
 * create an instance of this fragment.
 */
class AccountV2Fragment :
    BaseFragment<FragmentAccountV2Binding>(FragmentAccountV2Binding::inflate) {

    private lateinit var mUserViewModel: UserProfileViewModel

    private lateinit var mMenuAdapter: HomeAccountMenuAdapter
    private lateinit var mMenuList: MutableList<MenuTxtBean>
    private var mMeasurementUnit = 1

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

    override fun initData() {
        mViewBinding.apply {
            getHomeV2Activity()?.edgeToEdgeAdapterBars(
                llHomeAccountLayout, WindowInsetsCompat.Type.statusBars()
            )
            llHomeAccountTopUser.let {
                it.ivTopPetBtnSmall.visibility = View.GONE
                it.homeDataPetNameSmall.text =
                    MMKVUtil.getString(MMKVKey.UserName, getString(R.string.app_name))
                val imageUrl = MMKVUtil.getString(MMKVKey.HeadUrl)
                ViewUtil.instance.imageLoadUrl(
                    it.homeDataPetHeadSmall.appHeadImage, imageUrl, R.drawable.pic_avatar_df
                )
                it.homeDataPetNameSmall.setCompoundDrawablesWithIntrinsicBounds(
                    0, 0, R.drawable.icon_gray_right_arrow, 0
                )
            }

            addListData()
            mMenuAdapter = HomeAccountMenuAdapter(this@AccountV2Fragment, mMenuList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext!!, rvHomeAccountMenu, mMenuAdapter, top = QMUIDisplayHelper.dpToPx(6)
            )
            setOnClickListenerViews(
                llHomeAccountMyTracker,
                llHomeAccountSubscription,
                llHomeAccountTopUser.homeDataPetHeadSmall.root,
                llHomeAccountTopUser.homeDataPetNameSmall
            )
        }

        //切换到账户ActivityV2Fragment 页面，会导致ViewModel生命周期销毁，需要重新创建
        mUserViewModel = ViewModelProvider(this)[UserProfileViewModel::class.java]

        getHomeV2Activity()?.apply {
            mUserViewModel.getUserInfo(this)
        }
    }

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

    private fun addListData() {
        mMenuList = mutableListOf()
        ViewUtil.instance.addMenuBean(mMenuList, getString(R.string.txt_help))
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_tracker_guide),
            imageResId = R.drawable.icon_cellular_network_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
//        ViewUtil.instance.addMenuBean(
//            mMenuList,
//            getString(R.string.txt_features_guide),
//            imageResId = R.drawable.icon_cells_svg,
//            menuType = MultipleEntity.IMG_TEXT
//        )
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_feedback),
            imageResId = R.drawable.icon_help_square_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
        ViewUtil.instance.addMenuBean(mMenuList, getString(R.string.txt_setting))
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_notifications),
            imageResId = R.drawable.icon_notification_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_measurement_units),
            imageResId = R.drawable.icon_measurement_units_svg,
            menuType = MultipleEntity.IMG_TEXT,
            value = Util.getMeasureUnitName(mContext!!)
        )
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_permissions),
            imageResId = R.drawable.icon_permissions_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_advanced_set),
            imageResId = R.drawable.icon_advanced_set_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
        ViewUtil.instance.addMenuBean(mMenuList, getString(R.string.txt_more))
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_setting_about),
            imageResId = R.drawable.icon_about_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
//        ViewUtil.instance.addMenuBean(
//            mMenuList,
//            getString(R.string.txt_shop),
//            imageResId = R.drawable.icon_store_svg,
//            menuType = MultipleEntity.IMG_TEXT
//        )
//        ViewUtil.instance.addMenuBean(
//            mMenuList,
//            getString(R.string.txt_setting_clear),
//            imageResId = R.drawable.icon_database_restore_svg,
//            menuType = MultipleEntity.IMG_TEXT,
//            value = "0.00\tKb"
//        )
        ViewUtil.instance.addMenuBean(
            mMenuList,
            getString(R.string.txt_sign_out),
            imageResId = R.drawable.icon_logout_svg,
            menuType = MultipleEntity.IMG_TEXT
        )
    }

    override fun liveDataObserve() {
        XEventBus.observe(viewLifecycleOwner, EventName.UpdateUserInfo) {
            getHomeV2Activity()?.let {
                mUserViewModel.getUserInfo(it)
            }
        }
        mUserViewModel.apply {
            mUserInfoLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { info ->
                            MMKVUtil.putString(MMKVKey.Email, info.email)
                            MMKVUtil.putString(MMKVKey.UserName, info.userName)
                            MMKVUtil.putString(MMKVKey.HeadUrl, info.imgurl)
                            MMKVUtil.putString(MMKVKey.CountryCode, info.countryCode)
                            mViewBinding.llHomeAccountTopUser.let { view ->
                                view.homeDataPetNameSmall.text = info.userName
                                ViewUtil.instance.imageLoadUrl(
                                    view.homeDataPetHeadSmall.appHeadImage,
                                    info.imgurl,
                                    R.drawable.pic_avatar_df
                                )
                            }
                        }
                    }
                })
            }

            mUpdateMeasureUnitLiveData.observe(viewLifecycleOwner) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.apply {
                            MMKVUtil.putInt(MMKVKey.MeasureUnit, mMeasurementUnit)
                            mMenuAdapter.notifyItemChanged(5)
                        }
                    }
                })
            }
        }
    }


    fun setMeasureUnit(measurementUnit: Int) {
        mMeasurementUnit = measurementUnit
        mUserViewModel.updateMeasureUnit(measurementUnit)
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                llHomeAccountTopUser.homeDataPetHeadSmall.root, llHomeAccountTopUser.homeDataPetNameSmall -> startActivity(
                    Intent(
                        mContext, UserProfileActivity::class.java
                    )
                )

                llHomeAccountMyTracker -> startActivity(
                    Intent(
                        mContext, MyTrackerV2Activity::class.java
                    )
                )

                llHomeAccountSubscription -> startActivity(
                    Intent(
                        mContext, MySubscriptionActivity::class.java
                    )
                )
            }
        }
    }
}