import { Loading } from '../components/loading/Loading'
import { promptAction } from '@kit.ArkUI'
import { hideKeyboard } from '../utils/SysUtils'
import { ReqApi } from '../api/req/ReqApi'
import { Storage } from '../utils/Storage'

@Observed
export class VMLogin {
  // 登录类型
  // 0-短信登录 1-密码登录
  loginType: number = 0
  // 手机号或账号
  account: string = ""
  // 验证码或密码
  code: string = ""

  setLoginType(type: number) {
    this.loginType = type
  }

  login(skip: Function) {
    if (this.account.trim() == "") {
      const msg = this.loginType == 0 ? "请输入手机号" : "请输入用户名"
      promptAction.openToast({ message: msg }).catch()
      return
    }
    if (this.code == "") {
      const msg = this.loginType == 0 ? "请输入验证码" : "请输入密码"
      promptAction.openToast({ message: msg }).catch()
      return
    }
    hideKeyboard()
    Loading.showLoading({ text: '登录中...' })
    ReqApi.login(this.account.trim(), this.code).then((rsp) => {
      Storage.setLogin(true)
      Storage.setToken(rsp.token)
      Storage.setUsername(rsp.nickName)
      Loading.hideLoading()
      promptAction.openToast({ message: '登录成功' }).catch()
      skip()
    }).catch(() => {
      Loading.hideLoading()
    })
  }

  updateAccount(account: string) {
    this.account = account
  }

  updateCode(code: string) {
    this.code = code
  }
}