package com.za.ui.order_report

import com.blankj.utilcode.util.ToastUtils
import com.za.base.BaseVm
import com.za.base.view.LoadingManager
import com.za.bean.ReportHistoryBean
import com.za.bean.ReportHistoryRequest
import com.za.common.GlobalData
import com.za.net.BaseObserver
import com.za.net.RetrofitHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class HistoryReportVm : BaseVm<HistoryReportVm.Action, HistoryReportVm.UiState>() {
    private val _uiState = MutableStateFlow(UiState())
    val uiState get() = _uiState.asStateFlow()

    override fun updateState(uiState: UiState) {
        _uiState.value = uiState
    }

    override fun dispatch(action: Action) {
        when (action) {
            Action.Init -> init()
        }
    }

    private fun init() {
        LoadingManager.showLoading()
        val request = ReportHistoryRequest(taskId = "${GlobalData.currentOrder?.taskId}")
        RetrofitHelper.getDefaultService().getReportHistory(request)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseObserver<List<ReportHistoryBean>>() {
                override fun doSuccess(it: List<ReportHistoryBean>?) {
                    LoadingManager.hideLoading()
                    updateState(uiState.value.copy(historyReportList = it))
                }

                override fun doFailure(code: Int, msg: String?) {
                    LoadingManager.hideLoading()
                    ToastUtils.showLong(msg)
                }
            })
    }

    data class UiState(val historyReportList: List<ReportHistoryBean>? = null)

    sealed class Action {
        data object Init : Action()
    }
}