package com.miya.fastcashier.viewmodel

import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miya.fastcashier.R
import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.net.BaseResult
import com.miya.fastcashier.service.LoginService
import com.miya.fastcashier.beans.LoginFormState
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.RuntimeException

class LoginViewModel : ViewModel() {

    val loginLiveData: MutableLiveData<Result<SelfCashierAccountInfo>> = MutableLiveData()
    val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm


    fun login(userName: String, passWord: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = Result.success(
                    errorHandle(LoginService.getApi().login(LoginRequest(userName, passWord, "")))
                )

                //MMKV记录结算时间
                val balanceDate =
                    MMKV.defaultMMKV().getLong("balanceDate", 0L)
                if (balanceDate <= 0L) {
                    //todo 改成服务器时间
                    MMKV.defaultMMKV().putLong("balanceDate", System.currentTimeMillis())
                }
                loginLiveData.postValue(result)
            } catch (e: Exception) {
                loginLiveData.postValue(Result.failure(e))
            }
        }
    }

    //TODO 待优化
    private fun <T> errorHandle(result: BaseResult<T>): T {
        if (result.code != "200") {
            throw RuntimeException(result.msg)
        }
        return result.data;
    }

    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username)) {
            _loginForm.value = LoginFormState(usernameError = R.string.username_not_empty)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.password_not_empty)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    private fun isUserNameValid(username: String): Boolean {
        return username.isNotBlank()
    }

    private fun isPasswordValid(password: String): Boolean {
        return password.isNotBlank()
    }

}