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

459 lines
12 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<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"
>
<a-alert
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
show-icon
:message="loginShopMessage"
style="margin-bottom: 16px"
/>
<a-form-item label="用户名" name="account">
<a-input
v-model:value="formState.account"
size="large"
placeholder="请输入用户名"
:prefix-icon="UserOutlined"
@input="handleAccountInput"
/>
</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>
<a-form-item label="登录店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="shopPlaceholder"
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
show-search
:filter-option="filterShopOption"
/>
</a-form-item>
<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'
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 type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading'
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const shopLoading = ref(false)
const shops = ref<Array<{ id: IdType; shopName: string }>>([])
const allowShoplessLogin = ref(false)
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
const formState = reactive({
account: '',
password: '',
shopId: undefined as string | undefined
})
let loginShopTimer: number | undefined
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
}))
)
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 '请先输入账号'
})
const formRules = {
account: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{
validator: async () => {
if (!shouldRequireShop.value || formState.shopId) {
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
},
trigger: 'change'
}]
} as any
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
}
}
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
return
}
try {
const parsed = JSON.parse(cached)
if (parsed?.shopId) {
formState.shopId = String(parsed.shopId)
}
} 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
}
shopLoading.value = true
try {
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
}
} 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)
}
} finally {
shopLoading.value = false
}
}
const handleLogin = async () => {
try {
await formRef.value?.validate()
loading.value = true
const res = await runWithGlobalLoading(() => adminAuthApi.login({
account: formState.account,
password: formState.password,
shopId: formState.shopId
}))
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)
message.success('登录成功')
await runWithGlobalLoading(() => loadUserPermissions())
router.push('/admin').catch(err => {
console.error('跳转到首页失败:', err)
window.location.href = '/admin'
})
} catch (error: any) {
console.error('登录失败:', error)
message.error(error.message || '登录失败,请检查用户名和密码')
} finally {
loading.value = false
}
}
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()
})
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)
}
</script>
<style scoped>
.admin-login {
min-height: 100dvh;
background:
radial-gradient(circle at top right, rgba(255, 244, 232, 0.2), transparent 30%),
radial-gradient(circle at left top, rgba(233, 193, 167, 0.18), transparent 38%),
linear-gradient(
160deg,
var(--admin-mobile-shell-start) 0%,
var(--admin-mobile-shell-mid) 56%,
var(--admin-mobile-shell-end) 100%
);
display: flex;
align-items: center;
justify-content: center;
padding: max(24px, env(safe-area-inset-top)) 24px max(24px, env(safe-area-inset-bottom));
}
.login-container {
width: 100%;
max-width: 440px;
}
.login-header {
text-align: center;
margin-bottom: 28px;
color: #f7f2eb;
}
.login-header h1 {
font-size: clamp(28px, 4vw, 38px);
font-weight: 700;
margin: 0 0 8px 0;
}
.login-header p {
font-size: 14px;
line-height: 1.7;
opacity: 0.82;
margin: 0;
}
.login-card {
border-radius: 24px;
border: 1px solid var(--admin-mobile-border);
box-shadow: 0 24px 50px rgba(146, 103, 82, 0.18);
overflow: hidden;
}
.login-footer {
text-align: center;
margin-top: 18px;
}
.login-footer a {
color: #fff3ea;
text-decoration: none;
font-size: 14px;
font-weight: 600;
}
.login-footer a:hover {
text-decoration: underline;
}
.login-card :deep(.ant-card-body) {
background: rgba(255, 250, 244, 0.98);
}
.login-card :deep(.ant-btn-primary) {
border-color: transparent;
background: linear-gradient(135deg, var(--admin-mobile-accent) 0%, var(--admin-mobile-accent-strong) 100%);
box-shadow: 0 10px 22px rgba(185, 100, 73, 0.18);
}
.login-card :deep(.ant-btn-primary:hover),
.login-card :deep(.ant-btn-primary:focus) {
border-color: transparent;
background: linear-gradient(135deg, #d4866c 0%, #c26e52 100%);
}
.login-card :deep(.ant-input:hover),
.login-card :deep(.ant-input-affix-wrapper:hover),
.login-card :deep(.ant-select:not(.ant-select-disabled):hover .ant-select-selector) {
border-color: rgba(204, 123, 95, 0.46);
}
.login-card :deep(.ant-input:focus),
.login-card :deep(.ant-input-affix-wrapper-focused),
.login-card :deep(.ant-select-focused .ant-select-selector) {
border-color: rgba(204, 123, 95, 0.62);
box-shadow: 0 0 0 2px rgba(204, 123, 95, 0.12);
}
@media (max-width: 960px) {
.admin-login {
align-items: flex-start;
justify-content: stretch;
padding: calc(22px + env(safe-area-inset-top)) 14px calc(18px + env(safe-area-inset-bottom));
}
.login-container {
max-width: none;
}
.login-header {
text-align: left;
margin-bottom: 18px;
padding: 0 4px;
}
.login-header h1 {
max-width: 8em;
}
.login-card {
border-radius: 26px;
}
.login-card :deep(.ant-card-body) {
padding: 20px 18px 18px;
}
.login-card :deep(.ant-form-item) {
margin-bottom: 18px;
}
.login-card :deep(.ant-btn-lg),
.login-card :deep(.ant-input-affix-wrapper-lg),
.login-card :deep(.ant-input-lg),
.login-card :deep(.ant-select-single.ant-select-lg .ant-select-selector) {
min-height: 48px;
}
}
</style>