package com.gh.gamecenter.message.view.message

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.therouter.TheRouter
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.toRequestBody
import com.gh.gamecenter.feature.entity.MessageUnreadCount
import com.gh.gamecenter.feature.provider.IMessageUnreadRepositoryProvider
import com.gh.gamecenter.message.entity.SortedMessageEntity
import com.gh.gamecenter.message.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.HttpException

class SortedMessageListViewModel(application: Application) :
    ListViewModel<SortedMessageEntity, SortedMessageEntity>(application) {
    private val mApi = RetrofitManager.getInstance().newApi
    private val mMessageUnreadRepositoryProvider = TheRouter.get(IMessageUnreadRepositoryProvider::class.java)

    override fun provideDataObservable(page: Int): Observable<List<SortedMessageEntity>> {
        return mApi.getSortedMessage()
    }

    fun getSortedMessage() {
        mApi.getSortedMessage()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<SortedMessageEntity>>() {
                override fun onResponse(response: List<SortedMessageEntity>?) {
                    if (response.isNullOrEmpty()) {
                        mLoadStatusLiveData.postValue(LoadStatus.INIT_EMPTY)
                    } else {
                        mListLiveData.postValue(response)
                    }
                }

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

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            mResultLiveData.postValue(it)
            mLoadStatusLiveData.postValue(if (it.isEmpty()) LoadStatus.INIT_EMPTY else LoadStatus.INIT_OVER)
        }
    }

    @SuppressLint("CheckResult")
    fun postSortedMessageRead(id: String, action: () -> Unit) {
        mApi.postSortedMessageRead(id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    loadMessageUnreadData()
                    action()
                }

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

    fun markAllSortedMessageRead() {
        postSortedMessageRead("all") {
            load(LoadType.REFRESH)
        }
    }

    fun markSortedMessageRead(position: Int, id: String) {
        mListLiveData.value?.let {
            val messageEntityList = ArrayList(it)
            messageEntityList[position] = messageEntityList[position].copy(unreadCount = 0)
            mListLiveData.postValue(messageEntityList)
        }
        postSortedMessageRead(id) {}
    }

    @SuppressLint("CheckResult")
    fun deleteSortedMessage(position: Int, id: String) {
        mApi.deleteSortedMessage(id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    mListLiveData.value?.let {
                        val messageEntityList = ArrayList(it)
                        messageEntityList.removeAt(position)
                        mListLiveData.postValue(messageEntityList)
                    }
                }

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

    @SuppressLint("CheckResult")
    fun patchSortedMessageSetting(id: String, body: RequestBody, action: () -> Unit) {
        mApi.patchSortedMessageSetting(id, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    action()
                }

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

    fun setSortedMessageTop(id: String, isSetTop: Boolean) {
        patchSortedMessageSetting(id, mapOf("top" to isSetTop).toRequestBody()) {
            load(LoadType.REFRESH)
        }
    }

    fun setSortedMessageDoNotDisturb(position: Int, id: String, doNotDisturb: Boolean) {
        patchSortedMessageSetting(id, mapOf("do_not_disturb" to doNotDisturb).toRequestBody()) {
            mListLiveData.value?.let {
                val messageEntityList = ArrayList(it)
                messageEntityList[position] =
                    messageEntityList[position].copy(setting = messageEntityList[position].setting.copy(doNotDisturb = doNotDisturb))
                mListLiveData.postValue(messageEntityList)
            }
            loadMessageUnreadData()
        }
    }

    fun getUnreadCountLiveData(): MutableLiveData<MessageUnreadCount?>? {
        return mMessageUnreadRepositoryProvider?.getMessageUnreadCountLiveData()
    }

    fun getZixunConcernLiveData(): MutableLiveData<Boolean>? {
        return mMessageUnreadRepositoryProvider?.getZixunConcernLiveData()
    }

    fun loadMessageUnreadData() {
        mMessageUnreadRepositoryProvider?.loadMessageUnreadData()
    }
}