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

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.iscs.bozzys.R
import com.iscs.bozzys.api.ApiRequest
import com.iscs.bozzys.api.ApiRequest.getResponse
import com.iscs.bozzys.ui.base.StateLoading
import com.iscs.bozzys.ui.base.VMBase
import com.iscs.bozzys.utils.Storage
import com.iscs.bozzys.utils.Storage.saveToken
import com.iscs.bozzys.utils.Storage.saveUserName
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 登录ViewModel层
 */
class VMLogin : VMBase() {

    var state by mutableStateOf(StateLogin())
        private set

    /**
     * 更新登录方式
     *
     * @param type 0:短信验证码登录 1:账号密码登录
     */
    fun updateLoginType(type: Int) {
        state = state.copy(loginType = type)
    }

    /**
     * 更新账号字段数据
     *
     * @param account loginType=0时为手机号 loginType=1时为用户名
     */
    fun updateAccount(account: String) {
        state = state.copy(account = account)
    }

    /**
     * 更新code字段
     *
     * @param code loginType=0时为验证码 loginType=1时为密码
     */
    fun updateCode(code: String) {
        state = state.copy(code = code)
    }

    /**
     * 执行登录操作
     */
    fun login(done: () -> Unit) {
        viewModelScope.launch {
            val check = checkCanLogin()
            if (check != 0) {
                toastEvent.emit(check)
                return@launch
            }
            loadingEvent.emit(StateLoading(show = true))
            ApiRequest.login(state.account, state.code).onSuccess {
                it.token.saveToken()
                it.nickName.saveUserName()
                Storage.saveLogin(true)
                loadingEvent.emit(StateLoading(show = false))
                delay(500)
                toastEvent.emit("登录成功")
                done.invoke()
            }.onFailure {
                delay(500)
                loadingEvent.emit(StateLoading(show = false))
                toastEvent.emit(it.getResponse().msg)
            }
        }
    }

    /**
     * 检验是否可以提交登录
     */
    private fun checkCanLogin(): Int {
        if (state.loginType == 0) {
            if (state.account.trim().isEmpty()) return R.string.input_phone_number_tips
            if (state.code.trim().isEmpty()) return R.string.input_code_tips
        } else if (state.loginType == 1) {
            if (state.account.trim().isEmpty()) return R.string.input_account_tips
            if (state.code.trim().isEmpty()) return R.string.input_pwd_tips
        }
        return 0
    }

}

/**
 * 登录页面状态模型
 */
data class StateLogin(val loginType: Int = 0, val account: String = "", val code: String = "")