package com.ys.bdtp.adm.mvvm.vm.offline

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ys.bdtp.adm.mvvm.model.Data
import com.ys.bdtp.adm.mvvm.model.nt.Fail
import com.ys.bdtp.adm.mvvm.model.vo.Config
import com.ys.bdtp.adm.mvvm.model.vo.Dict
import com.ys.bdtp.adm.mvvm.model.vo.BuildingsAndFloors
import com.ys.bdtp.adm.mvvm.model.vo.Mission
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

/**
 * OfflineViewModel
 */
class OfflineViewModel(private val repo: OfflineRepository) : ViewModel() {

    /**
     * 获取任务
     */
    fun getMission(body: Map<String, String>, success: (Mission) -> Unit, failure: (Fail) -> Unit) {
        viewModelScope.launch {
            repo.getMission(
                body,
                success = {
                    success(it)
                },
                failure = {
                    failure(it)
                }
            )
        }
    }

    /**
     * 获取配置
     */
    fun getConfig(body: Map<String, String>, success: (Config) -> Unit, failure: (Fail) -> Unit) {
        viewModelScope.launch {
            repo.getConfig(body,
                success = {
                    success(it)
                },
                failure = {
                    failure(it)
                }
            )
        }
    }

    /**
     * 获取建筑和楼层数据
     */
    fun getBuildingsAndFloors(
        body: Map<String, String>,
        success: (BuildingsAndFloors) -> Unit,
        failure: (Fail) -> Unit
    ) {
        viewModelScope.launch {
            repo.getBuildingsAndFloors(body,
                success = {
                    success(it)
                },
                failure = {
                    failure(it)
                }
            )

        }
    }

    /**
     * 获取字典
     */
    fun getDict(body: Map<String, String>, success: (Dict) -> Unit, failure: (Fail) -> Unit) {
        viewModelScope.launch {
            repo.getDict(
                body = body,
                success = {
                    success(it)
                },
                failure = {
                    failure(it)
                }
            )
        }
    }

    val buildingWithFloorsFlow = repo.getBuildingWithFloors()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = Data.loading()
        )

    val projectWithBuildingsFlow = repo.getProjectWithBuildings()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = Data.loading()
        )


}