package com.gh.gamecenter.feedback.view.qa

import android.os.Build
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.therouter.TheRouter
import com.gh.gamecenter.common.base.GlobalActivityManager
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.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.core.provider.ISearchTabUtilsProvider
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.feedback.HaloApp
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.entity.HelpCategoryEntity
import com.gh.gamecenter.feedback.entity.HelpEntity
import com.gh.gamecenter.feedback.retrofit.RetrofitManager
import com.gh.gamecenter.feedback.utils.NewLogUtils
import com.gh.gamecenter.feedback.view.suggest.SuggestionActivity
import io.reactivex.Observable
import java.util.*

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 mCategoryId: String? = null
    private var mIsMyRelatedQA = false

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

    var searchKey: String? = null
    private var mLocation = ""
    private var mSearchType = ""

    private val iSearchTabUtilsProvider: ISearchTabUtilsProvider?
        get() = TheRouter.get(ISearchTabUtilsProvider::class.java)


    override fun provideListAdapter(): HelpContentAdapter {
        if (mAdapter == null) {
            mAdapter =
                HelpContentAdapter(
                    requireContext(),
                    this,
                    mListViewModel,
                    !mCategoryId.isNullOrEmpty() || mIsMyRelatedQA,
                    mQaCollectionId,
                    mNavigationTitle,
                    mSearchType,
                    mLocation
                )
            mAdapter?.searchKey = searchKey ?: ""
        }
        return mAdapter!!
    }

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

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

    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)
        mCategoryId = arguments?.getString(EntranceConsts.KEY_CATEGORY_ID)
        mIsMyRelatedQA = arguments?.getBoolean(EntranceConsts.KEY_MY_RELATED_QA) ?: false
        mNavigationTitle = arguments?.getString(EntranceConsts.KEY_NAVIGATION_TITLE) ?: ""
        mLocation = arguments?.getString(EntranceConsts.KEY_LOCATION) ?: ""
        mSearchType = arguments?.getString(EntranceConsts.KEY_SEARCH_TYPE) ?: ""
        super.onCreate(savedInstanceState)
        mReuseNoneDataSearch = mCachedView.findViewById(R.id.reuse_none_data_search)
        mReuseNoneDataButton = mCachedView.findViewById(com.gh.gamecenter.common.R.id.reuseResetLoadTv)
        mReuseNoneDataButton.text = "意见反馈"
        mReuseNoneDataButton.setTextColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.white))
        mReuseNoneDataButton.background = com.gh.gamecenter.common.R.drawable.download_button_normal_style.toDrawable(requireContext())
        mReuseNoneDataButton.visibility = View.VISIBLE
        val reuseNoneDataTv = mReuseNoneDataSearch.findViewById<TextView>(com.gh.gamecenter.common.R.id.reuseNoneDataTv)
        reuseNoneDataTv.text = "没有找到相关内容~"
        val reuseNoneDataDescTv = mReuseNoneDataSearch.findViewById<TextView>(com.gh.gamecenter.common.R.id.reuseNoneDataDescTv)
        reuseNoneDataDescTv.visibility = View.VISIBLE
        reuseNoneDataDescTv.text = "换个搜索词试试看吧"
        mReuseNoneDataButton.setOnClickListener {
            requireContext().startActivity(SuggestionActivity.getSuggestionCategoryIntent(requireContext()))
        }

        val parentViewModel = iSearchTabUtilsProvider?.obtainParentViewModel(this)
        iSearchTabUtilsProvider?.getKeyAndTypeLiveData(parentViewModel)?.observe(this) { (key, _) ->
            updateSearchKey(key)
        }
    }

    override fun provideDataObservable(page: Int): Observable<List<HelpEntity>> {
        val filterQuery = if (searchKey != null) {
            if (!mCategoryId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("help_id", mCategoryId, "keyword", searchKey)
            } else if (mIsMyRelatedQA) {
                UrlFilterUtils.getFilterQuery(
                    "manufacturer",
                    Build.MANUFACTURER.uppercase(Locale.CHINA),
                    "keyword",
                    searchKey
                )
            } else 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 || !mCategoryId.isNullOrEmpty()) {
            if (!mQaCollectionId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("qa_id", mCategory?.id ?: mCategoryId)
            } else {
                UrlFilterUtils.getFilterQuery("help_id", mCategory?.id ?: mCategoryId)
            }
        } else if (mIsMyRelatedQA) {
            UrlFilterUtils.getFilterQuery("manufacturer", Build.MANUFACTURER.uppercase(Locale.CHINA))
        } else {
            if (!mQaId.isNullOrEmpty()) {
                UrlFilterUtils.getFilterQuery("qa_id", mQaId)
            } else {
                ""
            }
        }

        return if (mQaId.isNullOrEmpty() && mQaCollectionId.isNullOrEmpty()) {
            RetrofitManager.getInstance().api.getSearchHelps(filterQuery, page)
        } else {
            RetrofitManager.getInstance().api.getQaContents(filterQuery, page)
        }.doOnNext {
            if (page == 1) {
                SensorsBridge.trackQASearchResultReturn(
                    GlobalActivityManager.getCurrentPageEntity().pageId,
                    GlobalActivityManager.getCurrentPageEntity().pageName,
                    mLocation,
                    searchKey ?: "",
                    mSearchType,
                    it.isNotEmpty()
                )
            }
        }
    }

    override fun provideListViewModel(): NormalListViewModel<HelpEntity> {
        val factory = NormalListViewModel.Factory(HaloApp.getInstance(), 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())
        }
    }

    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
    }
}