<template>
  <div class="container" style="max-width: 460px; margin-top: 80px">
    <a-card title="萌贝母婴商城 - 登录/注册">
      <a-form :model="form" layout="vertical">
        <a-form-item label="账号">
          <a-input v-model="form.username" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input-password v-model="form.password" placeholder="请输入密码" />
        </a-form-item>
        <a-space>
          <a-button type="primary" @click="onLogin">登录</a-button>
          <a-button @click="onRegister">注册</a-button>
        </a-space>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const form = reactive({ username: '', password: '' })

const routeByRole = (role) => {
  if (role === 'ADMIN') return '/admin'
  if (role === 'MERCHANT') return '/merchant'
  return '/products'
}

const onLogin = async () => {
  try {
    const res = await api.login({ username: form.username, password: form.password })
    localStorage.setItem('token', res.token)
    await userStore.fetchMe()
    Message.success('登录成功')
    router.replace(routeByRole(userStore.role))
  } catch (e) {
    Message.error(e.message)
  }
}

const onRegister = async () => {
  try {
    await api.register({ username: form.username, password: form.password })
    Message.success('注册成功，请登录')
  } catch (e) {
    Message.error(e.message)
  }
}
</script>
