package com.gh.gamecenter.feedback.view.help

import android.annotation.SuppressLint
import android.app.Application
import android.os.Build
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.feedback.entity.HelpCategoryEntity
import com.gh.gamecenter.feedback.entity.HelpEntity
import com.gh.gamecenter.feedback.entity.HelpVideo
import com.gh.gamecenter.feedback.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException
import java.util.*

class HelpAndFeedbackViewModel(application: Application) : AndroidViewModel(application) {
    private val mNewApi = RetrofitManager.getInstance().newApi
    private val mApi = RetrofitManager.getInstance().api

    val helpVideosLiveData = MutableLiveData<List<HelpVideo>?>()
    val categoryLiveData = MutableLiveData<List<HelpCategoryEntity>>()
    val helpContentsLiveData = MutableLiveData<List<HelpEntity>?>()

    var selectedCategory = HelpCategoryEntity(id = "", name = MY_RELATED_QA_NAME)

    init {
        initData()
    }

    fun initData() {
        getHelpVideo()
        getHelpCategory()
        getHelpContents()
    }

    fun setCategory(categoryEntity: HelpCategoryEntity) {
        selectedCategory = categoryEntity
        getHelpContents()
    }

    @SuppressLint("CheckResult")
    fun getHelpVideo() {
        mNewApi.getHelpVideos()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<HelpVideo>>() {
                override fun onSuccess(data: List<HelpVideo>) {
                    helpVideosLiveData.postValue(data)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    helpVideosLiveData.postValue(null)
                    Utils.toast(getApplication(), "网络异常")
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getHelpCategory() {
        mApi.getHelpCategory()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<HelpCategoryEntity>>() {
                override fun onSuccess(data: List<HelpCategoryEntity>) {
                    val categoryList = ArrayList(data)
                    categoryList.add(0, HelpCategoryEntity(name = MY_RELATED_QA_NAME))
                    categoryLiveData.postValue(categoryList.take(HELP_CATEGORY_MAX_COUNT))
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.toast(getApplication(), "网络异常")
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getHelpContents() {
        val filterQuery = if (selectedCategory.id.isNotEmpty()) {
            UrlFilterUtils.getFilterQuery("help_id", selectedCategory.id)
        } else {
            UrlFilterUtils.getFilterQuery("manufacturer", Build.MANUFACTURER.uppercase(Locale.CHINA))
        }

        mApi.getSearchHelps(filterQuery, 1, HELP_CONTENT_NORMAL_SIZE + HELP_CONTENT_RECOMMEND_SIZE)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<HelpEntity>>() {
                override fun onResponse(response: List<HelpEntity>?) {
                    super.onResponse(response)
                    val helpEntityList = ArrayList(response)
                    var recommendCount = response?.count { it.type == "recommend" } ?: 0
                    // 【与我相关】分类最多只显示2个推荐内容，多出来的设置为普通样式
                    if (selectedCategory.id.isEmpty() && recommendCount > HELP_CONTENT_RECOMMEND_SIZE) {
                        helpEntityList.forEachIndexed { index, helpEntity ->
                            if (index >= HELP_CONTENT_RECOMMEND_SIZE && helpEntity.type == "recommend") {
                                helpEntity.type = ""
                            }
                        }
                        recommendCount = HELP_CONTENT_RECOMMEND_SIZE
                    }
                    helpContentsLiveData.postValue(helpEntityList.take(recommendCount + HELP_CONTENT_NORMAL_SIZE))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    helpContentsLiveData.postValue(null)
                    Utils.toast(getApplication(), "网络异常")
                }
            })
    }

    companion object {
        const val MY_RELATED_QA_NAME = "与我相关"
        const val HELP_CONTENT_NORMAL_SIZE = 10
        const val HELP_CONTENT_RECOMMEND_SIZE = 2
        const val HELP_CATEGORY_MAX_COUNT = 9
    }
}