package com.gh.gamecenter.message.view

import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.PagerAdapter
import com.therouter.router.Route
import com.gh.gamecenter.common.base.activity.BaseActivity_TabLayout
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.feature.entity.MessageUnreadCount
import com.gh.gamecenter.message.R
import com.gh.gamecenter.message.databinding.ActivityMessageWrapperBinding
import com.gh.gamecenter.message.databinding.MessageTabItemBinding
import com.gh.gamecenter.message.view.concern.ConcernFragment
import com.gh.gamecenter.message.view.message.SortedMessageListFragment
import com.gh.gamecenter.message.view.message.SortedMessageListViewModel
import com.google.android.material.tabs.TabLayout

/**
 * 消息中心
 */
@Route(path = RouteConsts.activity.messageWrapperActivity)
class MessageWrapperActivity : BaseActivity_TabLayout() {
    private lateinit var mBinding: ActivityMessageWrapperBinding
    private lateinit var mViewModel: SortedMessageListViewModel

    private var mUnreadCount: MessageUnreadCount? = null
    private var mConcernUnread: Boolean = false // 游戏动态是否存在未读消息

    private var mConcernFragment: ConcernFragment? = null
    private var mSortedMessageListFragment: SortedMessageListFragment? = null

    override fun getLayoutId(): Int = R.layout.activity_message_wrapper

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        fragments.add(ConcernFragment().apply { mConcernFragment = this }
            .with(bundleOf(Pair(EntranceConsts.KEY_ENTRANCE, "消息中心-动态tab"))))
        fragments.add(SortedMessageListFragment().apply { mSortedMessageListFragment = this }
            .with(bundleOf(Pair(EntranceConsts.KEY_ENTRANCE, "消息中心-消息tab"))))
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add(TAB_CONCERN)
        tabTitleList.add(TAB_MESSAGE)
    }

    override fun provideAdapter(): PagerAdapter {
        return object : FragmentStatePagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            override fun getItem(position: Int) = mFragmentsList[position]

            override fun getCount() = mFragmentsList.size

            override fun getPageTitle(position: Int): CharSequence? {
                return mTabTitleList.safelyGetInRelease(position)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        mViewModel = viewModelProviderFromParent()
        mBinding = ActivityMessageWrapperBinding.bind(mContentView)

        mViewModel.getUnreadCountLiveData()?.observeNonNull(this) {
            mUnreadCount = it
            updateTabHint()
        }

        mViewModel.getZixunConcernLiveData()?.observeNonNull(this) {
            mConcernUnread = it
            updateTabHint()
        }

        ifLogin("") {}
    }

    private fun updateTabHint() {
        for (i in 0 until mTabLayout.tabCount) {
            val tab = mTabLayout.getTabAt(i)
            if (tab != null) {
                updateTabStyle(tab, tab.isSelected)
            }
        }
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        return when (mViewPager.currentItem) {
            TAB_CONCERN_INDEX -> {
                mConcernFragment?.onMenuItemClick(item)
                true
            }

            TAB_MESSAGE_INDEX -> {
                mSortedMessageListFragment?.onMenuItemClick(item)
                true
            }

            else -> false
        }
    }

    override fun provideTabView(position: Int, tabTitle: String?): View {
        val tabBinding = MessageTabItemBinding.inflate(LayoutInflater.from(this))
        tabBinding.run {
            hintTv.typeface = Typeface.createFromAsset(assets, Constants.DIN_FONT_PATH)
            titleTv.text = tabTitle
        }
        return tabBinding.root
    }

    override fun initTabStyle() {
        // 默认选择addOnTabSelectedListener不会回调
        val tabCount = mTabLayout.tabCount
        if (tabCount > 0) {
            val tab = mTabLayout.getTabAt(mCheckedIndex)
            if (tab != null) updateTabStyle(tab, true)
        }

        mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                updateTabStyle(tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                updateTabStyle(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                updateTabStyle(tab, true)
            }
        })
    }

    override fun updateTabStyle(tab: TabLayout.Tab, isChecked: Boolean) {
        val tabView = tab.customView
        val tabTitle = tabView?.findViewById<TextView>(R.id.titleTv)
        val hintTv = tabView?.findViewById<TextView>(R.id.hintTv)
        val ovalHint = tabView?.findViewById<View>(R.id.ovalHint)

        tabTitle?.typeface = if (isChecked) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
        tabTitle?.setTextColor(if (isChecked) com.gh.gamecenter.common.R.color.text_primary.toColor(this) else com.gh.gamecenter.common.R.color.text_secondary.toColor(this))
        hintTv?.background = com.gh.gamecenter.common.R.drawable.message_unread_hint.toDrawable(this)
        ovalHint?.background = com.gh.gamecenter.common.R.drawable.oval_message_hint_bg.toDrawable(this)

        if (tabTitle?.text == TAB_CONCERN) {
            ovalHint?.isVisible = mConcernUnread
            hintTv?.isVisible = false
        } else if (tabTitle?.text == TAB_MESSAGE) {
            ovalHint?.isVisible = mUnreadCount != null && mUnreadCount!!.message == -1
            hintTv?.isVisible = mUnreadCount != null && mUnreadCount!!.message > 0
            hintTv?.text = if ((mUnreadCount?.message ?: 0) < 100) mUnreadCount?.message.toString() else "99+"
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
    }

    companion object {
        private const val TAB_CONCERN_INDEX = 0
        private const val TAB_MESSAGE_INDEX = 1
        private const val TAB_CONCERN = "动态"
        private const val TAB_MESSAGE = "消息"
    }
}