package com.gh.gamecenter.help

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.HelpAndFeedbackActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.baselist.NormalListViewModel
import com.gh.gamecenter.entity.HelpCategoryEntity
import com.gh.gamecenter.entity.HelpEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.Observable

class HelpContentFragment : ListFragment<HelpEntity, NormalListViewModel<HelpEntity>>() {

    lateinit var mReuseNoneDataButton: TextView
    lateinit var mReuseNoneDataSearch: View

    private var mAdapter: HelpContentAdapter? = null

    private var mCategory: HelpCategoryEntity? = null

    private var mQaCollectionId: String? = null
    private var mQaId: String? = null
    private var mNavigationTitle = ""

    var searchKey: String? = null


    override fun provideListAdapter(): HelpContentAdapter {
        if (mAdapter == null) {
            mAdapter =
                HelpContentAdapter(requireContext(), this, mListViewModel, mQaId, mQaCollectionId, mNavigationTitle)
            mAdapter?.searchKey = searchKey ?: ""
        }
        return mAdapter!!
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration? {
        return null
    }

    override fun isAutomaticLoad(): Boolean {
        return !mQaId.isNullOrEmpty() || !searchKey.isNullOrEmpty()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_help_content
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        searchKey = arguments?.getString(EntranceConsts.KEY_SEARCHKEY)
        mQaId = arguments?.getString(EntranceConsts.KEY_QA_ID)
        mQaCollectionId = arguments?.getString(EntranceConsts.KEY_QA_COLLECTION_ID)
        mNavigationTitle = arguments?.getString(EntranceConsts.KEY_NAVIGATION_TITLE) ?: ""
        super.onCreate(savedInstanceState)
        mReuseNoneDataSearch = mCachedView.findViewById(R.id.reuse_none_data_search)
        mReuseNoneDataButton = mCachedView.findViewById(R.id.reuseResetLoadTv)
        mReuseNoneDataButton.text = "意见反馈"
        mReuseNoneDataButton.setTextColor(ContextCompat.getColor(requireContext(), R.color.theme_font))
        mReuseNoneDataButton.background =
            ContextCompat.getDrawable(requireContext(), R.drawable.bg_search_skip_game_btn_radius20)
        mReuseNoneDataButton.visibility = View.VISIBLE
        val reuseNoneDataTv = mReuseNoneDataSearch.findViewById<TextView>(R.id.reuseNoneDataTv)
        reuseNoneDataTv.text = "没有找到相关内容~"
        val reuseNoneDataDescTv = mReuseNoneDataSearch.findViewById<TextView>(R.id.reuseNoneDataDescTv)
        reuseNoneDataDescTv.visibility = View.VISIBLE
        reuseNoneDataDescTv.text = "换个搜索词试试看吧"
        mReuseNoneDataButton.setOnClickListener {
            if (activity is HelpAndFeedbackActivity) {
                (activity as HelpAndFeedbackActivity).setCurrentItem(HelpAndFeedbackActivity.SUGGESTION_ITEM)
            } else {
                DirectUtils.directToHelpAndFeedback(requireContext(), HelpAndFeedbackActivity.SUGGESTION_ITEM)
            }
        }
    }

    override fun provideDataObservable(page: Int): Observable<List<HelpEntity>> {
        val filterQuery = if (searchKey != null) {
            if (!mQaCollectionId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("collection_id", mQaCollectionId, "keyword", searchKey)
            } else if (!mQaId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("qa_id", mQaId, "keyword", searchKey)
            } else {
                UrlFilterUtils.getFilterQuery("keyword", searchKey)
            }
        } else if (mCategory != null) {
            if (!mQaCollectionId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("qa_id", mCategory?.id)
            } else {
                UrlFilterUtils.getFilterQuery("help_id", mCategory?.id)
            }
        } else {
            if (!mQaId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("qa_id", mQaId)
            } else {
                ""
            }
        }

        if (mQaId.isNullOrEmpty() && mQaCollectionId.isNullOrEmpty()) {
            return RetrofitManager.getInstance().api.getSearchHelps(filterQuery, page)
        } else {
            return RetrofitManager.getInstance().api.getQaContents(filterQuery, page)
        }
    }

    override fun provideListViewModel(): NormalListViewModel<HelpEntity> {
        val factory = NormalListViewModel.Factory(HaloApp.getInstance().application, this)
        return ViewModelProviders.of(this, factory)
            .get(NormalListViewModel::class.java) as NormalListViewModel<HelpEntity>
    }

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

    override fun theNumberNeededToFillAScreen(): Int {
        return 10
    }

    fun updateSearchKey(key: String) {
        if (key != searchKey) {
            searchKey = key
            mAdapter?.searchKey = searchKey ?: ""
            onLoadRefresh()
        }
    }

    fun setHelpCategory(category: HelpCategoryEntity?) {
        if (mCategory != category) {
            mCategory = category
            onLoadRefresh()
        }
    }

    fun getHelpCategory(): HelpCategoryEntity? {
        return mCategory
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        if (searchKey.isNullOrEmpty()) {
            mReuseNoneDataSearch.visibility = View.GONE
            mReuseNoData?.visibility = View.VISIBLE
        } else {
            mReuseNoneDataSearch.visibility = View.VISIBLE
            mReuseNoData?.visibility = View.GONE
        }
    }

    override fun onChanged(ts: MutableList<HelpEntity>?) {
        super.onChanged(ts)
        if (!searchKey.isNullOrEmpty() &&
            (mListViewModel.loadStatusLiveData.value == LoadStatus.INIT_OVER ||
                    mListViewModel.loadStatusLiveData.value == LoadStatus.INIT_LOADED ||
                    mListViewModel.loadStatusLiveData.value == LoadStatus.INIT_EMPTY)
        ) {
            NewLogUtils.logClickQaSearchBtn(searchKey ?: "", ts?.isNullOrEmpty() == true)
        }
    }

    override fun onLoadDone() {
        super.onLoadDone()
        mReuseNoneDataSearch.visibility = View.GONE
    }

    override fun onLoadError() {
        super.onLoadError()
        mReuseNoneDataSearch.visibility = View.GONE
    }

    override fun onLoadRefresh() {
        super.onLoadRefresh()
        mReuseNoneDataSearch.visibility = View.GONE
    }
}