package com.gh.gamecenter.gamedetail.rating

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.utils.toPx
import com.gh.gamecenter.core.iinterface.IScrollable
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.entity.RatingComment
import com.gh.gamecenter.eventbus.EBStar
import com.gh.gamecenter.eventbus.EBTypeChange
import com.gh.gamecenter.gamedetail.GameDetailFragment
import com.halo.assistant.HaloApp
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class RatingFragment : LazyListFragment<RatingComment, RatingViewModel>(), IScrollable {

    private var mAdapter: RatingAdapter? = null

    private var mSkipGameComment: Boolean? = null

    private var mRatingType: RatingViewModel.RatingType? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        mRatingType = arguments?.getSerializable(EntranceConsts.KEY_LOCATION) as? RatingViewModel.RatingType
            ?: RatingViewModel.RatingType.RATING
        super.onCreate(savedInstanceState)
    }

    override fun getRealLayoutId(): Int {
        return if (mRatingType == RatingViewModel.RatingType.RATING) {
            R.layout.fragment_list_base
        } else {
            R.layout.fragment_list_fold_rating
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RATING_EDIT_REQUEST && resultCode == Activity.RESULT_OK) {
            mListViewModel.initData()
        } else if (
            (requestCode == RATING_REPLAY_REQUEST || requestCode == RATING_PATCH_REQUEST)
            && resultCode == Activity.RESULT_OK
        ) {
            mAdapter?.handleSyncData(requestCode, data)
        } else if (requestCode == RATING_REPLAY_REQUEST && resultCode == RATING_DELETE_RESULT) {
            data?.getParcelableExtra<RatingComment>(RatingComment::class.java.simpleName)?.run {
                mAdapter?.deleteMyComment(id)
            }
        } else if (requestCode == RATING_FOLD_REQUEST && resultCode == RATING_DELETE_RESULT) {
            data?.getStringExtra(EntranceConsts.KEY_COMMENT_ID)?.run {
                mAdapter?.deleteMyComment(this, true)
            }
        }
    }

    override fun getItemDecoration() = null

    override fun provideListAdapter(): RatingAdapter {
        if (mAdapter == null) {
            val directComment = arguments?.getBoolean(EntranceConsts.KEY_DIRECT_COMMENT, false)
                ?: false
            mAdapter = RatingAdapter(requireContext(), mListViewModel, directComment, mEntrance)
        }
        return mAdapter!!
    }

    override fun provideListViewModel(): RatingViewModel {
        val factory = RatingViewModel.Factory(
            HaloApp.getInstance().application,
            arguments?.getParcelable(GameEntity.TAG)!!, mRatingType!!
        )
        return ViewModelProviders.of(this, factory).get(RatingViewModel::class.java)
    }

    override fun isAutomaticLoad(): Boolean {
        return false
    }

    override fun onFragmentResume() {
        super.onFragmentResume()

        startPageTime = System.currentTimeMillis()
    }

    override fun onFragmentPause() {
        super.onFragmentPause()

        val game = arguments?.getParcelable<GameEntity>(GameEntity.TAG)
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        NewLogUtils.logGameDetailTabOrCommentDetailPause(
            "jump_game_detail_comment_tab",
            stayTime,
            game?.id ?: "",
            game?.gameType ?: ""
        )
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()

        val horizontalPadding = R.dimen.game_detail_item_horizontal_padding.toPx()
        mSkipGameComment = arguments?.getBoolean(EntranceConsts.KEY_SKIP_GAME_COMMENT)
        mListRv.setPadding(horizontalPadding, 0, horizontalPadding, 0)
        mListRefresh?.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.transparent))
        mListRefresh?.isEnabled = mRatingType != RatingViewModel.RatingType.RATING
        mListViewModel.ratingLiveData.observe(this, Observer {
            mAdapter?.ratingData = it
            mAdapter?.notifyDataSetChanged()
            EventBus.getDefault().post(EBStar(it.star.average, it.commentCount))
        })
    }

    override fun initRealView() {
        super.initRealView()

        if (mRatingType == RatingViewModel.RatingType.FOLD_RATING) {
            val foldRatingReasonTv = requireView().findViewById<TextView>(R.id.foldRatingReasonTv)
            val text = "折叠原因：因违反《光环助手评论规则》被管理员折叠"
            foldRatingReasonTv.text = SpanBuilder(text).click(requireContext(), 8, 18, R.color.theme_font) {
                MtaHelper.onEvent("折叠评论", "点击评论规则", mListViewModel.game.name)
                requireContext().startActivity(
                    WebActivity.getWebIntent(
                        requireContext(),
                        requireContext().getString(R.string.comment_rules_title),
                        requireContext().getString(R.string.comment_rules_url)
                    )
                )
            }.build()
            foldRatingReasonTv.movementMethod = LinkMovementMethod()
        }
        mListRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    EventBus.getDefault().post(EBTypeChange(GameDetailFragment.EB_SCROLLING, 0))
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    var position = mLayoutManager.findLastCompletelyVisibleItemPosition()
                    if (position == -1) position = mLayoutManager.findLastVisibleItemPosition() - 1
                    NewLogUtils.logCommentFeedSlide(position)
                }
            }
        })
    }

    override fun onLoadDone() {
        super.onLoadDone()
        if (mSkipGameComment == true) {
            val view = mLayoutManager.findViewByPosition(0)
            if (view != null) {
                val bar = view.findViewById<View>(R.id.all_comment_bar)
                if (bar != null) {
                    mBaseHandler.postDelayed({
                        mListRv.smoothScrollBy(0, bar.top)
                    }, 500)
                }
                mSkipGameComment = false
            }
        }
    }

    override fun onLoadRefresh() {
        mReuseNoConn?.visibility = View.GONE
        mReuseNoData?.visibility = View.GONE
        mListLoading?.visibility = View.VISIBLE
        mListRv.visibility = View.GONE
        mBaseHandler.postDelayed({ mListViewModel.initData() }, 500)
    }

    override fun onLoadError() {
        if (mRatingType == RatingViewModel.RatingType.RATING && mListViewModel.ratingLiveData.value != null) {
            mAdapter?.setListData(arrayListOf())
            mAdapter?.loadChange(LoadStatus.LIST_FAILED)
            super.onLoadDone()
        } else {
            super.onLoadError()
        }
    }

    override fun onLoadEmpty() {
        if (mRatingType == RatingViewModel.RatingType.RATING && mListViewModel.ratingLiveData.value != null) {
            mAdapter?.loadChange(LoadStatus.LIST_OVER)
            super.onLoadDone()
            if (mAdapter?.ratingData != null && mListViewModel.filterMap.isEmpty()) {
                mAdapter?.ratingData?.isExistComment = false
                mAdapter?.notifyDataSetChanged()
            }
        } else {
            super.onLoadEmpty()
        }
    }

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

    override fun autoLoadMore() {
        mListViewModel.load(LoadType.NORMAL)
    }

    override fun theNumberNeededToFillAScreen(): Int {
        return 5
    }

    override fun scrollToTop() {
        mListRv?.scrollToPosition(0)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mListRv?.background = R.color.background.toDrawable(requireContext())
        mListRv?.recycledViewPool?.clear()
        mAdapter?.notifyItemRangeChanged(0, mAdapter?.itemCount ?: 0)
    }

    companion object {
        const val RATING_EDIT_REQUEST = 222
        const val RATING_REPLAY_REQUEST = 223
        const val RATING_PATCH_REQUEST = 224
        const val RATING_DELETE_RESULT = 225
        const val RATING_FOLD_REQUEST = 226
        const val FOLD_COUNT_INTENT = "fold_count_intent"
    }
}