package com.casic.br.vm

import androidx.lifecycle.MutableLiveData
import com.casic.br.base.BaseApplication
import com.casic.br.extensions.separateResponseCode
import com.casic.br.extensions.toErrorMessage
import com.casic.br.model.CommonResultModel
import com.casic.br.model.PushMessageModel
import com.casic.br.utils.retrofit.RetrofitServiceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.extensions.launch
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.vm.BaseViewModel

class MessageViewModel : BaseViewModel() {

    private val gson by lazy { Gson() }
    val listModel = MutableLiveData<PushMessageModel>()
    val deleteResult = MutableLiveData<CommonResultModel>()
    val updateResult = MutableLiveData<CommonResultModel>()

    fun obtainMessageListByPage(
        messageCode: String, messageTitle: String, messageContent: String, offset: Int
    ) = launch({
        val response = RetrofitServiceManager.obtainMessageListByPage(
            messageCode, messageTitle, messageContent, offset
        )
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            listModel.value = gson.fromJson<PushMessageModel>(
                response, object : TypeToken<PushMessageModel>() {}.type
            )
        }
    }, {
        it.printStackTrace()
    })

    fun deleteMessageById(id: String) = launch({
        val response = RetrofitServiceManager.deleteMessageById(id)
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            deleteResult.value = gson.fromJson<CommonResultModel>(
                response, object : TypeToken<CommonResultModel>() {}.type
            )
        } else {
            response.toErrorMessage().show(BaseApplication.obtainInstance())
        }
    }, {
        it.printStackTrace()
    })

    fun updateMessageById(id: String, messageStatus: String) = launch({
        val response = RetrofitServiceManager.updateMessageById(id, messageStatus)
        val responseCode = response.separateResponseCode()
        if (responseCode == 200) {
            updateResult.value = gson.fromJson<CommonResultModel>(
                response, object : TypeToken<CommonResultModel>() {}.type
            )
        } else {
            response.toErrorMessage().show(BaseApplication.obtainInstance())
        }
    }, {
        it.printStackTrace()
    })
}