package com.gh.gamecenter.personal

import android.annotation.SuppressLint
import android.content.Intent
import android.database.sqlite.SQLiteException
import android.graphics.Typeface
import android.os.*
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.gh.common.constant.Config
import com.gh.common.databind.BindingAdapters
import com.gh.common.iinterface.ISuperiorChain
import com.gh.common.prioritychain.AccelerateNotificationHandler
import com.gh.common.prioritychain.PriorityChain
import com.gh.common.util.*
import com.gh.common.util.LogUtils
import com.gh.common.util.NewFlatLogUtils
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.CollectionActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.ShareGhActivity
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.fragment.BaseLazyFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBNetworkState
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.common.view.ScrollEventListener
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentHaloPersonalBinding
import com.gh.gamecenter.databinding.FragmentPersonalStubBinding
import com.gh.gamecenter.entity.BadgeEntity
import com.gh.gamecenter.feature.entity.Badge
import com.gh.gamecenter.feature.eventbus.EBConcernChanged
import com.gh.gamecenter.gamecollection.mine.MyGameCollectionActivity
import com.gh.gamecenter.history.HistoryActivity
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.gh.gamecenter.login.utils.LoginHelper
import com.gh.gamecenter.message.MessageUnreadRepository
import com.gh.gamecenter.message.MessageUnreadViewModel
import com.gh.gamecenter.mygame.MyGameActivity
import com.gh.gamecenter.mypost.MyPostActivity
import com.gh.gamecenter.personalhome.UserHomeViewModel
import com.gh.gamecenter.room.AppDatabase
import com.gh.gamecenter.setting.SettingBridge
import com.gh.gamecenter.wrapper.MainWrapperFragment
import com.gh.gamecenter.wrapper.MainWrapperViewModel
import com.gh.vspace.ITestCase
import com.google.android.material.appbar.AppBarLayout
import com.halo.assistant.HaloApp
import com.jakewharton.rxbinding2.view.RxView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import splitties.views.dsl.core.endMargin
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class HaloPersonalFragment : BaseLazyFragment() {
    private var mUserInfoEntity: UserInfoEntity? = null

    private lateinit var mDatabase: AppDatabase

    private lateinit var mBinding: FragmentPersonalStubBinding
    private lateinit var mStubBinding: FragmentHaloPersonalBinding
    private lateinit var mUserViewModel: UserViewModel
    private lateinit var mUnreadViewModel: MessageUnreadViewModel
    private lateinit var mUserHomeViewModel: UserHomeViewModel
    private lateinit var mHaloPersonalViewModel: HaloPersonalViewModel
    private lateinit var mMainWrapperViewModel: MainWrapperViewModel

    private lateinit var mPersonalRecommendAdapter: HaloPersonalRecommendAdapter
    private lateinit var mPersonalBannerAdapter: HaloPersonalBannerAdapter
    private lateinit var mPersonalFunctionAdapter: HaloPersonalFunctionAdapter

    private lateinit var mSnapHelper: PagerSnapHelper
    private lateinit var mBannerLayoutManager: LinearLayoutManager
    private val mLooperHandle = LooperHandle(this)
    private val mSlideLooperKey = 101

    private var mIsUpdate = false
    private var mIsLogging = false

    private val mPriorityChain by lazy { PriorityChain() }
    private var mSuperiorChain: ISuperiorChain? = null

    override fun getInflatedLayout(): View {
        mBinding = FragmentPersonalStubBinding.inflate(layoutInflater, null, false)
        mBinding.stub.setOnInflateListener { _, inflateId ->
            mStubBinding = FragmentHaloPersonalBinding.bind(inflateId)
        }
        return mBinding.root
    }

    override fun getLayoutId() = R.layout.fragment_personal_stub

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            com.tencent.connect.common.Constants.REQUEST_LOGIN -> {
                LoginHelper.onQQLoginCallback(requestCode, resultCode, data)
            }

            32973 -> {
                LoginHelper.onWeiboLoginCallback(requireActivity(), requestCode, resultCode, data)
            }

            REQUEST_MESSAGE -> {
                mUnreadViewModel.retry()
            }
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v) {
            mStubBinding.motionLayout -> {
                if (mUserInfoEntity == null) {
                    NewFlatLogUtils.logHaloSelfLogin()
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "立即登录")
                    SensorsBridge.trackHaloSelfClick("用户信息", "立即登录", "", "", "")
                    CheckLoginUtils.checkLogin(context, "我的光环-立即登录", null)
                } else {
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "个人主页")
                    SensorsBridge.trackHaloSelfClick("用户信息", "个人主页", "", "", "")
                    DirectUtils.directToHomeActivity(
                        requireContext(),
                        UserManager.getInstance().userId,
                        "",
                        "我的光环"
                    )
                }
            }

            mStubBinding.toolbarContainer -> {
                if (mUserInfoEntity == null) {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(context, "我的光环-立即登录", null)
                }
            }

            mStubBinding.darkModeIv -> {
                if (!ClickUtils.isFastDoubleClick(v.id, 1000)) {
                    NewFlatLogUtils.logHaloSelfClick("右上角", "切换模式")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "右上角",
                        text = "切换模式",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    if (DarkModeUtils.isFollowSystemDarkModeFromSp()) {
                        DialogHelper.showDialog(
                            context = requireContext(),
                            title = getString(com.gh.gamecenter.core.R.string.hint),
                            content = getString(R.string.switch_theme_mode_dialog_content),
                            confirmText = getString(com.gh.gamecenter.common.R.string.confirm),
                            cancelText = getString(com.gh.gamecenter.common.R.string.cancel),
                            confirmClickCallback = {
                                NewFlatLogUtils.logHaloSelfNightModeOsDialog("确定")
                                DarkModeUtils.updateAppDarkModeStatusToSp(!mIsDarkModeOn)
                                DarkModeUtils.updateFollowSystemDarkModeToSp(false)
                                DarkModeUtils.initDarkMode()
                            }, cancelClickCallback = {
                                NewFlatLogUtils.logHaloSelfNightModeOsDialog("关闭弹窗")
                            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )?.setOnCancelListener {
                            NewFlatLogUtils.logHaloSelfNightModeOsDialog("关闭弹窗")
                        }
                    } else {
                        NewFlatLogUtils.logHaloSelfNightModeClick(if (mIsDarkModeOn) "日间模式" else "深色模式")
                        com.gh.gamecenter.common.utils.NewFlatLogUtils.logNightModeSwitch(false, !mIsDarkModeOn)
                        DarkModeUtils.updateAppDarkModeStatusToSp(!mIsDarkModeOn)
                        DarkModeUtils.initDarkMode()
                    }
                }
            }

            mStubBinding.personalMsg -> {
                // 优先进入有数字提醒的消息tab，其次是有红点提醒的游戏动态，最后是没有提醒的消息tab
                val defaultTabIndex = if ((mUnreadViewModel.messageUnreadCountLiveData.value?.message
                        ?: 0) < 1 && mUnreadViewModel.zixunConcernLiveData.value == true
                ) 0 else 1

                if (CheckLoginUtils.isLogin()) {
                    NewFlatLogUtils.logHaloSelfClick("右上角", "消息中心")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "右上角",
                        text = "消息中心",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    NewLogUtils.logMessageInformBellClick(
                        mStubBinding.loginMessageHint.visibility == View.VISIBLE,
                        "我的"
                    )
                    SensorsBridge.trackMessageCenterClick()
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                }

                DirectUtils.directToMessageCenter(defaultTabIndex, "我的光环-消息")
            }

            mStubBinding.personalUserIcon,
            mStubBinding.personalUserName -> {
                if (mUserInfoEntity != null) {
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "个人主页")
                    SensorsBridge.trackHaloSelfClick("用户信息", "个人主页", "", "", "")
                    DirectUtils.directToHomeActivity(
                        requireContext(),
                        UserManager.getInstance().userId,
                        "",
                        "我的光环"
                    )
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "立即登录")
                    SensorsBridge.trackHaloSelfClick("用户信息", "立即登录", "", "", "")
                    CheckLoginUtils.checkLogin(context, "我的光环-立即登录", null)
                }
            }

            mStubBinding.tvMyAssets -> {
                if (mUserInfoEntity != null) {
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "个人主页")
                    SensorsBridge.trackHaloSelfClick("用户信息", "个人主页", "", "", "")
                    SensorsBridge.trackMyAssetsPageShow("无", "无", "无", "我的光环")
                    DirectUtils.navigateToMyAssetsPage(requireContext(), "我的光环-个人主页")
                } else {
                    NewFlatLogUtils.logHaloSelfClick("用户信息", "立即登录")
                    SensorsBridge.trackHaloSelfClick("用户信息", "立即登录", "", "", "")
                    CheckLoginUtils.checkLogin(context, "我的光环-个人主页", null)
                }
            }

            mStubBinding.personalBadge -> {
                NewFlatLogUtils.logHaloSelfClick("用户信息", "我的徽章")
                SensorsBridge.trackHaloSelfClick("用户信息", "我的徽章", "", "", "")
                DirectUtils.directToBadgeWall(
                    requireContext(),
                    mUserInfoEntity?.userId,
                    mUserInfoEntity?.name,
                    mUserInfoEntity?.icon
                )
            }

            mStubBinding.myGameTv -> {
                if (UserManager.getInstance().isLoggedIn) {
                    NewFlatLogUtils.logHaloSelfClick("常用功能", "我的游戏")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "常用功能",
                        text = "我的游戏",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    startActivity(Intent(requireContext(), MyGameActivity::class.java))
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(requireContext(), "我的光环-我的游戏") {}
                }
            }

            mStubBinding.myPostTv -> {
                if (UserManager.getInstance().isLoggedIn) {
                    NewFlatLogUtils.logHaloSelfClick("常用功能", "我的发布")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "常用功能",
                        text = "我的发布",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    startActivity(MyPostActivity.getIntent(requireContext(), "我的光环-我的发布"))
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(requireContext(), "我的光环-我的发布") { }
                }
            }

            mStubBinding.myGameCollectionTv -> {
                if (UserManager.getInstance().isLoggedIn) {
                    NewFlatLogUtils.logHaloSelfClick("常用功能", "我的游戏单")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "常用功能",
                        text = "我的游戏单",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    startActivity(MyGameCollectionActivity.getIntent(requireContext()))
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(requireContext(), "我的光环-我的游戏单") { }
                }
            }

            mStubBinding.historyTv -> {
                NewFlatLogUtils.logHaloSelfClick("常用功能", "浏览记录")
                SensorsBridge.trackHaloSelfClick(
                    profile = "常用功能",
                    text = "浏览记录",
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(HistoryActivity.getHistoryIntent(requireContext(), "我的光环-浏览记录"))
            }

            mStubBinding.myCollectionTv -> {
                if (UserManager.getInstance().isLoggedIn) {
                    NewFlatLogUtils.logHaloSelfClick("常用功能", "我的收藏")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "常用功能",
                        text = "我的收藏",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    if ((MessageUnreadRepository.addonsUnread.value?.favorite ?: 0) > 0) {
                        MessageUnreadRepository.refreshUnreadCount(MessageUnreadRepository.UnreadMessageType.FAVORITE)
                    }
                    startActivity(CollectionActivity.getCollectionActivity(requireContext(), "(我的光环)"))
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(requireContext(), "我的光环-我的收藏") {}
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mDatabase = AppDatabase.getInstance()
        mUserViewModel = viewModelProvider(UserViewModel.Factory(requireActivity().application))
        mUserHomeViewModel = viewModelProvider(
            UserHomeViewModel.Factory(
                HaloApp.getInstance().application,
                UserManager.getInstance().userId
            )
        )
        mUnreadViewModel = viewModelProvider(MessageUnreadViewModel.Factory(HaloApp.getInstance().application))
        mHaloPersonalViewModel = viewModelProvider()
        mMainWrapperViewModel = viewModelProviderFromParent(MainWrapperViewModel.Factory(HaloApp.getInstance()))
        mUserHomeViewModel.getUserInfo()

        observeNoneUIRelatedChanges()
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        inflateRealView()
        observeUIRelatedChanges()
        buildPriorityChain()
    }

    override fun onFragmentResume() {
        super.onFragmentResume()

        if (NetworkUtils.isNetworkConnected(requireContext())) {
            mUnreadViewModel.retry()
            mUserHomeViewModel.getBadgeList()
            mUserHomeViewModel.availableBadges()
            mMainWrapperViewModel.requestAccelerateNotificationPopup()
        }
        val currentTab = (parentFragment as? MainWrapperFragment)?.currentTab
        if (currentTab?.link?.type == ViewPagerFragmentHelper.TYPE_MY_HALO) {
            DisplayUtils.transparentStatusBar(requireActivity())
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
        }

        mSuperiorChain?.registerInferiorChain(mPriorityChain)
        startBannerAutoPlay()
    }

    override fun onFragmentPause() {
        super.onFragmentPause()

        mSuperiorChain?.unregisterInferiorChain(mPriorityChain)
        stopBannerAutoPlay()
    }

    @SuppressLint("CheckResult", "SetTextI18n")
    private fun observeUIRelatedChanges() {
        mHaloPersonalViewModel.appEntity.observe(this) {
            mIsUpdate = it.versionCode > PackageUtils.getGhVersionCode()
            mStubBinding.settingItem.newVersionTv.goneIf(!mIsUpdate)
        }
        mHaloPersonalViewModel.recommendData.observeNonNull(this) {
            if (it.size > 1) {
                mStubBinding.recommendRv.visibility = View.VISIBLE
                mPersonalRecommendAdapter.setRecommendList(it.take(if (it.size < MAX_RECOMMEND_COUNT) 2 else MAX_RECOMMEND_COUNT))
            } else {
                mStubBinding.recommendRv.visibility = View.GONE
            }
        }
        mHaloPersonalViewModel.activityData.observeNonNull(this) {
            if (it.isNotEmpty()) {
                mStubBinding.bannerContainer.visibility = View.VISIBLE
                mPersonalBannerAdapter.submitList(it)
                if (mPersonalBannerAdapter.getActualSize() > 1) {
                    mStubBinding.bannerRv.scrollToPosition(mPersonalBannerAdapter.getActualFirstPositionInCenter())
                }
                mStubBinding.bannerIndicator.run {
                    pageSize = mPersonalBannerAdapter.getActualSize()
                    notifyDataChanged()
                }
                startBannerAutoPlay()
            } else {
                mStubBinding.bannerContainer.visibility = View.GONE
            }
        }
        mHaloPersonalViewModel.moreFeaturesData.observeNonNull(this) {
            if (it.isNotEmpty()) {
                mStubBinding.functionContainer.visibility = View.VISIBLE
                mPersonalFunctionAdapter.setFunctionList(it.take(MAX_MORE_FEATURES_COUNT))
            } else {
                mStubBinding.functionContainer.visibility = View.GONE
            }
        }

        mUserViewModel.loginObsUserinfo.observe(
            this
        ) { userInfoEntity: ApiResponse<UserInfoEntity?>? ->
            if (userInfoEntity != null && userInfoEntity.data != null) {
                changeLoginState(true)
            } else {
                changeLoginState(false)
            }
        }

        mUserHomeViewModel.badges.observe(
            this
        ) { badgeEntities: List<BadgeEntity> ->
            mStubBinding.personalBadgeIcon.setImageURI("")
            if (badgeEntities.isEmpty()) {
                mStubBinding.personalBadgeCountTv.text = getString(R.string.my_badge)
            } else {
                mStubBinding.personalBadgeCountTv.text = getString(R.string.badge_count, badgeEntities.size)
                for ((_, _, icon, name, _, wear, _, actions) in badgeEntities) {
                    if (wear) {
                        ImageUtils.display(
                            mStubBinding.personalBadgeIcon,
                            icon
                        )
                        mStubBinding.personalBadgeIcon.setOnClickListener {
                            DialogUtils.showViewBadgeDialog(requireContext(), Badge(name, icon, "", actions)) {
                                DirectUtils.directToBadgeWall(
                                    requireContext(),
                                    mUserInfoEntity?.userId,
                                    mUserInfoEntity?.name,
                                    mUserInfoEntity?.icon
                                )
                            }
                        }
                        break
                    }
                }
            }
        }
        mUserHomeViewModel.availableBadgeCount.observe(this) { count: Int ->
            mStubBinding.personalBadgeTips.visibility =
                if (count > 0) View.VISIBLE else View.GONE
        }

        mUserHomeViewModel.availableBadge.observe(this) { badge: BadgeEntity? ->
            val badgeSevenDayMap = SPUtils.getMap(SP_BADGE_RECORD_SEVEN_DAY_MAP)
            // 徽章领取弹窗每隔7天弹出一次，所以要判断现在是否是上一次弹出的第7天或者之后
            if (badge != null && System.currentTimeMillis() >= (badgeSevenDayMap[badge.id]?.toLong() ?: 0)) {
                // 徽章领取弹窗每隔7天弹出一次，所以本次弹出后就记录7天后的时间戳
                badgeSevenDayMap[badge.id] =
                    TimeUtils.getStartTimeOfDay(System.currentTimeMillis() + 86400000 * 6).toString()
                SPUtils.setMap(SP_BADGE_RECORD_SEVEN_DAY_MAP, badgeSevenDayMap)
                DialogUtils.showReceiveBadgeDialog(requireContext(), badge) {
                    if ("auto" == badge.receive?.type) {
                        DirectUtils.directToBadgeDetail(
                            requireContext(),
                            mUserInfoEntity?.userId,
                            badge.id
                        )
                        return@showReceiveBadgeDialog
                    }
                    mHaloPersonalViewModel.applyOrReceiveBadge(badge.id, {
                        if ("self" == badge.receive?.type) {
                            ToastUtils.showToast(getString(R.string.ling_sucessfully_toast))
                        } else {
                            ToastUtils.showToast(getString(R.string.apply_successfully_toast))
                        }
                        // 跳转到徽章详情
                        DirectUtils.directToBadgeDetail(
                            requireContext(),
                            mUserInfoEntity?.userId,
                            badge.id
                        )
                    }, {
                        if ("self" == badge.receive?.type) {
                            ToastUtils.showToast(getString(R.string.ling_failed_toast))
                        } else {
                            ToastUtils.showToast(getString(R.string.apply_failed_toast))
                        }
                    })
                }
            }
        }

        mUnreadViewModel.messageCenterUnreadCountLiveData.observe(this) {
            if (it != null) {
                mStubBinding.loginMessageHint.goneIf(it == 0)
                val params = mStubBinding.loginMessageHint.layoutParams
                if (it == -1) {
                    mStubBinding.loginMessageHint.text = ""
                    params.width = 6F.dip2px()
                    params.height = 6F.dip2px()
                    (params as ViewGroup.MarginLayoutParams).topMargin = 0
                    params.endMargin = (-4F).dip2px()
                    mStubBinding.loginMessageHint.setPadding(0, 0, 0, 0)
                    mStubBinding.loginMessageHint.minWidth = 0
                } else {
                    BindingAdapters.setMessageUnread(mStubBinding.loginMessageHint, it)
                    params.width = RelativeLayout.LayoutParams.WRAP_CONTENT
                    params.height = 14F.dip2px()
                    (params as ViewGroup.MarginLayoutParams).topMargin = (-4F).dip2px()
                    params.endMargin = (-8F).dip2px()
                    mStubBinding.loginMessageHint.setPadding(4F.dip2px(), 0, 4F.dip2px(), 0)
                    mStubBinding.loginMessageHint.minWidth = 14F.dip2px()
                }
                mStubBinding.loginMessageHint.layoutParams = params
            } else {
                mStubBinding.loginMessageHint.visibility = View.GONE
                EventBus.getDefault()
                    .post(EBReuse(MESSAGE_READ_OVER))
            }
        }

        // 微信/签到
        RxView.clicks(mStubBinding.personalSign)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (CheckLoginUtils.isLogin()) {
                    NewFlatLogUtils.logHaloSelfClick("右上角", "签到")
                    SensorsBridge.trackHaloSelfClick(
                        profile = "右上角",
                        text = "签到",
                        linkType = "",
                        linkId = "",
                        linkText = ""
                    )
                    sign()
                } else {
                    NewFlatLogUtils.logHaloSelfLogin()
                    CheckLoginUtils.checkLogin(context, "我的光环-签到") {}
                }
            }
    }

    private fun sign() {
        mHaloPersonalViewModel.sign { signEntity ->
            if (mHaloPersonalViewModel.isCanSign(signEntity.lastTime)) {
                DialogUtils.showSignDialog(
                    context,
                    getString(R.string.sign_title),
                    getString(R.string.sign_dialog_content, signEntity.serialSign),
                    getString(R.string.sign_dialog_content2, signEntity.experience),
                    getSignSkipText(signEntity.title)
                ) { mHaloPersonalViewModel.signSkip(requireContext(), signEntity) }
                signEntity.lastTime = System.currentTimeMillis() / 1000
            } else {
                DialogUtils.showSignDialog(
                    context,
                    getString(R.string.sign_dialog_content_3),
                    getString(R.string.sign_dialog_content, signEntity.serialSign),
                    getString(R.string.sign_dialog_content2, signEntity.experience),
                    getSignSkipText(signEntity.title)
                ) { mHaloPersonalViewModel.signSkip(requireContext(), signEntity) }
            }
            signEntity.id = UserManager.getInstance().userId
            if (mDatabase.signDao().updateSignEntity(signEntity) <= 0) {
                try {
                    mDatabase.signDao().addSignEntity(signEntity)
                } catch (e: SQLiteException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun buildPriorityChain() {
        val accelerateNotificationHandler = AccelerateNotificationHandler(21)

        mMainWrapperViewModel.accelerateNotificationPopup.observe(this) {
            if (mPriorityChain.isHandlerQueueEmpty()) {
                if (it == null) return@observe

                val accelerateSet =
                    HashSet(SPUtils.getStringSet(Constants.SP_ACCELERATE_NOTIFICATION_POP_UP_SET))
                if (it.isNotEmpty() && !accelerateSet.contains(it[0].messageId)) {
                    AccelerateNotificationHandler.showAccelerateNotificationPopupWindow(
                        requireActivity(),
                        mMainWrapperViewModel,
                        mBaseHandler as BaseHandler,
                        it[0],
                        null
                    )
                    accelerateSet.add(it[0].messageId)
                    SPUtils.setStringSet(Constants.SP_ACCELERATE_NOTIFICATION_POP_UP_SET, accelerateSet)
                }
            } else {
                accelerateNotificationHandler.doPreProcess(
                    requireActivity(),
                    mBaseHandler,
                    it,
                    mMainWrapperViewModel
                )
            }
        }

        mPriorityChain.addHandler(accelerateNotificationHandler)
    }

    private fun getSignSkipText(text: String): String =
        if (TextUtils.isEmpty(text)) getString(R.string.go_to_home) else text

    @SuppressLint("SetTextI18n")
    private fun changeLoginState(isLogin: Boolean) {
        if (isLogin) {
            if (mUserInfoEntity != null) {
                mStubBinding.personalUserIcon.display(
                    if (mUserInfoEntity?.iconBorder == null) "" else mUserInfoEntity?.iconBorder?.url,
                    mUserInfoEntity?.icon,
                    null
                )
                mStubBinding.motionLayout.run {
                    getConstraintSet(R.id.start).run {
                        setVisibility(R.id.personal_badge, View.VISIBLE)
                        clear(R.id.personal_user_name, ConstraintSet.BOTTOM)
                        clear(R.id.tv_my_assets, ConstraintSet.TOP)
                        clear(R.id.tv_my_assets, ConstraintSet.BOTTOM)
                        if (!mUserInfoEntity?.getShortUserId().isNullOrEmpty()) {
                            setMargin(R.id.personal_user_name, ConstraintSet.TOP, 14F.dip2px())
                            setMargin(R.id.personal_badge, ConstraintSet.BOTTOM, 14F.dip2px())
                            setMargin(R.id.userIdTv, ConstraintSet.TOP, 0)
                            connect(R.id.userIdTv, ConstraintSet.TOP, R.id.personal_user_name, ConstraintSet.BOTTOM)
                            connect(R.id.userIdTv, ConstraintSet.BOTTOM, R.id.personal_badge, ConstraintSet.TOP)
                            connect(R.id.tv_my_assets, ConstraintSet.BOTTOM, R.id.personal_badge, ConstraintSet.BOTTOM)
                            setVisibility(R.id.userIdTv, View.VISIBLE)
                        } else {
                            connect(
                                R.id.personal_user_name,
                                ConstraintSet.BOTTOM,
                                R.id.personal_badge,
                                ConstraintSet.TOP
                            )
                            connect(
                                R.id.personal_badge,
                                ConstraintSet.TOP,
                                R.id.personal_user_name,
                                ConstraintSet.BOTTOM
                            )
                            connect(R.id.tv_my_assets, ConstraintSet.BOTTOM, R.id.personal_badge, ConstraintSet.BOTTOM)
                            setVerticalChainStyle(R.id.personal_user_name, ConstraintSet.CHAIN_PACKED)
                            setVerticalChainStyle(R.id.personal_badge, ConstraintSet.CHAIN_PACKED)
                            setMargin(R.id.personal_badge, ConstraintSet.TOP, 6F.dip2px())
                            setVisibility(R.id.userIdTv, View.GONE)
                        }
                    }
                    getConstraintSet(R.id.end).run {
                        setVisibility(R.id.personal_badge, View.VISIBLE)
                    }
                }
                mStubBinding.userIdTv.textSize = 10F
                mStubBinding.personalUserName.text = mUserInfoEntity?.name
                mStubBinding.userIdTv.text = "ID:${mUserInfoEntity?.getShortUserId()}"
                mStubBinding.userIdTv.setOnLongClickListener {
                    mStubBinding.userIdTv.text.toString().substring(3).copyTextAndToast("用户ID复制成功")
                    return@setOnLongClickListener true
                }
            }
            mUserHomeViewModel.userId = UserManager.getInstance().userId
            mUserHomeViewModel.getBadgeList()
            mUserHomeViewModel.availableBadges()
            MessageUnreadRepository.loadMessageUnreadTotal(true)
        } else {
            mStubBinding.personalUserIcon.display("", "", "")
            mStubBinding.motionLayout.run {
                getConstraintSet(R.id.start).run {
                    setVisibility(R.id.userIdTv, View.VISIBLE)
                    setVisibility(R.id.personal_badge, View.GONE)
                    setVerticalChainStyle(R.id.personal_user_name, ConstraintSet.CHAIN_PACKED)
                    setVerticalChainStyle(R.id.userIdTv, ConstraintSet.CHAIN_PACKED)
                    connect(R.id.personal_user_name, ConstraintSet.TOP, R.id.personal_user_icon, ConstraintSet.TOP)
                    connect(R.id.personal_user_name, ConstraintSet.BOTTOM, R.id.userIdTv, ConstraintSet.TOP)
                    connect(R.id.userIdTv, ConstraintSet.TOP, R.id.personal_user_name, ConstraintSet.BOTTOM)
                    connect(R.id.userIdTv, ConstraintSet.BOTTOM, R.id.personal_user_icon, ConstraintSet.BOTTOM)
                    connect(R.id.tv_my_assets, ConstraintSet.BOTTOM, R.id.personal_user_icon, ConstraintSet.BOTTOM)
                    connect(R.id.tv_my_assets, ConstraintSet.TOP, R.id.personal_user_icon, ConstraintSet.TOP)
                    setMargin(R.id.personal_user_name, ConstraintSet.TOP, 0)
                    setMargin(R.id.userIdTv, ConstraintSet.TOP, 3F.dip2px())
                }
                getConstraintSet(R.id.end).run {
                    setVisibility(R.id.personal_badge, View.GONE)
                }
            }

            mStubBinding.userIdTv.textSize = 11F
            mStubBinding.personalUserName.text = getString(R.string.login_immediately)
            mStubBinding.userIdTv.text = getString(R.string.login_immediately_hint)

            if (mStubBinding.loginMessageHint.visibility == View.VISIBLE) {
                mStubBinding.loginMessageHint.visibility = View.GONE
                EventBus.getDefault().post(EBReuse(MESSAGE_READ_OVER))
            }
        }
    }

    private fun inflateRealView() {
        mBinding.stub.inflateOrShow()

        mStubBinding.statusBar.goneIf(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        mStubBinding.darkModeIv.goneIf(!(Config.getNightModeSetting()?.icon ?: false))
        mStubBinding.darkModeIv.setImageResource(if (mIsDarkModeOn) R.drawable.ic_personal_light_mode else R.drawable.ic_personal_dark_mode)
        mStubBinding.loginMessageHint.typeface =
            Typeface.createFromAsset(requireContext().assets, Constants.DIN_FONT_PATH)

        mStubBinding.motionLayout.setOnClickListener(this)
        mStubBinding.toolbarContainer.setOnClickListener(this)
        mStubBinding.darkModeIv.setOnClickListener(this)
        mStubBinding.personalMsg.setOnClickListener(this)
        mStubBinding.tvMyAssets.setOnClickListener(this)
        mStubBinding.personalUserName.setOnClickListener(this)
        mStubBinding.personalUserIcon.setOnClickListener(this)
        mStubBinding.personalBadge.setOnClickListener(this)
        mStubBinding.myGameTv.setOnClickListener(this)
        mStubBinding.myPostTv.setOnClickListener(this)
        mStubBinding.myGameCollectionTv.setOnClickListener(this)
        mStubBinding.historyTv.setOnClickListener(this)
        mStubBinding.myCollectionTv.setOnClickListener(this)

        val statusBarHeight =
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) 0 else DisplayUtils.getStatusBarHeight(resources)
        mStubBinding.motionLayout.minimumHeight = statusBarHeight + 48F.dip2px()

        mStubBinding.appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _: AppBarLayout?, verticalOffset: Int ->
            mStubBinding.listRefresh.isEnabled = abs(verticalOffset) <= 2
        })

        mStubBinding.listRefresh.setColorSchemeColors(
            ContextCompat.getColor(
                requireContext(),
                com.gh.gamecenter.common.R.color.primary_theme
            )
        )
        mStubBinding.listRefresh.setProgressViewOffset(
            false,
            0,
            DisplayUtils.dip2px(80F) + DisplayUtils.getStatusBarHeight(requireContext().resources)
        )
        mStubBinding.listRefresh.setOnRefreshListener {
            mHaloPersonalViewModel.getHaloAddons(true)
            if (CheckLoginUtils.isLogin()) {
                mUnreadViewModel.retry()
                MessageUnreadRepository.loadMessageUnreadTotal(false)
                mUserHomeViewModel.getBadgeList()
                mUserHomeViewModel.availableBadges()
            }
            mBaseHandler.postDelayed({ mStubBinding.listRefresh.isRefreshing = false }, 2000)
        }
        MessageUnreadRepository.loadMessageUnreadTotal(true)

        initRecommendRv()
        initActivityBanner()
        initMoreFeaturesRv()
        initSettingItems()
    }

    private fun initSettingItems() {
        // 测试环境添加一个安装外部存储游戏的按钮
        if (PackageFlavorHelper.IS_TEST_FLAVOR) {
            (try {
                Class.forName("com.gh.vspace.ExternalGameUsage")?.newInstance()
            } catch (e: Exception) {
            } as? ITestCase)?.apply {
                addInstallExternalGameButton(mStubBinding.otherItems)
            }
        }

        mStubBinding.settingItem.run {
            titleTv.text = getString(R.string.title_settings)
            iconIv.setImageResource(R.drawable.ic_personal_setting)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", "设置")
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = "设置",
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(SettingBridge.getSettingIntent(requireContext(), mIsUpdate, "我的光环"))
            }
        }
        mStubBinding.feedbackItem.run {
            titleTv.text = getString(R.string.help_and_feedback)
            iconIv.setImageResource(R.drawable.ic_personal_feedback)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", "帮助与反馈")
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = "帮助与反馈",
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                DirectUtils.directToHelpAndFeedback(
                    requireContext(),
                    bundleOf(EntranceConsts.KEY_ENTRANCE to "我的光环")
                )
            }
            // 港澳台APP不显示帮助与反馈
            root.goneIf(EnvHelper.isGATApp)
        }
        mStubBinding.shareGhItem.run {
            titleTv.text = getString(R.string.share_halo)
            iconIv.setImageResource(R.drawable.ic_personal_share)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", "分享光环")
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = "分享光环",
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(ShareGhActivity.getIntent(requireContext()))
            }
            // 港澳台APP不显示分享光环
            root.goneIf(EnvHelper.isGATApp)
        }
        mStubBinding.userProtocolItem.run {
            titleTv.text = getString(R.string.setting_user_protocol)
            iconIv.setImageResource(R.drawable.ic_personal_user_protocol)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_user_protocol))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_user_protocol),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        requireContext().getString(com.gh.gamecenter.common.R.string.disclaimer_title),
                        requireContext().getString(com.gh.gamecenter.common.R.string.disclaimer_url)
                    )
                )
            }
        }
        mStubBinding.privacyPolicyItem.run {
            titleTv.text = getString(R.string.setting_privacy_policy)
            iconIv.setImageResource(R.drawable.ic_personal_privacy_policy)
            //判断隐私政策是否有更新
            mStubBinding.privacyPolicyItem.redDot.visibility = if (checkPrivacyIsSame()) View.GONE else View.VISIBLE
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_privacy_policy))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_privacy_policy),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                SPUtils.setString(
                    Constants.SP_PRIVACY_MD5,
                    SPUtils.getString(Constants.SP_PRIVACY_CURRENT_MD5)
                )
                redDot.visibility = if (checkPrivacyIsSame()) View.GONE else View.VISIBLE
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        requireContext().getString(com.gh.gamecenter.common.R.string.privacy_policy_title),
                        requireContext().getString(com.gh.gamecenter.common.R.string.privacy_policy_url)
                    )
                )
            }
        }
        mStubBinding.infoListItem.run {
            titleTv.text = getString(R.string.setting_info_list)
            iconIv.setImageResource(R.drawable.ic_personal_info_list)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_info_list))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_info_list),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        getString(R.string.setting_info_list),
                        requireContext().getString(R.string.info_list_url)
                    )
                )
            }
        }
        mStubBinding.sdkListItem.run {
            titleTv.text = getString(R.string.setting_sdk_list)
            iconIv.setImageResource(R.drawable.ic_personal_sdk)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_sdk_list))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_sdk_list),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        getString(R.string.setting_sdk_list),
                        requireContext().getString(R.string.sdk_list_url)
                    )
                )
            }
        }
        mStubBinding.permissionAndUsageItem.run {
            titleTv.text = getString(R.string.setting_permission_and_usage)
            iconIv.setImageResource(R.drawable.ic_personal_permission)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_permission_and_usage))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_permission_and_usage),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        getString(R.string.setting_permission_and_usage),
                        requireContext().getString(R.string.permission_and_usage_url)
                    )
                )
            }
        }
        mStubBinding.childrenPolicyItem.run {
            titleTv.text = getString(R.string.setting_children_policy)
            iconIv.setImageResource(R.drawable.ic_personal_children_policy)
            root.setOnClickListener {
                NewFlatLogUtils.logHaloSelfClick("其他功能", getString(R.string.setting_children_policy))
                SensorsBridge.trackHaloSelfClick(
                    profile = "其他功能",
                    text = getString(R.string.setting_children_policy),
                    linkType = "",
                    linkId = "",
                    linkText = ""
                )
                startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        getString(R.string.setting_children_policy),
                        requireContext().getString(R.string.children_policy_url)
                    )
                )
            }
        }
    }

    private fun initRecommendRv() {
        mPersonalRecommendAdapter = HaloPersonalRecommendAdapter(requireContext())
        mStubBinding.recommendRv.layoutManager = GridLayoutManager(requireContext(), 2)
        mStubBinding.recommendRv.adapter = mPersonalRecommendAdapter
    }

    private fun initActivityBanner() {
        mStubBinding.bannerRv.run {
            mPersonalBannerAdapter = HaloPersonalBannerAdapter(requireContext())
            mSnapHelper = PagerSnapHelper()
            mBannerLayoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            adapter = mPersonalBannerAdapter
            layoutManager = mBannerLayoutManager
            mSnapHelper.attachToRecyclerView(this)
            isNestedScrollingEnabled = false
            addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
                override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                    when (e.action) {
                        MotionEvent.ACTION_DOWN -> {
                            mStubBinding.listRefresh.isEnabled = false
                        }

                        MotionEvent.ACTION_UP -> {
                            mStubBinding.listRefresh.isEnabled = true
                        }
                    }

                    val isStop = e.action == MotionEvent.ACTION_DOWN || e.action == MotionEvent.ACTION_MOVE
                    if (isStop) stopBannerAutoPlay() else startBannerAutoPlay()
                    return false
                }
            })
            addOnScrollListener(ScrollEventListener(this).apply {
                registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                        super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                        mStubBinding.bannerIndicator.onPageScrolled(
                            mPersonalBannerAdapter.getActualPosition(position),
                            positionOffset
                        )
                    }
                })
            })
        }
    }

    private fun scrollToNextPage() {
        val snapView = mSnapHelper.findSnapView(mBannerLayoutManager)
        if (snapView != null) {
            mBannerLayoutManager.smoothScrollToPosition(
                mStubBinding.bannerRv,
                null,
                mBannerLayoutManager.getPosition(snapView) + 1
            )
        }
    }

    private fun startBannerAutoPlay() {
        if (!::mPersonalBannerAdapter.isInitialized || mPersonalBannerAdapter.getActualSize() < 2) return
        stopBannerAutoPlay()
        mLooperHandle.sendEmptyMessageDelayed(mSlideLooperKey, BANNER_LOOP_TIME)
    }

    private fun stopBannerAutoPlay() {
        mLooperHandle.removeMessages(mSlideLooperKey)
    }

    private fun initMoreFeaturesRv() {
        mPersonalFunctionAdapter = HaloPersonalFunctionAdapter(requireContext())
        mStubBinding.funcRv.layoutManager = GridLayoutManager(requireContext(), 4)
        mStubBinding.funcRv.adapter = mPersonalFunctionAdapter
        mStubBinding.funcRv.isNestedScrollingEnabled = false
        mStubBinding.funcRv.addItemDecoration(
            GridSpacingItemColorDecoration(
                requireContext(),
                0,
                18,
                com.gh.gamecenter.common.R.color.transparent
            )
        )
    }

    private fun checkPrivacyIsSame(): Boolean {
        val currentMd5 = SPUtils.getString(Constants.SP_PRIVACY_CURRENT_MD5)
        val privacyMd5 = SPUtils.getString(Constants.SP_PRIVACY_MD5)
        return currentMd5 == privacyMd5
    }

    private fun observeNoneUIRelatedChanges() {
        mHaloPersonalViewModel.getHaloAddons(false)
        mUserViewModel.loginObsUserinfo.observe(this) { userInfoEntity: ApiResponse<UserInfoEntity>? ->
            val notifyUserInfo: UserInfoEntity? = userInfoEntity?.data
            if (notifyUserInfo != null && mUserInfoEntity == null) { // 单个用户，首次触发
                EventBus.getDefault().post(EBConcernChanged())
                val loginTokenEntity =
                    UserManager.getInstance().loginTokenEntity
                if (mIsLogging && loginTokenEntity != null) {
                    val loginType = loginTokenEntity.loginType
                    LogUtils.login(
                        "success",
                        loginType,
                        mHaloPersonalViewModel.getLoginEntranceByType(loginType)
                    )
                    mIsLogging = false
                }
            }
            mUserInfoEntity = notifyUserInfo
            if (notifyUserInfo == null) {
                mUnreadViewModel.clean()
                EventBus.getDefault().post(EBConcernChanged())
            }
        }
        mHaloPersonalViewModel.haloAddData.observeNonNull(this) {
            if (it.isNotEmpty()) {
                MessageUnreadRepository.loadMessageUnreadTotal(false)
            }
        }
        mUserHomeViewModel.userInfo.observeNonNull(this) {
            if (it.source != null) {
                SensorsBridge.profileSet("city", it.source?.region ?: "")
            }
        }
    }

    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busNetworkState: EBNetworkState) {
        if (busNetworkState.isNetworkConnected
            && UserManager.getInstance().isLoggedIn
            && (mUserViewModel.loginObsUserinfo.value == null)
        ) {
            mUserViewModel.retryCheckLogin()
        }
        if (busNetworkState.isNetworkConnected) {
            mHaloPersonalViewModel.getHaloAddons(false)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if (MESSAGE_READ_OVER == reuse.type) { // 消息阅读完成
            mStubBinding.loginMessageHint.visibility = View.GONE
        }
    }

    fun setSuperiorChain(superiorChain: ISuperiorChain?): HaloPersonalFragment {
        this.mSuperiorChain = superiorChain
        return this
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (isSupportVisible) DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn)
        if (isAdded) {
            if (::mPersonalFunctionAdapter.isInitialized) mPersonalFunctionAdapter.notifyItemRangeChanged(
                0,
                mPersonalFunctionAdapter.itemCount
            )
            if (::mStubBinding.isInitialized) {
                mStubBinding.run {
                    settingItem.iconIv.setImageResource(R.drawable.ic_personal_setting)
                    feedbackItem.iconIv.setImageResource(R.drawable.ic_personal_feedback)
                    shareGhItem.iconIv.setImageResource(R.drawable.ic_personal_share)
                    userProtocolItem.iconIv.setImageResource(R.drawable.ic_personal_user_protocol)
                    privacyPolicyItem.iconIv.setImageResource(R.drawable.ic_personal_privacy_policy)
                    infoListItem.iconIv.setImageResource(R.drawable.ic_personal_info_list)
                    sdkListItem.iconIv.setImageResource(R.drawable.ic_personal_sdk)
                    permissionAndUsageItem.iconIv.setImageResource(R.drawable.ic_personal_permission)
                    childrenPolicyItem.iconIv.setImageResource(R.drawable.ic_personal_children_policy)
                    whiteBg.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
                    gradientBg.background = R.drawable.bg_personal_top_gradient.toDrawable(requireContext())
                    personalUserName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    userIdTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(requireContext()))
                    darkModeIv.setImageResource(if (mIsDarkModeOn) R.drawable.ic_personal_light_mode else R.drawable.ic_personal_dark_mode)
                    myGameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    myGameCollectionTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    myCollectionTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    historyTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    myPostTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                    myGameTv.setDrawableTop(
                        AppCompatResources.getDrawable(
                            requireContext(),
                            R.drawable.ic_personal_my_game
                        )
                    )
                    myGameCollectionTv.setDrawableTop(
                        AppCompatResources.getDrawable(
                            requireContext(),
                            R.drawable.ic_personal_my_game_collection
                        )
                    )
                    myCollectionTv.setDrawableTop(
                        AppCompatResources.getDrawable(
                            requireContext(),
                            R.drawable.ic_personal_my_collection
                        )
                    )
                    historyTv.setDrawableTop(
                        AppCompatResources.getDrawable(
                            requireContext(),
                            R.drawable.ic_personal_history
                        )
                    )
                    myPostTv.setDrawableTop(
                        AppCompatResources.getDrawable(
                            requireContext(),
                            R.drawable.ic_personal_my_post
                        )
                    )
                    tvMyAssets.background =
                        com.gh.gamecenter.common.R.drawable.bg_common_button_stroke_gray.toDrawable(requireContext())
                    tvMyAssets.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext()))
                }
            }
        }
    }

    companion object {
        private const val MESSAGE_READ_OVER = "MESSAGE_READ_OVER"
        private const val SP_BADGE_RECORD_SEVEN_DAY_MAP = "badgeRecordSevenDayMap"
        private const val REQUEST_MESSAGE = 199
        private const val MAX_RECOMMEND_COUNT = 4
        private const val MAX_MORE_FEATURES_COUNT = 12
        private const val BANNER_LOOP_TIME = 3000L
    }

    class LooperHandle(fragment: HaloPersonalFragment) : Handler(Looper.getMainLooper()) {
        private val mWeakReference: WeakReference<HaloPersonalFragment> = WeakReference(fragment)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val fragment = mWeakReference.get()
            if (fragment != null && msg.what == fragment.mSlideLooperKey) {
                fragment.scrollToNextPage()
                fragment.startBannerAutoPlay()
            }
        }
    }
}