WEB/src/views/login/index.vue
2026-09-08 18:04:27 +08:00

861 lines
23 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="login-container" :style="loginBgStyle">
<div class="login-card">
<!-- 左侧品牌区 -->
<div class="login-left-panel">
<div class="brand-info">
<!-- <svg-icon icon-class="dashboard" class="brand-logo" /> -->
<img :src="brandLogo" style="width:160px;height: 65px;" alt="logo">
<!-- <h1 class="brand-name">天豹云仓</h1> -->
<h1 v-if="brandName" class="brand-name">{{ brandName }}</h1>
<p class="brand-desc">{{ loginDesc }}</p>
</div>
</div>
<!-- 右侧表单区 -->
<div class="login-right-panel">
<lang-select class="set-language" />
<!-- ========== 注册表单 ========== -->
<el-form
v-if="showRegister"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
class="login-form"
auto-complete="on"
label-position="top"
>
<div class="title-container">
<h3 class="title">{{ $t('login.register') }}</h3>
<p class="subtitle">开启您的管理之旅</p>
</div>
<el-form-item prop="username" :label="$t('login.username')">
<el-input
v-model="registerForm.username"
:placeholder="$t('login.usernamePlaceholder')"
name="username"
type="text"
tabindex="1"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="user" /></template>
</el-input>
</el-form-item>
<el-form-item prop="email" :label="$t('login.email')">
<el-input
v-model="registerForm.email"
:placeholder="$t('login.emailPlaceholder')"
name="email"
type="email"
tabindex="2"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="email" /></template>
</el-input>
</el-form-item>
<el-form-item>
<el-input
v-model="registerForm.real_name"
:placeholder="$t('login.realNamePlaceholder')"
name="real_name"
type="text"
tabindex="3"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="user" /></template>
</el-input>
</el-form-item>
<el-form-item prop="password" :label="$t('login.password')">
<el-input
:key="passwordType"
v-model="registerForm.password"
:type="passwordType"
:placeholder="$t('login.passwordPlaceholder')"
name="password"
tabindex="4"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="password" /></template>
</el-input>
</el-form-item>
<el-form-item prop="confirmPassword" :label="$t('login.confirmPassword')">
<el-input
:key="passwordType"
v-model="registerForm.confirmPassword"
:type="passwordType"
:placeholder="$t('login.confirmPassword')"
name="confirmPassword"
tabindex="5"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="password" /></template>
</el-input>
</el-form-item>
<el-button
:loading="loading"
type="primary"
class="submit-btn"
@click.prevent="handleRegister"
>
{{ $t('login.register') }}
</el-button>
<div class="form-footer">
<span>{{ $t('login.hasAccount') }}</span>
<el-button type="link" @click="showRegister = false">{{ $t('login.logIn') }}</el-button>
</div>
</el-form>
<!-- ========== 登录区(账号 + 扫码 Tab) ========== -->
<div v-else class="login-tabs-wrap">
<div class="title-container">
<h3 class="title">{{ $t('login.title') }}</h3>
<p class="subtitle">欢迎回来,请登录您的账户</p>
</div>
<!-- Tab 切换按钮 -->
<div class="login-tabs">
<button
class="tab-btn"
:class="{ active: activeTab === 'account' }"
@click="switchTab('account')"
>
{{ $t('login.accountLogin') }}
</button>
<button
class="tab-btn"
:class="{ active: activeTab === 'qrcode' }"
@click="switchTab('qrcode')"
>
{{ $t('login.qrcodeLogin') }}
</button>
</div>
<!-- 账号登录表单 -->
<el-form
v-show="activeTab === 'account'"
ref="loginFormRef"
:model="loginForm"
:rules="loginRules"
class="login-form"
auto-complete="on"
label-position="top"
>
<el-form-item prop="username" :label="$t('login.username')">
<el-input
ref="usernameRef"
v-model="loginForm.username"
:placeholder="$t('login.usernamePlaceholder')"
name="username"
type="text"
tabindex="1"
auto-complete="on"
>
<template #prefix><svg-icon icon-class="user" /></template>
</el-input>
</el-form-item>
<el-form-item prop="password" :label="$t('login.password')">
<el-input
:key="passwordType"
ref="passwordRef"
v-model="loginForm.password"
:type="passwordType"
:placeholder="$t('login.passwordPlaceholder')"
name="password"
tabindex="2"
auto-complete="on"
@keyup.enter="handleLogin"
>
<template #prefix><svg-icon icon-class="password" /></template>
<template #suffix>
<span class="show-pwd" @click="showPwd">
<svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
</span>
</template>
</el-input>
</el-form-item>
<el-button
:loading="loading"
type="primary"
class="submit-btn"
@click.prevent="handleLogin"
>
{{ loading ? $t('login.loggingIn') : $t('login.logIn') }}
</el-button>
<div class="form-footer">
<span>{{ $t('login.noAccount') }}</span>
<el-button type="link" @click="showRegister = true">{{ $t('login.register') }}</el-button>
</div>
</el-form>
<!-- 微信扫码登录面板 -->
<div v-show="activeTab === 'qrcode'" class="qrcode-panel">
<p class="qrcode-desc">{{ $t('login.qrcodeDesc') }}</p>
<!-- 二维码展示区 -->
<div class="qrcode-box" @click="qrcodeExpired ? refreshQrCode() : undefined">
<!-- 加载中 -->
<div v-if="qrcodeLoading" class="qrcode-mask">
<el-icon class="loading-icon"><Loading /></el-icon>
<span>{{ $t('login.qrcodeLoading') }}</span>
</div>
<!-- 已扫码等待确认 -->
<div v-else-if="qrcodeScanned" class="qrcode-mask scanned">
<el-icon><CircleCheck /></el-icon>
<span>{{ $t('login.qrcodeScanned') }}</span>
</div>
<!-- 过期遮罩 -->
<div v-else-if="qrcodeExpired" class="qrcode-mask expired" style="cursor:pointer">
<el-icon><RefreshRight /></el-icon>
<span>{{ $t('login.qrcodeExpired') }}</span>
<small>{{ $t('login.qrcodeRefresh') }}</small>
</div>
<!-- 二维码图片 -->
<img v-if="qrcodeUrl" :src="qrcodeUrl" class="qrcode-img" alt="WeChat QR Code" />
<div v-else-if="!qrcodeLoading" class="qrcode-placeholder" />
</div>
<p class="qrcode-waiting" v-if="!qrcodeExpired && !qrcodeLoading && !qrcodeScanned">
{{ $t('login.qrcodeWaiting') }}
</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Loading, CircleCheck, RefreshRight } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import * as userApi from '@/api/user/user'
import { useFrontBrandStore } from '@/stores/modules/frontBrand'
import { setToken } from '@/utils/auth'
import { useI18n } from 'vue-i18n'
import LangSelect from '@/components/LangSelect/index.vue'
import QRCode from 'qrcode'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
// ── 前端独立部署品牌(frontConfig.getByDomain):按域名替换 Logo / 标题 / 背景 ──
const frontBrand = useFrontBrandStore()
const brand = computed(() => frontBrand.brand)
// 主题约定:网页名称(theme.siteName||brand.title)、登录页 logo(theme.loginLogoUrl||品牌 logo)、登录页文字(theme.loginText)
const brandName = computed(() => frontBrand.siteTitle)
const brandLogo = computed(() => frontBrand.themeLoginLogoUrl || '../../../public/logo/1.png')
const loginDesc = computed(() => frontBrand.themeLoginText || '现代化仓储管理系统 - 助力企业高效运营')
const loginBgStyle = computed(() =>
brand.value?.login_bg_url?.trim()
? {
backgroundImage: `url(${brand.value.login_bg_url.trim()})`,
backgroundSize: 'cover',
backgroundPosition: 'center'
}
: undefined
)
onMounted(() => {
// 登录前免鉴权拉取域名品牌(main 已触发时内部幂等跳过)
frontBrand.loadBrandByDomain()
})
// ---- 表单 refs ----
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
// ---- 视图状态 ----
const showRegister = ref(false)
const activeTab = ref<'account' | 'qrcode'>('account')
// ---- 账号登录 ----
const loginForm = reactive({ username: '', password: '' })
const loginRules = {
username: [{ required: true, trigger: 'blur', message: t('login.usernamePlaceholder') }],
password: [{ required: true, trigger: 'blur', message: t('login.passwordPlaceholder') }]
}
// ---- 注册 ----
const registerForm = reactive({
username: '',
password: '',
confirmPassword: '',
email: '',
real_name: ''
})
const validateConfirmPassword = (_rule: any, value: string, callback: any) => {
if (value !== registerForm.password) {
callback(new Error(t('login.passwordMismatch')))
} else {
callback()
}
}
const registerRules = {
username: [{ required: true, trigger: 'blur', message: t('login.usernamePlaceholder') }],
password: [
{ required: true, trigger: 'blur', message: t('login.passwordPlaceholder') },
{ min: 6, message: t('login.passwordLengthTip'), trigger: 'blur' }
],
confirmPassword: [
{ required: true, trigger: 'blur', message: t('login.confirmPassword') },
{ validator: validateConfirmPassword, trigger: 'blur' }
]
}
// ---- 密码显示切换 ----
const passwordType = ref('password')
const loading = ref(false)
const showPwd = () => {
passwordType.value = passwordType.value === 'password' ? '' : 'password'
}
// ---- 路由重定向 ----
const redirect = ref('')
const otherQuery = ref<Record<string, any>>({})
watch(
() => route.query,
(query) => {
if (query) {
redirect.value = query.redirect as string
const { redirect: _, ...rest } = query
otherQuery.value = rest
}
},
{ immediate: true }
)
// ---- 登录 ----
const handleLogin = () => {
loginFormRef.value?.validate(async (valid: boolean) => {
if (valid) {
loading.value = true
try {
await userStore.login(loginForm)
router.push({ path: redirect.value || '/', query: otherQuery.value })
} catch {
// handled by interceptor
} finally {
loading.value = false
}
}
})
}
// ---- 注册 ----
const handleRegister = () => {
registerFormRef.value?.validate(async (valid: boolean) => {
if (valid) {
loading.value = true
try {
const { username, email, real_name, password } = registerForm
await userStore.register({ username, email, real_name, password })
ElMessage.success(t('login.registerSuccess') || '注册成功')
showRegister.value = false
} catch {
// handled by interceptor
} finally {
loading.value = false
}
}
})
}
// ====================================================
// 微信扫码登录
// ====================================================
const qrcodeUrl = ref('')
const qrcodeLoading = ref(false)
const qrcodeExpired = ref(false)
const qrcodeScanned = ref(false)
let pollingAborted = false
let currentPollingVersion = 0
/** 小程序登录链接模板(二维码内容) */
const loginLinkTemplate = 'https://ye4s.wms.gztbyc.com/mini/?spm=0.4.${code}.1.4'
/** 前端本地生成二维码 Data URL */
const generateQrDataUrl = async (code: string): Promise<string> => {
const targetUrl = loginLinkTemplate.replace('${code}', code)
return QRCode.toDataURL(targetUrl, {
width: 200,
margin: 2,
color: { dark: '#000000', light: '#ffffff' }
})
}
/** 停止当前轮询 */
const stopPolling = () => {
pollingAborted = true
currentPollingVersion++
}
/** 跳转到已登录状态 */
const doLoginWithToken = (token: string) => {
setToken(token)
userStore.$patch({ token })
router.push({ path: redirect.value || '/', query: otherQuery.value })
}
/** 长轮询 */
const startPolling = () => {
pollingAborted = false
const version = currentPollingVersion
const poll = async () => {
if (pollingAborted || currentPollingVersion !== version) return
try {
const resp = await (userApi as any).getLoginWechatCode({
clientCode: qrcodeClientCode,
})
if (pollingAborted || currentPollingVersion !== version) return
const data = resp?.data
if (data) {
// 更新缓存的 clientCode
if (data.clientCode || data.client_code) {
qrcodeClientCode = data.clientCode || data.client_code
}
// 服务端返回 token 或 loginToken 表示扫码登录成功
if (data.loginToken || data.token) {
qrcodeScanned.value = true
stopPolling()
setTimeout(() => doLoginWithToken(data.loginToken || data.token), 800)
return
}
// 更新状态
if (data.status === 'scanned' || data.scanned) {
qrcodeScanned.value = true
}
if (data.status === 'expired') {
qrcodeExpired.value = true
stopPolling()
return
}
if (data.qrCodeUrl || data.code) {
qrcodeUrl.value = data.code
? await generateQrDataUrl(data.code)
: data.qrCodeUrl
}
}
// 继续下一轮
poll()
} catch (err: any) {
if (pollingAborted || currentPollingVersion !== version) return
// 网络错误等,稍等后重试
setTimeout(poll, 3000)
}
}
poll()
}
let qrcodeClientCode = ''
/** 初次获取二维码 */
const fetchQrCode = async () => {
qrcodeLoading.value = true
qrcodeExpired.value = false
qrcodeScanned.value = false
qrcodeUrl.value = ''
qrcodeClientCode = ''
try {
const resp = await (userApi as any).getLoginWechatCode()
const data = resp?.data
if (data) {
qrcodeClientCode = data.clientCode || data.client_code
const code = data.code
qrcodeUrl.value = code
? await generateQrDataUrl(code)
: (data.qrCodeUrl || data.qr_code_url)
if (qrcodeClientCode) {
startPolling()
}
}
} catch {
qrcodeExpired.value = true
} finally {
qrcodeLoading.value = false
}
}
/** 手动刷新二维码 */
const refreshQrCode = () => {
stopPolling()
fetchQrCode()
}
/** Tab 切换 */
const switchTab = (tab: 'account' | 'qrcode') => {
if (tab === activeTab.value) return
activeTab.value = tab
if (tab === 'qrcode') {
fetchQrCode()
} else {
stopPolling()
}
}
onUnmounted(() => {
stopPolling()
})
</script>
<style lang="scss">
/* 全局覆盖 Element Plus 样式 */
.login-container {
.el-form-item__label {
padding-bottom: 4px;
font-weight: 500;
color: #606266;
}
.el-input__wrapper {
background-color: #f5f7fa;
box-shadow: none !important;
border: 1px solid #e4e7ed;
transition: all 0.3s;
height: 44px;
&:hover, &.is-focus {
border-color: #409eff;
background-color: #fff;
}
}
.el-input__inner {
height: 44px;
/* 让输入区域透明,使用外层 wrapper 的背景色,避免与前后缀颜色不一致 */
background-color: transparent;
border: none;
box-shadow: none !important;
/* 修复浏览器自动填充时的背景色问题 */
&:-webkit-autofill {
box-shadow: 0 0 0px 1000px transparent inset !important;
transition: background-color 5000s ease-in-out 0s;
}
}
/* 确保 prefix / suffix 区域也透明并垂直居中 */
.el-input__prefix,
.el-input__suffix {
background-color: transparent;
height: 100%;
display: flex;
align-items: center;
}
}
</style>
<style lang="scss" scoped>
.login-container {
min-height: 100vh;
width: 100%;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
.login-card {
width: 900px;
max-width: 100%;
min-height: 550px;
background: #fff;
border-radius: 16px;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
display: flex;
overflow: hidden;
}
.login-left-panel {
flex: 1;
background: linear-gradient(to bottom, #1890ff, #5c9cd8);
padding: 40px;
display: flex;
flex-direction: column;
justify-content: center;
color: #fff;
position: relative;
&::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: url('https://gw.alipayobjects.com/zos/rmsportal/TVirbqOXmUycLUXfInid.svg') no-repeat center;
background-size: cover;
opacity: 0.1;
}
.brand-info {
position: relative;
z-index: 1;
text-align: center;
.brand-logo {
font-size: 64px;
margin-bottom: 20px;
}
.brand-name {
font-size: 32px;
font-weight: 700;
margin-bottom: 12px;
letter-spacing: 2px;
}
.brand-desc {
font-size: 20px;
opacity: 0.8;
font-weight: 700;
}
}
}
.login-right-panel {
width: 450px;
padding: 40px 60px;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
.set-language {
position: absolute;
top: 20px;
right: 20px;
color: #606266;
}
.login-form {
width: 100%;
}
.title-container {
margin-bottom: 32px;
.title {
font-size: 24px;
font-weight: 600;
color: #303133;
margin-bottom: 8px;
}
.subtitle {
font-size: 14px;
color: #909399;
}
}
.submit-btn {
width: 100%;
height: 44px;
font-size: 16px;
margin-top: 12px;
border-radius: 4px;
}
.form-footer {
margin-top: 24px;
text-align: center;
font-size: 14px;
color: #606266;
.el-button--link {
padding: 0 4px;
}
}
.show-pwd {
cursor: pointer;
color: #909399;
&:hover {
color: #409eff;
}
}
// ---- 登录 Tab ----
.login-tabs-wrap {
width: 100%;
/* 固定登录和扫码面板高度,防止切换时抖动 */
.login-form,
.qrcode-panel {
height: 330px;
display: flex;
flex-direction: column;
}
}
.login-tabs {
display: flex;
border-bottom: 2px solid #f0f2f5;
margin-bottom: 24px;
.tab-btn {
flex: 1;
background: none;
border: none;
outline: none;
padding: 10px 0;
font-size: 15px;
color: #909399;
cursor: pointer;
position: relative;
transition: color 0.2s;
&.active {
color: #409eff;
font-weight: 600;
&::after {
content: '';
position: absolute;
bottom: -2px;
left: 10%;
width: 80%;
height: 2px;
background: #409eff;
border-radius: 2px;
}
}
&:hover:not(.active) {
color: #606266;
}
}
}
// ---- 微信扫码面板 ----
.qrcode-panel {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 8px 0 16px;
.qrcode-desc {
height: 18px; /* 固定描述文字高度 */
font-size: 13px;
color: #909399;
margin-bottom: 20px;
text-align: center;
line-height: 1.4;
}
.qrcode-box {
width: 200px;
height: 200px;
flex-shrink: 0; /* 防止尺寸被压缩 */
border: 1px solid #e4e7ed;
border-radius: 8px;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background: #fafafa;
.qrcode-img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.qrcode-placeholder {
width: 100%;
height: 100%;
background: #f5f7fa;
}
.qrcode-mask {
position: absolute;
inset: 0;
background: rgba(255, 255, 255, 0.92);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
z-index: 2;
.el-icon {
font-size: 36px;
color: #909399;
}
span {
font-size: 13px;
color: #606266;
}
small {
font-size: 12px;
color: #409eff;
}
&.scanned .el-icon {
color: #67c23a;
}
&.expired .el-icon {
color: #909399;
}
.loading-icon {
animation: rotating 1.5s linear infinite;
font-size: 32px;
color: #409eff;
}
}
}
.qrcode-waiting {
height: 18px; /* 固定底部提示文字高度 */
margin-top: 14px;
font-size: 13px;
color: #909399;
line-height: 1.4;
}
}
}
}
@keyframes rotating {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* 响应式适配 */
@media screen and (max-width: 768px) {
.login-card {
flex-direction: column;
width: 450px;
}
.login-left-panel {
display: none;
}
.login-right-panel {
width: 100%;
padding: 40px 30px;
}
}
</style>