<script setup lang="ts">
import { reactive } from "vue"
import { login } from "~/service/modules/login"
import { CellGroup, Cell, Field, Button, NavBar, Form, showLoadingToast, closeToast } from "vant"
import { setAuthToken } from "~/utils/auth";
import { useRouter } from "vue-router"

import { useTitle } from "@vueuse/core"

const router = useRouter()

const formData = reactive({
  username: '',
  password: ''
})

async function onLogin(){
  try{
    showLoadingToast({ message: '登录中...', forbidClick: true })
    const { code, data } = await login(formData)
    if(code == 0){
      setAuthToken(data.token)
      router.push('/home')
    }
    closeToast()
  }catch(err){
    console.log(err)
    closeToast()
  }
}

useTitle('登录')
</script>

<template>
  <div class="w-full h-full">
    <NavBar title="登录" />
    <Form @submit="onLogin">
      <CellGroup>
        <Cell>
          <Field
            v-model="formData.username"
            label="用户名" 
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名', trigger: 'change' }]"
          />
        </Cell>

        <Cell>
          <Field
            v-model="formData.password"
            label="密码" 
            placeholder="请输入密码"
            type="password"
            :rules="[{ required: true, message: '请填写用户名', trigger: 'change' }]"
          />
        </Cell>

        <Cell class="mt-[16px]">
          <Button 
            block 
            type="primary" 
            native-type="submit"
          >登录</Button>
        </Cell>
      </CellGroup>
    </Form>
  </div>
</template>
