package com.gh.gamecenter.gamecollection.square

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.common.filter.RegionSettingHelper
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadParams
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import java.util.*

class GameCollectionSquareViewModel(application: Application) :
    ListViewModel<GamesCollectionEntity, GameCollectionListItemData>(application) {

    private val mApi = RetrofitManager.getInstance().api
    private val mRandomId = UUID.randomUUID().toString()

    var entrance: String? = null
    var selectedTagCategory = ""
    var selectedTagEntity: TagInfoEntity? = null
    var selectedTagId = ""
    var selectedTagName = "全部标签"
    var view = "recommend"
    var isHome = false
    var refreshCount = 0

    val amwayCommentList = MutableLiveData<List<AmwayCommentEntity>>()
    val bannerList = MutableLiveData<List<CarouselEntity>>()
    val hotListFirstTab = MutableLiveData<String>()

    override fun loadData() {
        getAmwayCommentList()
        getBannerList()
        getGameCollectionHotListTab()
        super.loadData()
    }

    override fun initLoadParams() {
        mCurLoadParams = LoadParams(PAGE_SIZE, LoadParams.DEFAULT_OFFSET)
        mLoadStatusLiveData.value = LoadStatus.INIT
    }

    override fun provideDataSingle(page: Int): Single<MutableList<GamesCollectionEntity>> {
        val paramsMap = if (selectedTagId.isNotEmpty()) {
            mutableMapOf("tag_id" to selectedTagId)
        } else {
            mutableMapOf()
        }
        if (view == "recommend") {
            paramsMap["random"] = mRandomId
            if (refreshCount == 0 && page == 1) {
                paramsMap["refresh"] = "true"
            }
        }
        return RetrofitManager.getInstance()
            .api.getGameCollectionSquareList(
                view,
                page,
                PAGE_SIZE,
                paramsMap.toMap()
            )
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) { list ->
            val itemDataList = arrayListOf<GameCollectionListItemData>().apply {
                var position = 0
                if (isHome) {
                    add(
                        GameCollectionListItemData(
                            amwayListItem = amwayCommentList.value,
                            carouselListItem = bannerList.value,
                            hotListTabName = hotListFirstTab.value ?: "",
                            isHeaderItem = true
                        )
                    )
                    add(GameCollectionListItemData(isFilterItem = true))
                }
                for (item in list) {
                    item.games = RegionSettingHelper.filterSimpleGame(item.games)
                    add(
                        GameCollectionListItemData(
                            gameCollectionItem = item,
                            gameStartPosition = position,
                            isGameCollectionItem = true
                        )
                    )
                    position += if (item.count?.game!! > 2) 3 else if (item.games?.size == 0) 0 else item.count?.game
                        ?: 0
                }
            }
            mResultLiveData.postValue(itemDataList)
        }
    }

    override fun provideDataObservable(page: Int): Observable<MutableList<GamesCollectionEntity>>? = null

    @SuppressLint("CheckResult")
    fun getAmwayCommentList() {
        mApi.getAmwayCommentList(1, 10)
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<List<AmwayCommentEntity>>() {
                override fun onSuccess(data: List<AmwayCommentEntity>) {
                    amwayCommentList.postValue(data)
                }
            })
    }

    @SuppressLint("CheckResult")
    fun getBannerList() {
        mApi.gameCollectionSquareBanner
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<List<CarouselEntity>>() {
                override fun onSuccess(data: List<CarouselEntity>) {
                    bannerList.postValue(data)
                }

                override fun onFailure(exception: Exception) {
                    bannerList.postValue(emptyList())
                }
            })
    }

    private fun getGameCollectionHotListTab() {
        mApi.gameCollectionHotListTab
            .compose(observableToMain())
            .subscribe(object : Response<List<GameCollectionListEntity>>() {
                override fun onResponse(response: List<GameCollectionListEntity>?) {
                    super.onResponse(response)
                    response?.firstOrNull()?.let {
                        hotListFirstTab.postValue(it.name)
                    }
                }
            })
    }

    companion object {
        const val PAGE_SIZE = 15

        fun getOrderNameByPosition(position: Int) = when (position) {
            1 -> "hot"
            2 -> "new"
            else -> "recommend"
        }

        fun getOrderPositionByName(name: String) = when (name) {
            "hot" -> 1
            "new" -> 2
            else -> 0
        }

        fun getOrderChineseByName(name: String) = when (name) {
            "recommend" -> "推荐"
            "hot" -> "热门"
            "new" -> "最新"
            else -> ""
        }
    }
}