package com.gh.gamecenter.personalhome

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckedTextView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.gh.common.databind.BindingAdapters
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.DirectUtils.directToBadgeWall
import com.gh.common.util.IntegralLogHelper
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.ImageViewerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.UserInfoActivity
import com.gh.gamecenter.UserInfoEditActivity
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentHomeBinding
import com.gh.gamecenter.feature.entity.Badge
import com.gh.gamecenter.feature.entity.MessageUnreadEntity
import com.gh.gamecenter.feature.entity.PersonalEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.gh.gamecenter.message.MessageUnreadViewModel
import com.gh.gamecenter.personalhome.background.PersonalityBackgroundActivity
import com.gh.gamecenter.personalhome.border.AvatarBorderActivity
import com.gh.gamecenter.personalhome.fans.FansActivity
import com.gh.gamecenter.personalhome.followers.FollowersActivity
import com.gh.gamecenter.personalhome.home.UserHistoryFragment
import com.gh.gamecenter.personalhome.home.UserHistoryViewModel
import com.gh.gamecenter.personalhome.home.game.UserGameFragment
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class UserHomeFragment : ToolbarFragment() {

    private var mPath = ""

    private var mHomeBinding: FragmentHomeBinding? = null

    private lateinit var mUserHomeViewModel: UserHomeViewModel
    private lateinit var mUserViewModel: UserViewModel
    private lateinit var mMessageUnreadViewModel: MessageUnreadViewModel
    private lateinit var mPersonalEntity: PersonalEntity
    private lateinit var mBitmap: Bitmap
    private lateinit var mPopupWindow: PopupWindow
    private var mBadgeCount = 0
    private var mPlayGameCount = 0
    private var mFragmentList = listOf<Fragment>()

    override fun getLayoutId() = 0
    override fun getInflatedLayout() =
        FragmentHomeBinding.inflate(layoutInflater).apply { mHomeBinding = this }.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mPath = arguments?.getString(EntranceConsts.KEY_PATH) ?: ""
        val userId = arguments?.getString(EntranceConsts.KEY_USER_ID) ?: ""

        mUserHomeViewModel =
            viewModelProvider(UserHomeViewModel.Factory(HaloApp.getInstance().application, userId))
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance().application))
        mMessageUnreadViewModel = viewModelProvider()

        mUserHomeViewModel.run {
            getUserInfo()
            getBadgeList()
            getUserPlayedGameCount()
        }

        mHomeBinding?.container?.setZoomView(mHomeBinding?.userBackgroundContainer)

        mUserHomeViewModel.userInfo.observeNonNull(this) {
            // 区分是数据初始化还是数据更新
            if (mHomeBinding?.viewpager?.adapter == null) {
                mHomeBinding?.container?.visibility = View.VISIBLE
                mHomeBinding?.reuseNoConnection?.root?.visibility = View.GONE

                if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
                    val data = mUserViewModel.loginObsUserinfo?.value?.data
                    it.icon = data?.icon ?: ""
                    it.name = data?.name ?: ""
                    it.introduce = data?.introduce ?: ""
                    it.iconBorder = data?.iconBorder
                    it.background = data?.background
                }

                SensorsBridge.trackPersonalHomepageBrowsing(
                    userId = it.id,
                    customerType = it.auth?.text ?: ""
                )

                updateUserInfo(it)
                updateTab(it)
            } else {
                updateUserInfo(it)
            }
        }

        mUserHomeViewModel.badges.observeNonNull(this) {
            mBadgeCount = it.size

            mHomeBinding?.badgeContainer?.visibility = View.VISIBLE
            if (it.isEmpty()) {
                mHomeBinding?.badgeTv?.visibility = View.GONE
                mHomeBinding?.badgeCountTv?.visibility = View.GONE
                mHomeBinding?.badgeMyBadgeIcon?.visibility = View.VISIBLE
            } else {
                mHomeBinding?.badgeTv?.visibility = View.VISIBLE
                mHomeBinding?.badgeCountTv?.visibility = View.VISIBLE
                mHomeBinding?.badgeMyBadgeIcon?.visibility = View.GONE
                mHomeBinding?.badgeCountTv?.text = mBadgeCount.toString()
                run outside@{
                    it.forEach { badge ->
                        if (badge.wear) {
                            ImageUtils.display(mHomeBinding?.badgeIcon, badge.icon)
                            mHomeBinding?.badgeIcon?.setOnClickListener {
                                DialogUtils.showViewBadgeDialog(
                                    requireContext(),
                                    Badge(badge.name, badge.icon, "", badge.actions)
                                ) {
                                    if (::mPersonalEntity.isInitialized) {
                                        directToBadgeWall(
                                            requireContext(),
                                            mPersonalEntity.id,
                                            mPersonalEntity.name,
                                            mPersonalEntity.icon
                                        )
                                    }
                                }
                            }
                            return@outside
                        }
                    }
                }
            }

            if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
                mUserHomeViewModel.availableBadges()
            }
        }

        mUserHomeViewModel.availableBadgeCount.observeNonNull(this) {
            mHomeBinding?.badgeTips?.visibility = if (it > 0) View.VISIBLE else View.GONE
        }

        mUserHomeViewModel.networkError.observeNonNull(this) {
            mHomeBinding?.container?.visibility = View.GONE
            mHomeBinding?.reuseNoConnection?.root?.visibility = View.VISIBLE
            mHomeBinding?.reuseNoConnection?.root?.setOnClickListener {
                mUserHomeViewModel.getUserInfo()
                mUserHomeViewModel.getUserPlayedGameCount()
            }
            toast("网络异常")
        }

        // 记录玩过的游戏总数
        mUserHomeViewModel.playGamesCount.observe(this, Observer {
            mPlayGameCount = it
        })

        mMessageUnreadViewModel.liveData.observeNonNull(this) {
            updateUnreadInfo(it)
        }

        mUserViewModel.editObsUserinfo.observeNonNull(this) {
            it.data?.let { updatedUserInfo ->
                if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
                    mUserHomeViewModel.userInfo.value?.run {
                        icon = updatedUserInfo.icon ?: ""
                        name = updatedUserInfo.name ?: ""
                        introduce = updatedUserInfo.introduce
                        iconBorder = updatedUserInfo.iconBorder
                        background = updatedUserInfo.background
                        updateUserInfo(this)
                    }
                }
            }
        }
    }

    private fun changeLayoutForContent() {
        mHomeBinding?.run {
            val set = ConstraintSet()
            set.run {
                clone(contentContainer)
                clear(R.id.user_icon, ConstraintSet.BOTTOM)
                connect(
                    R.id.user_icon,
                    ConstraintSet.TOP,
                    R.id.statusBarView,
                    ConstraintSet.BOTTOM,
                    50F.dip2px()
                )
                applyTo(contentContainer)
            }

            userCountContainer.post {
                if (!isAdded) return@post

                val newHeight = userCountContainer.bottom + (12F + 16F).dip2px()
                userBackgroundContainer.layoutParams = userBackgroundContainer.layoutParams.apply {
                    height = newHeight
                }

                val newSet = ConstraintSet()
                newSet.run {
                    clone(contentContainer)
                    clear(R.id.user_icon, ConstraintSet.TOP)
                    val marginBottom =
                        newHeight - DisplayUtils.getStatusBarHeight(resources) - 50F.dip2px() - 96F.dip2px()
                    connect(
                        R.id.user_icon,
                        ConstraintSet.BOTTOM,
                        R.id.user_background_container,
                        ConstraintSet.BOTTOM,
                        marginBottom
                    )
                    applyTo(contentContainer)
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mHomeBinding?.run {
            arrayListOf(
                ivBack,
                ivShare,
                ivMore
            ).forEach {
                it.setOnClickListener(this@UserHomeFragment)
            }

            appbar.addOnOffsetChangedListener(OnOffsetChangedListener { _: AppBarLayout?, verticalOffset: Int ->
                if (isAdded) {
                    val statusBarHeight =
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) 0 else DisplayUtils.getStatusBarHeight(
                            resources
                        )
                    val absOffset = abs(verticalOffset)
                    val invisibleOffset =
                        264f.dip2px() - 50f.dip2px() - 2f.dip2px() - statusBarHeight
                    if (absOffset < invisibleOffset) {
                        toolbar.setBackgroundColor(
                            ContextCompat.getColor(
                                requireContext(),
                                com.gh.gamecenter.common.R.color.transparent
                            )
                        )
                        toolbarContainer.background = null
                        userSmallContainer.visibility = View.GONE
                    } else {
                        if (this@UserHomeFragment::mBitmap.isInitialized) {
                            toolbar.setBackgroundColor(com.gh.gamecenter.common.R.color.white.toColor())
                            toolbarContainer.background = BitmapDrawable(resources, mBitmap)
                        } else {
                            toolbar.setBackgroundColor(
                                ContextCompat.getColor(
                                    requireContext(),
                                    com.gh.gamecenter.common.R.color.primary_theme
                                )
                            )
                        }
                        userSmallContainer.visibility = View.VISIBLE
                    }
                }
            })
        }
    }

    private fun updateTab(personalData: PersonalEntity) {
        val keyPosition = arguments?.getInt(EntranceConsts.KEY_TAB_INDEX, -1) ?: -1
        val type = UserHistoryViewModel.TYPE.fromValue(arguments?.getString(EntranceConsts.KEY_COMMUNITY_TYPE))
        val gameType = arguments?.getString(EntranceConsts.KEY_GAME_TYPE) ?: "game_collection"
        val count = personalData.count
        val position = if (keyPosition > -1) {
            keyPosition
        } else {
            // 根据是否有内容选择页面显示
            when {
                count.gameComment > 0 -> 0
                count.getTotalCount() > 0 -> 1
//                count.video > 0 -> 2
                else -> 0
            }
        }

        val tag = "android:switcher:${mHomeBinding?.viewpager?.id}:"
        val gameFragment = childFragmentManager.findFragmentByTag("${tag}0")
            ?: UserGameFragment.getInstance(mUserHomeViewModel.userId, count, gameType)
        val qaFragment = childFragmentManager.findFragmentByTag("${tag}1")
            ?: UserHistoryFragment.getInstance(
                mUserHomeViewModel.userId,
                UserHistoryViewModel.SCENE.QUESTION_ANSWER,
                count,
                type
            )
//        val videoFragment = childFragmentManager.findFragmentByTag("${tag}2")
//                ?: UserVideoHistoryFragment.getInstance(mUserHomeViewModel.userId, count)

        mFragmentList = listOf(gameFragment, qaFragment)
        val titleList = listOf("游戏", "发布")

        mHomeBinding?.viewpager?.offscreenPageLimit = mFragmentList.size
        mHomeBinding?.viewpager?.adapter =
            FragmentAdapter(childFragmentManager, mFragmentList, titleList)
        mHomeBinding?.viewpager?.currentItem = position
        mHomeBinding?.viewpager?.doOnPageSelected {
            if (it == 1) (mFragmentList[1] as UserHistoryFragment).onScrollStateChanged()
        }
        mHomeBinding?.tabLayout?.setupWithViewPager(mHomeBinding?.viewpager)
        mHomeBinding?.tabIndicator?.setupWithTabLayout(mHomeBinding?.tabLayout)
        mHomeBinding?.tabIndicator?.setupWithViewPager(mHomeBinding?.viewpager)

        mHomeBinding?.tabLayout?.run {
            for (i in 0 until tabCount) {
                val tab = getTabAt(i) ?: continue
                val tabView = getTabView(titleList[i])
                tab.customView = tabView
            }
        }

        BaseFragment_TabLayout.initTabStyle(mHomeBinding?.tabLayout, mHomeBinding?.viewpager?.currentItem ?: 0)
    }

    private fun getTabView(title: String): View {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.tab_item_user_home, null)
        val tabTitle = view.findViewById<View>(R.id.tab_title)
        if (tabTitle is CheckedTextView) {
            tabTitle.text = title
        }
        return view
    }

    private fun updateUnreadInfo(messageEntity: MessageUnreadEntity) {
        if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
            BindingAdapters.setMessageUnread(mHomeBinding?.userFansCountHint, messageEntity.fans)
            mHomeBinding?.userFansCountHint?.goneIf(messageEntity.fans == 0)
        }
    }

    private fun updateUserInfo(personalData: PersonalEntity) {
        mHomeBinding?.run {
            mPersonalEntity = personalData

            ImageUtils.display(userBackground, personalData.background?.url)
            ImageUtils.display(authIcon, personalData.auth?.icon)
            ImageUtils.display(recentVisitIcon, personalData.lastVisitor?.icon)

            userName.text = personalData.name
            authTv.text = personalData.auth?.text
            userIdTv.text = "ID:${personalData.getShortUserId()}"
            ipRegionTv.goneIf(!(personalData.source != null && personalData.source?.region?.isNotEmpty() == true))
            ipRegionTv.text = "IP属地：${personalData.source?.region}"
            userIntroduce.text = if (personalData.introduce.isNullOrBlank()) "这是一个很神秘的崽" else personalData.introduce
            todayVisitCount.text =
                if (personalData.count.todayVisit == null) "0" else personalData.count.todayVisit.toString()
            userFollowerCount.text = personalData.count.follower.toSimpleCount()
            userFansCount.text = personalData.count.fans.toSimpleCount()
            userVoteCount.text = personalData.count.vote?.toSimpleCount()
            userSmallName.text = personalData.name

            shadowView.goneIf(personalData.background?.url.isNullOrBlank() || personalData.background?.id?.isNotBlank() == true)
            regulationTestContainer.goneIf(personalData.regulationTest == null)
            authContainer.goneIf(personalData.auth == null)
            recentVisitIcon.goneIf(personalData.lastVisitor?.icon.isNullOrBlank())
            recentVisitEmpty.goneIf(personalData.lastVisitor?.icon?.isNotBlank() == true)

            changeLayoutForContent()

            // 截取背景图片，供toolbar使用
            if (!personalData.background?.url.isNullOrEmpty()) {
                ImageUtils.getBitmap(
                    personalData.background?.url ?: "",
                    object : BiCallback<Bitmap, Boolean> {
                        override fun onFirst(first: Bitmap) {
                            userBackground.postDelayed({
                                if (activity?.isFinishing == false && !isStateSaved) {
                                    val statusBarHeight =
                                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) 0 else DisplayUtils.getStatusBarHeight(
                                            resources
                                        )
                                    val bitmap = userBackground.getBitmapFromView()
                                    bitmap?.let {
                                        mBitmap = Bitmap.createBitmap(
                                            it,
                                            0,
                                            it.height - statusBarHeight - 50f.dip2px(),
                                            it.width,
                                            statusBarHeight + 50f.dip2px()
                                        )
                                    }
                                }
                            }, 1000)
                        }

                        override fun onSecond(second: Boolean) {
                            Utils.log("获取背景图片失败")
                        }
                    })
            }

            // 设置有边框挂件的头像
            userIcon.display(personalData.iconBorder?.url, personalData.icon, "")
            ImageUtils.display(userSmallIcon, personalData.icon)

            authTv.setOnClickListener {
                personalData.auth?.link?.let { link ->
                    NewFlatLogUtils.logClickAuthText(link.type ?: "", link.link ?: "", link.text ?: "", personalData.id, personalData.auth?.text ?: "")
                    DirectUtils.directToLinkPage(requireContext(), link, mEntrance, mPath)
                }
            }

            if (mUserHomeViewModel.userId != UserManager.getInstance().userId) {
                ivMore.visibility = View.VISIBLE
                ivShare.visibility = View.GONE
                changeBgTips.visibility = View.GONE
                userFansCountHint.visibility = View.GONE
                if (personalData.me.isFollower) {
                    userConcernedBtn.visibility = View.VISIBLE
                    userConcernContainer.visibility = View.GONE
                } else {
                    userConcernedBtn.visibility = View.GONE
                    userConcernContainer.visibility = View.VISIBLE
                }
            } else {
                ivMore.visibility = View.GONE
                ivShare.visibility = View.VISIBLE
                userEditBtn.visibility = View.VISIBLE
                userChangeBgBtn.visibility = View.VISIBLE
                recentVisitContainer.visibility = View.VISIBLE
                recentVisitIcon.setOnClickListener {
                    DirectUtils.directToHomeActivity(
                        requireContext(),
                        personalData.lastVisitor?.id,
                        "个人主页-最近来访"
                    )
                }

                // 默认显示悬浮窗，点击图标进入更换背景页，悬浮窗消失
                // 若未点击图标，当天内不再显示，第2天后进入继续显示悬浮窗
                changeBgTips.visibility = when {
                    SPUtils.getBoolean(Constants.SP_HAS_CLICK_CHANGE_BG) -> View.GONE

                    SPUtils.getBoolean(Constants.SP_SHOW_CHANGE_BG_TIPS, true) -> {
                        SPUtils.setBoolean(Constants.SP_SHOW_CHANGE_BG_TIPS, false)
                        View.VISIBLE
                    }

                    else -> View.GONE
                }

                // 跳转更换背景页
                userChangeBgBtn.setOnClickListener {
                    SPUtils.setBoolean(Constants.SP_HAS_CLICK_CHANGE_BG, false)
                    changeBgTips.visibility = View.GONE
                    startActivity(PersonalityBackgroundActivity.getIntent(requireContext()))
                }
                changeBgTips.setOnClickListener { userChangeBgBtn.performClick() }

                // 个性签名
                userIntroduce.setOnClickListener {
                    IntegralLogHelper.log("click_what's_up", LOCATION)
                    startActivity(
                        UserInfoEditActivity.getIntent(
                            requireContext(),
                            UserViewModel.TYPE_INTRODUCE
                        )
                    )
                }
            }

            personalData.background?.url?.let {
                userBackground.setOnClickListener {
                    startActivity(
                        ImageViewerActivity.getIntent(
                            requireContext(),
                            arrayListOf(personalData.background!!.url),
                            0,
                            arrayListOf(userIcon),
                            "$mEntrance+($mPath)",
                            true
                        )
                    )
                }
            }

            // 礼仪测试标签
            regulationTestContainer.setOnClickListener {
                if (::mPersonalEntity.isInitialized
                    && mUserHomeViewModel.userId == UserManager.getInstance().userId
                ) {
                    IntegralLogHelper.log("click_test_label", LOCATION)
                    DialogUtils.showPassRegulationDialog(requireContext(), mPersonalEntity.icon)
                }
            }

            // 徽章标签
            badgeContainer.setOnClickListener {
                if (::mPersonalEntity.isInitialized) {
                    IntegralLogHelper.log("click_badge_label", LOCATION)
                    directToBadgeWall(
                        requireContext(),
                        mPersonalEntity.id,
                        mPersonalEntity.name,
                        mPersonalEntity.icon
                    )
                }
            }

            userIcon.setOnClickListener {
                IntegralLogHelper.run {
                    log("click_profile_photo", LOCATION)
                    log("view_pendant", "头像挂件页")
                }
                if (mUserHomeViewModel.userId == UserManager.getInstance().userId) {
                    startActivity(AvatarBorderActivity.getIntent(requireContext()))
                } else {
                    startActivity(
                        ImageViewerActivity.getIntent(
                            requireContext(),
                            arrayListOf(personalData.icon),
                            0,
                            arrayListOf(userIcon.avatarView as View),
                            "$mEntrance+($mPath)",
                            true
                        )
                    )
                }
            }

            userFollowerContainer.setOnClickListener {
                IntegralLogHelper.log("click_follow", LOCATION)
                startActivity(
                    FollowersActivity.getIntent(
                        requireContext(),
                        mUserHomeViewModel.userId,
                        mEntrance,
                        mPath
                    )
                )
            }
            userFansContainer.setOnClickListener {
                IntegralLogHelper.log("click_follower", LOCATION)
                requireContext().startActivity(
                    FansActivity.getIntent(
                        requireContext(),
                        mUserHomeViewModel.userId,
                        mEntrance,
                        mPath
                    )
                )
            }
            userVoteContainer.setOnClickListener {
                IntegralLogHelper.log("click_like", LOCATION)
                Utils.toast(
                    requireContext(),
                    "共获得 " + NumberUtils.transSimpleCount(personalData?.count?.vote!!) + " 赞同"
                )
            }
            userEditBtn.setOnClickListener {
                IntegralLogHelper.log("click_edit", LOCATION)
                requireContext().startActivity(UserInfoActivity.getIntent(requireContext()))
            }
            userConcernContainer.setOnClickListener {
                SensorsBridge.trackUserFollowClick(
                    userId = personalData.id,
                    userName = personalData.name,
                    buttonName = "关注"
                )
                ifLogin("个人主页-关注-[关注]") {
                    mUserHomeViewModel.follow()
                }
            }

            userConcernedBtn.setOnClickListener {
                SensorsBridge.trackUserFollowClick(
                    userId = personalData.id,
                    userName = personalData.name,
                    buttonName = "已关注"
                )
                ifLogin("个人主页-关注-[关注]") {
                    DialogHelper.showDialog(
                        requireContext(),
                        "取消关注",
                        "确定要取消关注 ${personalData.name} 吗？",
                        "确定取消",
                        "暂不取消",
                        {
                            mUserHomeViewModel.unFollow()
                        }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                    )
                }
            }

            userName.setOnLongClickListener {
                userName.text.toString().copyTextAndToast("用户昵称已复制~")
                return@setOnLongClickListener true
            }

            userIdTv.setOnLongClickListener {
                userIdTv.text.toString().substring(3).copyTextAndToast("用户ID复制成功")
                return@setOnLongClickListener true
            }
        }
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.iv_back -> requireActivity().finish()

            R.id.iv_share -> {
                IntegralLogHelper.log("click_share", LOCATION)
                shareUserHome()
            }

            R.id.iv_more -> {
                IntegralLogHelper.run {
                    log("click_more", LOCATION)
                    log("view_panel-more", "更多面板")
                }
                showMorePopup()
            }
        }
    }

    private fun showMorePopup() {
        if (!::mPopupWindow.isInitialized) {
            mPopupWindow = PopupWindow(
                inflateMorePopupView(),
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )

            mPopupWindow.run {
                isTouchable = true
                isFocusable = true
                isOutsideTouchable = true
            }
        }

        mPopupWindow.showAsDropDown(mHomeBinding?.ivMore, (-49F).dip2px(), 0)
    }

    private fun inflateMorePopupView(): View {
        val contentView = View.inflate(activity, R.layout.popup_user_home_more, null)
        contentView.run {
            findViewById<TextView>(R.id.shareBtn)
                .setOnClickListener {
                    IntegralLogHelper.log("click_share", "更多面板")
                    mPopupWindow.dismiss()
                    shareUserHome()
                }

            findViewById<TextView>(R.id.reportBtn).setOnClickListener {
                IntegralLogHelper.log("click_report", "更多面板")
                mPopupWindow.dismiss()
                val items = arrayListOf(
                    context.getString(R.string.report_reason_one),
                    context.getString(R.string.report_reason_two),
                    context.getString(R.string.report_reason_three),
                    context.getString(R.string.report_reason_four),
                    context.getString(R.string.report_reason_other)
                )
                DialogUtils.showReportReasonDialog(requireContext(), items) { reason, desc ->
                    ifLogin("个人主页-举报") {
                        mUserHomeViewModel.postReport(reason, desc)
                    }
                }
            }
        }
        return contentView
    }

    private fun shareUserHome() {
        val content = (if (mPlayGameCount == 0) "" else "好燃~ 玩过 $mPlayGameCount 款游戏\n") +
                (if (mBadgeCount == 0) "" else "给力~ 已领取 $mBadgeCount 枚徽章\n") +
                "要好玩，上光环"
        if (::mPersonalEntity.isInitialized) {
            ShareUtils.getInstance(requireContext()).showShareUserHomeWindows(
                requireActivity(),
                mHomeBinding?.root,
                if (EnvHelper.isDevEnv) {
                    Constants.SHARE_USER_HOME_ADDRESS_DEV
                } else {
                    Constants.SHARE_USER_HOME_ADDRESS
                } + "?user=${mPersonalEntity.id}",
                mPersonalEntity.icon,
                "【推荐】来自光环助手的${mPersonalEntity.name}",
                content,
                ShareUtils.ShareEntrance.userHome,
                mPersonalEntity.id, null
            )
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if ("RefreshUserInfo" == reuse.type) {
            mUserHomeViewModel.getUserInfo()
            if (mFragmentList.isNotEmpty() && mFragmentList[1] is UserHistoryFragment) {
                (mFragmentList[1] as UserHistoryFragment).onLoadRefresh()
            }
        }
    }

    override fun onBackPressed(): Boolean {
        mHomeBinding?.viewpager?.run {
            if (currentItem == 1) {
                return (mFragmentList[1] as UserHistoryFragment).onBackPressed()
            }
        }
        return super.onBackPressed()
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mHomeBinding?.tabLayout?.run {
            for (i in 0 until tabCount) {
                val tab = getTabAt(i)
                if (tab != null) {
                    tab.customView?.findViewById<CheckedTextView>(R.id.tab_title)?.setTextColor(
                        if (tab.isSelected) com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()) else com.gh.gamecenter.common.R.color.text_secondary.toColor(
                            requireContext()
                        )
                    )
                    tab.customView?.findViewById<TextView>(R.id.tab_count)?.setTextColor(
                        if (tab.isSelected) com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()) else com.gh.gamecenter.common.R.color.text_secondary.toColor(
                            requireContext()
                        )
                    )
                }
            }
        }

        if (::mPopupWindow.isInitialized) {
            mPopupWindow.contentView = inflateMorePopupView()
        }
    }

    companion object {
        const val LOCATION = "个人主页"
    }
}