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 com.lanyun.common.base.BaseViewModel
import com.lanyun.net.ext.*
import com.lanyun.wanglaotou.model.GuestPlan
import com.lanyun.wanglaotou.model.UrlModel
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.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

class WelcomeModel : BaseViewModel() {

    var viewStates by mutableStateOf(WelcomeViewState())
        private set

    private val _viewEvents = Channel<WelcomeViewEvent>(Channel.BUFFERED)
    val viewEvents = _viewEvents.receiveAsFlow()

    init {
        dispatch(WelcomeViewAction.FetchData)
    }

    fun dispatch(action: WelcomeViewAction) {
        when (action) {
            is WelcomeViewAction.FetchData -> getUrl()
        }
    }

    private fun getUrl() = serverAwait{
        viewStates = viewStates.copy(pageState = PageState.Loading)
        GuestRepo.getUrl().serverData().onSuccess {
            onBizError { code, error_message ->
                viewStates = viewStates.copy(pageState = PageState.Error(error_message ?: "异常请求"))
            }
            onBizOK<UrlModel> { code, data, error_message ->
                data?.let {
                    MmkvManager.encodeUrlinfo(it)
                    viewStates = viewStates.copy(pageState = PageState.Success(it.register.isEmpty()))
                }

                launch {
                    delay(1000)
                    _viewEvents.send(WelcomeViewEvent.ToMain)
                }
            }
        }.onFailure {
            viewStates = viewStates.copy(pageState = PageState.Error(it.errorMsg))
        }
    }
}

data class WelcomeViewState(
    val pageState: PageState = PageState.Loading,
)

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

/**
 * 一次性事件
 */
sealed class WelcomeViewEvent {
    object ToMain : WelcomeViewEvent()

}