package com.ccwangluo.accelerator.ui.news

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccwangluo.accelerator.model.NewsModel
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.http.HttpGo
import com.xuexiang.xpage.base.XPageFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class NewsObjectModel : ViewModel() {
    val newsModel = MutableLiveData<NewsModel>()


    fun freshData(position: String, gameId: Int, page: Int) {
        val type = when (position) {
            "1" -> 1
            "2" -> 2
            "3" -> 5
            "4" -> 4
            else -> ""
        }
        viewModelScope.launch(Dispatchers.IO) {
            val res =
                HttpGo.getSync<NewsModel>("/api/new/all/list?gameId=$gameId&page=$page&size=10&type=$type")
            res?.let {
                if (it.code == 200) {
                    it.data?.let {
                        newsModel.postValue(it)
                    }
                }
            }
        }
    }

    /**
     * 点赞
     */
    fun greate(xPageFragment: XPageFragment,type: Int?, gameId: Int, parentId: Int, isGreate: Boolean, callback: () -> Unit) {
        val map = mutableMapOf<String, Any>()
        map.put("gameId", gameId)
        map.put("parentId", parentId)
        map.put("isUnGreat", isGreate)
        type?.let {
            map.put("type", it)
        }
        if (LoginUtils.token == null) {
            xPageFragment.context?.let { LoginUtils.login(it,{}) }
            return
        }
        viewModelScope.launch(Dispatchers.IO) {
            val res =
                HttpGo.postSync<String>("/api/new/great", map)
            res?.let {
                if (it.code == 200) {
                    withContext(Dispatchers.Main) {
                        callback()
                    }
                }
            }
        }
    }
}