package com.iscs.bozzys.ui.pages.vm

import androidx.lifecycle.viewModelScope
import com.iscs.bozzys.api.ApiRequest
import com.iscs.bozzys.api.ApiRequest.getResponse
import com.iscs.bozzys.event.RefreshEvent
import com.iscs.bozzys.event.RefreshEventBus
import com.iscs.bozzys.ui.common.VMBase
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * 发布作业
 */
class VMPushJob : VMBase() {

    private var _state = MutableStateFlow(StatePushJob())
    val state = _state.asStateFlow()

    /**
     * 发布作业
     */
    fun onPush(id: Int, done: () -> Unit) {
        viewModelScope.launch {
            loading.emit(StateLoading(show = true))
            ApiRequest.pushJob(mutableMapOf("startType" to _state.value.pushType, "workId" to id)).onSuccess {
                delay(1000)
                loading.emit(StateLoading())
                toast.emit("发布成功")
                // 刷新首页数据
                RefreshEventBus.onRefreshData(RefreshEvent.JobDetail)
                RefreshEventBus.onRefreshData(RefreshEvent.HomeData)
                done()
            }.onFailure {
                delay(1000)
                loading.emit(StateLoading())
                toast.emit(it.getResponse<Any>().msg)
            }
        }
    }

    /**
     * 更新发布方式
     */
    fun updatePushType(pushType: String) {
        _state.value = _state.value.copy(pushType = pushType)
    }

}

/**
 * 发布作业状态类
 *
 * @param pushType 发布方式 0-立即发布 1-定时发布
 */
data class StatePushJob(val pushType: String = "0")