package com.lanyun.wanglaotou.viewModel

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lanyun.common.base.BaseViewModel
import com.lanyun.net.ext.onBizOK
import com.lanyun.net.ext.onFailure
import com.lanyun.net.ext.onSuccess
import com.lanyun.net.ext.serverData
import com.lanyun.wanglaotou.model.GuestPlan
import com.lanyun.wanglaotou.model.UserSubModel
import com.lanyun.wanglaotou.public.PageState
import com.lanyun.wanglaotou.repo.GuestRepo
import com.lanyun.wanglaotou.util.MmkvManager
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class GuestViewModel : BaseViewModel() {

    var viewStates by mutableStateOf(GuestViewState())
        private set

    init {
        dispatch(GuestViewAction.FetchData)
    }

    fun dispatch(action: GuestViewAction) {
        when (action) {
            is GuestViewAction.FetchData -> getGuest()
        }
    }



    fun getGuest() = serverAwait {
        showLoading()
        viewStates = viewStates.copy(pageState = PageState.Loading)
        GuestRepo.getGuest().serverData().onSuccess {
            onBizOK<List<GuestPlan>> { code, data, error_message ->
                val subModel = MmkvManager.decodeSubUserInfo()
                data?.let {
                    viewStates = viewStates.copy(
                        dataList = it,
                        userSubModel= subModel,
                        pageState = PageState.Success(it.isEmpty())
                    )
                }

            }
        }.onFailure {
            hidLoading()
            viewStates = viewStates.copy(pageState = PageState.Error(it.errorMsg))
        }
    }

}

data class GuestViewState(
    val dataList: List<GuestPlan> = emptyList(),
    val pageState: PageState = PageState.Loading,
    val listState: LazyListState = LazyListState(),
    val userSubModel: UserSubModel? = null
) {
    val size = dataList.size
}


sealed class GuestViewAction() {
    object FetchData : GuestViewAction()
}