Files
JayuCloud/Frontend/src/views/admin/AdminLoginView.vue
T

375 lines
9.8 KiB
Vue
Raw Normal View History

2026-02-25 10:37:16 +08:00
<template>
<div class="admin-login">
<div class="login-container">
<div class="login-header">
<h1>后台管理系统</h1>
<p>欢迎回来,请登录您的账户</p>
</div>
<a-card class="login-card">
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleLogin"
>
2026-03-21 12:37:52 +08:00
<a-alert
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
2026-03-21 12:37:52 +08:00
show-icon
:message="loginShopMessage"
2026-03-21 12:37:52 +08:00
style="margin-bottom: 16px"
/>
2026-02-25 11:08:02 +08:00
<a-form-item label="用户名" name="account">
2026-02-25 10:37:16 +08:00
<a-input
2026-02-25 11:08:02 +08:00
v-model:value="formState.account"
2026-02-25 10:37:16 +08:00
size="large"
placeholder="请输入用户名"
:prefix-icon="UserOutlined"
@input="handleAccountInput"
2026-02-25 10:37:16 +08:00
/>
</a-form-item>
<a-form-item label="密码" name="password">
<a-input-password
v-model:value="formState.password"
size="large"
placeholder="请输入密码"
:prefix-icon="LockOutlined"
@pressEnter="handleLogin"
/>
</a-form-item>
2026-03-20 17:20:23 +08:00
<a-form-item label="登录店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="shopPlaceholder"
2026-03-20 17:20:23 +08:00
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
2026-03-20 17:20:23 +08:00
show-search
:filter-option="filterShopOption"
/>
</a-form-item>
2026-02-25 10:37:16 +08:00
<a-form-item>
<a-button
type="primary"
size="large"
html-type="submit"
:loading="loading"
block
>
登录
</a-button>
</a-form-item>
</a-form>
<div class="login-footer">
<a @click="goToFrontend">返回前台</a>
</div>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
2026-02-25 10:37:16 +08:00
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import { usePermission } from '@/utils/permission'
2026-02-25 10:37:16 +08:00
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
2026-03-20 17:20:23 +08:00
const shopLoading = ref(false)
const shops = ref<Array<{ id: number | string; shopName: string }>>([])
const allowShoplessLogin = ref(false)
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
2026-02-25 10:37:16 +08:00
const formState = reactive({
2026-02-25 11:08:02 +08:00
account: '',
2026-03-20 17:20:23 +08:00
password: '',
shopId: undefined as string | undefined
2026-02-25 10:37:16 +08:00
})
let loginShopTimer: number | undefined
2026-02-25 10:37:16 +08:00
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
const getShopIdValue = (shop: { id: number | string; shopName: string }) => String(shop.id ?? '')
const getShopLabel = (shop: { id: number | string; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
2026-03-20 17:20:23 +08:00
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
2026-03-20 17:20:23 +08:00
}))
)
2026-03-21 12:37:52 +08:00
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
const shopPlaceholder = computed(() => {
if (allowShoplessLogin.value) {
return '当前无需选择店铺'
}
if (shopLoading.value) {
return '正在加载可登录店铺'
}
if (hasAvailableShops.value) {
return '请选择登录店铺'
}
return '请先输入账号'
})
2026-03-20 17:20:23 +08:00
2026-02-25 10:37:16 +08:00
const formRules = {
account: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
],
2026-03-20 17:20:23 +08:00
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
2026-03-21 12:37:52 +08:00
shopId: [{
validator: async () => {
if (!shouldRequireShop.value || formState.shopId) {
2026-03-21 12:37:52 +08:00
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
},
trigger: 'change'
}]
2026-03-10 23:23:15 +08:00
} as any
2026-02-25 10:37:16 +08:00
2026-03-20 17:20:23 +08:00
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
}
const resetLoginShopTimer = () => {
if (loginShopTimer !== undefined) {
window.clearTimeout(loginShopTimer)
loginShopTimer = undefined
}
}
2026-03-20 17:20:23 +08:00
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
return
}
try {
const parsed = JSON.parse(cached)
if (parsed?.shopId) {
formState.shopId = String(parsed.shopId)
2026-03-20 17:20:23 +08:00
}
} catch (error) {
console.error('恢复后台登录店铺失败:', error)
}
}
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
shops.value = selection?.shops || []
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
loginShopMessage.value = selection?.message || ''
if (allowShoplessLogin.value) {
formState.shopId = undefined
return
}
if (!shops.value.length) {
formState.shopId = undefined
return
}
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
if (matchedShop) {
return
}
if (shops.value.length === 1) {
formState.shopId = getShopIdValue(shops.value[0]!)
return
}
formState.shopId = undefined
}
const loadLoginShops = async (account = formState.account) => {
const trimmedAccount = account.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
2026-03-20 17:20:23 +08:00
shopLoading.value = true
try {
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
2026-03-21 12:37:52 +08:00
}
2026-03-20 17:20:23 +08:00
} catch (error) {
if (formState.account.trim() === trimmedAccount) {
if (isLoginShopPrefetchUnsupported(error)) {
applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
shops: []
})
} else {
applyLoginShopSelection(null)
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
}
}
if (!isLoginShopPrefetchUnsupported(error)) {
console.error('获取登录店铺列表失败:', error)
}
2026-03-20 17:20:23 +08:00
} finally {
shopLoading.value = false
}
}
2026-02-25 10:37:16 +08:00
const handleLogin = async () => {
try {
await formRef.value?.validate()
loading.value = true
const res = await adminAuthApi.login({
2026-02-25 11:08:02 +08:00
account: formState.account,
2026-03-20 17:20:23 +08:00
password: formState.password,
2026-03-21 12:37:52 +08:00
shopId: formState.shopId
2026-02-25 10:37:16 +08:00
})
2026-02-26 17:54:18 +08:00
2026-02-25 10:37:16 +08:00
const { accessToken, refreshToken, userInfo } = res as any
localStorage.setItem('adminAccessToken', accessToken)
localStorage.setItem('adminRefreshToken', refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(userInfo))
sessionStorage.setItem('adminAccessToken', accessToken)
2026-02-25 10:37:16 +08:00
message.success('登录成功')
await loadUserPermissions()
2026-02-26 17:54:18 +08:00
router.push('/admin').catch(err => {
console.error('跳转到首页失败:', err)
window.location.href = '/admin'
})
2026-02-25 10:37:16 +08:00
} catch (error: any) {
console.error('登录失败:', error)
message.error(error.message || '登录失败,请检查用户名和密码')
} finally {
loading.value = false
}
}
2026-03-20 17:20:23 +08:00
onMounted(() => {
restoreLoginShop()
})
watch(
() => formState.account,
value => {
resetLoginShopTimer()
const trimmedAccount = value.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
loginShopTimer = window.setTimeout(() => {
loginShopTimer = undefined
void loadLoginShops(trimmedAccount)
}, 400)
}
)
onBeforeUnmount(() => {
resetLoginShopTimer()
2026-03-20 17:20:23 +08:00
})
2026-02-25 10:37:16 +08:00
const goToFrontend = () => {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
sessionStorage.removeItem('accessToken')
setTimeout(() => {
window.location.href = '/'
}, 100)
2026-02-25 10:37:16 +08:00
}
</script>
<style scoped>
.admin-login {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
.login-container {
width: 100%;
max-width: 420px;
}
.login-header {
text-align: center;
margin-bottom: 32px;
color: white;
}
.login-header h1 {
font-size: 32px;
font-weight: 600;
margin: 0 0 8px 0;
}
.login-header p {
font-size: 14px;
opacity: 0.9;
margin: 0;
}
.login-card {
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.login-footer {
text-align: center;
margin-top: 16px;
}
.login-footer a {
color: #1890ff;
text-decoration: none;
font-size: 14px;
}
.login-footer a:hover {
text-decoration: underline;
}
</style>