package com.gh.gamecenter.collection

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.gh.common.exposure.ExposureListener
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.EntranceConsts.*
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.SpacingItemDecoration
import com.gh.gamecenter.entity.GamesCollectionEntity
import com.gh.gamecenter.history.IBatchDelete
import com.gh.gamecenter.history.ManageOption
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class GamesCollectionFragment : ListFragment<GamesCollectionEntity, GamesCollectionViewModel>(), IBatchDelete {

    private var mUserId = ""
    private var mType = ""
    private var mIsInsertGameCollection = false
    private var mAdapter: GamesCollectionAdapter? = null

    override fun provideListViewModel() = viewModelProvider<GamesCollectionViewModel>(
        GamesCollectionViewModel.Factory(mUserId, mType, mIsInsertGameCollection)
    )

    override fun provideListAdapter() =
        mAdapter ?: GamesCollectionAdapter(requireContext(), mListViewModel).apply { mAdapter = this }

    override fun getItemDecoration() =
        SpacingItemDecoration(
            notDecorateTheFirstItem = !mIsInsertGameCollection && mType == TYPE_USER,
            top = 16F.dip2px()
        )

    override fun addSyncPageObserver(): Boolean = true

    override fun provideSyncAdapter() = mAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        mUserId = arguments?.getString(KEY_USER_ID, "") ?: ""
        mType = arguments?.getString(KEY_TYPE, "") ?: ""
        mIsInsertGameCollection = arguments?.getBoolean(KEY_INSERT_GAME_COLLECTION, false) ?: false
        super.onCreate(savedInstanceState)
        mListRv?.run {
            overScrollMode = View.OVER_SCROLL_NEVER
            if (!mIsInsertGameCollection && mType == TYPE_USER) {
                setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            } else {
                setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
            }
        }

    }

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

        mListViewModel.deleteLiveData.observe(viewLifecycleOwner) {
            val index = mAdapter?.entityList?.indexOf(it) ?: -1
            mAdapter?.entityList?.removeAt(index)
            if (mAdapter?.entityList?.isNullOrEmpty() == true) {
                onLoadEmpty()
            } else {
                mAdapter?.notifyItemRemoved(index)
            }

            toast("删除成功")
        }

        mListViewModel.publishLiveData.observe(viewLifecycleOwner) {
            mListViewModel.load(LoadType.REFRESH)

            val path = when (mType) {
                TYPE_COLLECT -> "我的收藏"
                TYPE_HISTORY -> "浏览记录"
                TYPE_USER -> "个人主页"
                else -> ""
            }
            SensorsBridge.trackEvent("GameCollectContributeSuccess", json {
                "source_entrance" to path
                "game_num" to it.count?.game
                "game_collect_title" to it.title
                "game_collect_id" to it.id
            })
        }

        mListRv.addOnScrollListener(ExposureListener(this, provideListAdapter()))
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        // RecyclerView 被隐藏的话会导致不能 AppBar 不能滑动
        if (mType == TYPE_USER) mListRv.visibility = View.VISIBLE
    }

    override fun onLoadError() {
        super.onLoadError()
        if (mType == TYPE_USER) {
            mListRv.visibility = View.VISIBLE
            mReuseNoConn?.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_background))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(changed: EBReuse) {
        if (changed.type == "createGameCollectionSuccess") {
            mListViewModel.load(LoadType.REFRESH)
        }
    }

    override fun changeOption(option: ManageOption) {
        mAdapter?.changeOption(option)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mListRv?.run {
            if (!mIsInsertGameCollection && mType == TYPE_USER) {
                setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            } else {
                setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
            }
            if (itemDecorationCount > 0) {
                removeItemDecorationAt(0)
                addItemDecoration(itemDecoration)
            }
        }
    }


    companion object {
        const val TYPE_HISTORY = "history"
        const val TYPE_COLLECT = "collect"
        const val TYPE_USER = "user"
    }
}