package com.gh.gamecenter.forum.moderator

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.ifLogin
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.FragmentModeratorListBinding
import com.gh.gamecenter.entity.ApplyModeratorStatusEntity
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.newsdetail.NewsDetailActivity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ModeratorListFragment : ToolbarFragment() {
    private lateinit var mBinding: FragmentModeratorListBinding
    private var mViewModel: ModeratorListViewModel? = null
    private var mAdapter: ModeratorListAdapter? = null
    private var mBbsId: String = ""
    private var mBbsType: String = ""
    private var mStatus: ApplyModeratorStatusEntity = ApplyModeratorStatusEntity()

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = FragmentModeratorListBinding.bind(mCachedView)
        mBbsId = arguments?.getString(EntranceConsts.KEY_BBS_ID) ?: ""
        mBbsType = arguments?.getString(EntranceConsts.KEY_TYPE) ?: ""
        val bbsName = arguments?.getString(EntranceConsts.KEY_NAME) ?: ""
        val factory = ModeratorListViewModel.Factory(mBbsId)
        mViewModel = viewModelProvider(factory)

        mViewModel?.isModerators?.observe(this, Observer {
            if (it) {
                mBinding.applyTv.background = R.drawable.bg_forum_follow.toDrawable(requireContext())
                mBinding.applyTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
                mBinding.applyTv.text = "您已是版主"
                mBinding.applyTv.setOnClickListener {
                    NewLogUtils.logForumModeratorClick("click_member")
                    ToastUtils.toast("您已经是${bbsName}版主啦~")
                }
            }
        })

        mViewModel?.moderators?.observe(this, Observer {
            mBinding.reuseLoading.root.visibility = View.GONE
            if (it != null) {
                mBinding.reuseNoConnection.root.visibility = View.GONE
                if (it.isNotEmpty()) {
                    mBinding.reuseNoneData.reuseNoneData.visibility = View.GONE
                    mAdapter?.setListData(it)
                } else {
                    mBinding.reuseNoneData.reuseNoneData.visibility = View.VISIBLE
                }
            } else {
                mBinding.reuseNoneData.reuseNoneData.visibility = View.GONE
                mBinding.reuseNoConnection.root.visibility = View.VISIBLE
            }
        })

        mViewModel?.statusEntity?.observe(this, Observer {
            it?.run { mStatus = this }
        })
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.listRv.apply {
            layoutManager = LinearLayoutManager(requireContext())
            mAdapter = ModeratorListAdapter(requireContext(), mViewModel)
            adapter = mAdapter
        }
        mBinding.toolbar.setNavigationOnClickListener {
            requireActivity().finish()
        }
        mBinding.doubtIv.setOnClickListener {
            val bbsType = if (mBbsType == "game_bbs") "游戏论坛" else "综合论坛"
            NewLogUtils.logForumRuleEnter(mBbsId, bbsType)
            startActivity(
                NewsDetailActivity.getIntentById(
                    requireContext(),
                    Constants.FORUM_REGULATIONS_NEWS_ID,
                    "板块成员"
                )
            )
        }
        mBinding.applyTv.setOnClickListener {
            context?.ifLogin("板块成员") {
                NewLogUtils.logForumModeratorClick("click_apply_member")
                val bbsType = if (mBbsType == "game_bbs") "游戏论坛" else "综合论坛"
                NewLogUtils.logApplyModeratorEnter(mBbsId, bbsType)
                requireContext().startActivity(
                    ApplyModeratorActivity.getIntent(
                        requireContext(),
                        mBbsId,
                        mStatus
                    )
                )
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(follow: EBUserFollow?) {
        val index = mAdapter?.datas?.indexOfFirst { it.id == follow?.userId } ?: 0
        mAdapter?.datas?.get(index)?.me?.isFollower = follow?.isFollow ?: false
        mAdapter?.notifyItemChanged(index)
    }

    override fun onResume() {
        super.onResume()
        mViewModel?.getModeratorsInfo()
        mViewModel?.getModeratorsApplyStatus()
    }

    override fun onStop() {
        super.onStop()
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        val bbsType = if (mBbsType == "game_bbs") "游戏论坛" else "综合论坛"
        NewLogUtils.logActivityPause(
            "版主成员", "jump_forum_member", stayTime,
            mBbsId, bbsType, "", ""
        )
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.toolbar.setNavigationIcon(com.gh.gamecenter.common.R.drawable.ic_bar_back)
        mBinding.toolbar.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
        mBinding.title.setTextColor(com.gh.gamecenter.common.R.color.text_black.toColor(requireContext()))
    }
}