package com.gh.gamecenter.mygame

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.callback.OnRequestCallBackListener
import com.gh.common.exposure.ExposureListener
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.ConcernActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentFollowedGameBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.eventbus.EBConcernChanged
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.view.CustomDividerItemDecoration
import com.gh.gamecenter.login.user.UserManager
import com.halo.assistant.fragment.myconcern.MyConcernRecommendAdapter
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyFollowedGameFragment : ListFragment<GameEntity, MyFollowedGameViewModel>() {

    private var mAdapter: MyFollowedGameAdapter? = null
    private lateinit var mViewModel: MyFollowedGameViewModel

    private var mRecommendAdapter: MyConcernRecommendAdapter? = null
    private var mExposureListener: ExposureListener? = null
    private val mBinding by lazy { FragmentFollowedGameBinding.inflate(layoutInflater) }

    override fun onStart() {
        super.onStart()
        if (!UserManager.getInstance().isLoggedIn) {
            mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv.text = getString(R.string.login_hint)
            mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.theme_font
                )
            )
        } else {
            mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv.text = getString(R.string.game_empty)
            mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv.setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    R.color.text_title
                )
            )
        }
    }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

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

        arrayListOf(
            mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv,
            mBinding.concernRlTitle,
            mBinding.concernManageRl
        ).forEach {
            it.setOnClickListener(this)
        }

        // 不需要分页
        mListRv.clearOnScrollListeners()
        mListRv.addOnScrollListener(mExposureListener!!)
        mCachedView.setBackgroundColor(R.color.background_white.toColor(requireContext()))

        mBinding.concernRvRecommend.setHasFixedSize(true)
        mBinding.concernRvRecommend.layoutManager = GridLayoutManager(context, 4)
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        if (mRecommendAdapter?.recommendGameList == null || mRecommendAdapter!!.recommendGameList.isEmpty()) {
            mBinding.concernRlTitle.visibility = View.GONE
            mBinding.concernRvRecommend.visibility = View.GONE
            onLoadDone()
        } else {
            if (mRecommendAdapter!!.recommendGameList.size < 4) {
                mBinding.concernRvRecommend.layoutManager =
                    GridLayoutManager(context, mRecommendAdapter!!.recommendGameList.size)
            }
        }
    }

    override fun onLoadDone() {
        super.onLoadDone()
        postDelayedRunnable({
            if (mRecommendAdapter == null && context != null) {
                mRecommendAdapter = MyConcernRecommendAdapter(context, object :
                    OnRequestCallBackListener<Any> {
                    override fun loadDone() {
                        mBinding.concernRlTitle.goneIf(mViewModel.getListData().size > 3)
                        mBinding.concernRvRecommend.goneIf(mViewModel.getListData().size > 3)
                        val size = mRecommendAdapter!!.recommendGameList.size
                        mBinding.concernRvRecommend.layoutManager =
                            GridLayoutManager(context, if (size > 4) 4 else size)
                        mBinding.concernRvRecommend.adapter?.notifyDataSetChanged()
                        if (mAdapter != null && mAdapter!!.itemCount > 0) {
                            mBinding.concernLl.hideRecyclerViewNoAnimation()
                        }
                    }

                    override fun loadDone(obj: Any?) {
                        //do nothing
                    }

                    override fun loadError() {
                        //do nothing
                    }

                    override fun loadEmpty() {
                        //do nothing
                    }

                    override fun loadNotFound() {
                        //do nothing
                    }

                }, mViewModel.getListData(), mEntrance)
                mBinding.concernRvRecommend.adapter = mRecommendAdapter
            }
        }, 100)
    }

    override fun onChanged(ts: MutableList<GameEntity>?) {
        super.onChanged(ts)
        mBinding.concernRlTitle.goneIf(mViewModel.getListData().size > 3)
        mBinding.concernRvRecommend.goneIf(mViewModel.getListData().size > 3)
        mBinding.concernManageRl.goneIf(mViewModel.getListData().size <= 3)
    }

    override fun provideListViewModel(): MyFollowedGameViewModel {
        mViewModel = viewModelProvider()
        return mViewModel
    }

    override fun provideListAdapter(): ListAdapter<GameEntity> {
        return mAdapter ?: MyFollowedGameAdapter(requireContext(), mViewModel).apply {
            mAdapter = this
            mExposureListener = ExposureListener(this@MyFollowedGameFragment, this)
        }
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.reuseNoneDataTv -> {
                val hint = getString(R.string.login_hint)
                if (hint == mBinding.fragmentListBase.reuseNoneData.reuseNoneDataTv.text.toString()) {
                    ifLogin("(我的关注)", null)
                }
            }
            R.id.concern_rl_title -> {
                if (mBinding.concernRvRecommend.visibility == View.VISIBLE) {
                    mBinding.concernLl.hideRecyclerView()
                    NewFlatLogUtils.logMyGameFollowTabHotGameClick("收起", "", "")
                } else {
                    mBinding.concernLl.showRecyclerView()
                    NewFlatLogUtils.logMyGameFollowTabHotGameClick("展开", "", "")
                }
            }
            R.id.concernManageRl -> {
                val intent = ConcernActivity.getIntent(requireContext(), "我的游戏-关注")
                requireContext().startActivity(intent)
            }
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration {
        mItemDecoration = CustomDividerItemDecoration(
            requireContext(),
            onlyDecorateTheFirstItem = false,
            notDecorateTheFirstItem = false,
            notDecorateTheLastItem = true,
            notDecorateTheFirstTwoItems = false
        ).apply {
            setDrawable(R.drawable.divider_my_game.toDrawable(requireContext())!!)
        }
        return mItemDecoration
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(changed: EBReuse) {
        if (Constants.LOGIN_TAG == changed.type) { // 登入
            onLoadRefresh()
        }
    }

    // 关注事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(changed: EBConcernChanged) {
        if (!changed.isSingle) {
            return
        }
        if (changed.isConcern) {
            if (mRecommendAdapter == null) return

            onLoadRefresh()

            var i = 0
            val size = mRecommendAdapter?.recommendGameList?.size ?: 0
            while (i < size) {
                if (changed.gameId == mRecommendAdapter?.recommendGameList?.get(i)?.id) {
                    val game = mRecommendAdapter?.recommendGameList?.get(i)
                    NewFlatLogUtils.logMyGameFollowTabHotGameClick(
                        "关注",
                        game?.id ?: "",
                        game?.name ?: ""
                    )
                    mRecommendAdapter?.recommendGameList?.removeAt(i)
                    mRecommendAdapter?.notifyItemRemoved(i) // 删除动画
                    mRecommendAdapter?.notifyDataSetChanged() // 防止列表串行
                    if (mRecommendAdapter?.recommendGameList.isNullOrEmpty()) {
                        mBinding.concernRlTitle.visibility = View.GONE
                        mBinding.concernRvRecommend.visibility = View.GONE
                    }
                    break
                }
                i++
            }
        } else {
            mViewModel.removeFollowLocally(changed.gameId)

            // fuck me
//            if (gameEntity != null) {
//                mRecommendAdapter?.recommendGameList?.add(0, gameEntity)
//                mRecommendAdapter?.notifyDataSetChanged()
//            }

            if (mRecommendAdapter?.recommendGameList.isNullOrEmpty()) {
                mBinding.concernRlTitle.visibility = View.GONE
                mBinding.concernRvRecommend.visibility = View.GONE
            } else {
                mBinding.concernRlTitle.visibility = View.VISIBLE
                mBinding.concernRvRecommend.visibility = View.VISIBLE
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.run {
            if (mRecommendAdapter?.recommendGameList?.isNotEmpty() == true) {
                concernRvRecommend.recycledViewPool.clear()
                mRecommendAdapter?.notifyItemRangeChanged(0, mRecommendAdapter!!.itemCount)
            }
        }
    }
}