<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useToast } from '@/composables/useToast'

defineOptions({ name: 'Login' })
const auth = useAuthStore()
const route = useRoute()
const router = useRouter()
const { show } = useToast()

const username = ref('')
const password = ref('')
const loading = ref(false)

const submit = async () => {
  if (!username.value || !password.value) {
    show('请输入账号和密码', 'error')
    return
  }
  loading.value = true
  try {
    await auth.login({ username: username.value, password: password.value })
    const redirect = route.query.redirect || '/'
    router.replace(redirect)
  } catch (e) {
    show(e?.response?.data?.detail || '登录失败', 'error')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="min-h-screen flex flex-col bg-surface">
    <div class="flex-[0.55] flex items-end justify-center pb-10">
      <div class="text-center">
        <div class="w-16 h-16 mx-auto rounded-2xl bg-brand text-white text-2xl font-bold flex items-center justify-center">M³</div>
        <h1 class="mt-4 text-lg font-semibold leading-snug">房地产新材料<br/>选材管理数据系统</h1>
        <p class="mt-1 text-sm text-muted">登录后查看材料库</p>
      </div>
    </div>
    <div class="flex-[0.45] px-6 space-y-3">
      <input v-model="username" placeholder="账号"
        class="w-full h-12 px-4 rounded-card bg-surface-alt border border-line focus:border-brand outline-none" />
      <input v-model="password" type="password" placeholder="密码"
        class="w-full h-12 px-4 rounded-card bg-surface-alt border border-line focus:border-brand outline-none" />
      <button :disabled="loading" @click="submit"
        class="w-full h-12 rounded-card bg-brand text-white text-base font-medium active:bg-brand-dark disabled:opacity-60">
        {{ loading ? '登录中…' : '登录' }}
      </button>
    </div>
  </div>
</template>
