<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminLogin } from '../../api/admin/auth'
import { useAdminAuthStore } from '../../stores/adminAuth'

const route = useRoute()
const router = useRouter()
const adminAuth = useAdminAuthStore()

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

function loginErrorMessage(e: unknown): string {
  if (e instanceof Error && e.message.trim()) return e.message
  if (typeof e === 'string' && e.trim()) return e
  return '登录失败'
}

function resolvePostLoginPath(): string {
  const redir = typeof route.query.redirect === 'string' ? route.query.redirect : ''
  if (redir && redir.startsWith('/admin') && !redir.includes('/login')) {
    return redir
  }
  return '/admin'
}

async function onSubmit() {
  if (!username.value.trim() || !password.value.trim()) {
    ElMessage.warning('请输入账号和密码')
    return
  }
  submitting.value = true
  try {
    const res = await adminLogin({
      username: username.value.trim(),
      password: password.value.trim(),
    })
    adminAuth.setToken(res.token)
    await router.replace(resolvePostLoginPath())
    ElMessage.success('登录成功')
  } catch (e) {
    ElMessage.error(loginErrorMessage(e))
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="login-wrap">
    <el-card class="login-card" shadow="hover">
      <template #header>
        <div class="card-title">管理员登录</div>
      </template>
      <el-form label-position="top" @submit.prevent="onSubmit">
        <el-form-item label="账号">
          <el-input v-model.trim="username" autocomplete="username" clearable />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" autocomplete="current-password" show-password />
        </el-form-item>
        <el-button type="danger" class="w-100" native-type="submit" :loading="submitting">
          {{ submitting ? '登录中…' : '登录' }}
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.login-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background: var(--el-bg-color-page);
}

.login-card {
  width: 100%;
  max-width: 420px;
}

.card-title {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
}

.w-100 {
  width: 100%;
}

</style>
