Files
art-design/src/views/auth/login/index.vue
T
2025-09-17 15:10:28 +08:00

508 lines
16 KiB
Vue

<template>
<div class="login">
<LoginLeftView></LoginLeftView>
<div class="right-wrap">
<div class="top-right-wrap">
<!-- <div class="btn theme-btn" @click="toggleTheme">
<i class="iconfont-sys">
{{ isDark ? '&#xe6b5;' : '&#xe725;' }}
</i>
</div> -->
<!-- <ElDropdown @command="changeLanguage" popper-class="langDropDownStyle">
<div class="btn language-btn">
<i class="iconfont-sys icon-language">&#xe611;</i>
</div>
<template #dropdown>
<ElDropdownMenu>
<div v-for="lang in languageOptions" :key="lang.value" class="lang-btn-item">
<ElDropdownItem
:command="lang.value"
:class="{ 'is-selected': locale === lang.value }"
>
<span class="menu-txt">{{ lang.label }}</span>
<i v-if="locale === lang.value" class="iconfont-sys icon-check">&#xe621;</i>
</ElDropdownItem>
</div>
</ElDropdownMenu>
</template>
</ElDropdown> -->
</div>
<div class="header">
<ArtLogo class="icon" />
<h1>{{ systemName }}</h1>
</div>
<div class="login-wrap">
<div class="form">
<!-- 登录方式切换 tab -->
<div class="login-type-tabs">
<span
:class="{ active: activeLoginType === 'password' }"
@click="activeLoginType = 'password'"
>账号密码登录</span
>
<span
:class="{ active: activeLoginType === 'qrcode' }"
@click="activeLoginType = 'qrcode'"
>飞书登录</span
>
</div>
<div v-if="activeLoginType === 'password'">
<ElForm
ref="formRef"
:model="formData"
:rules="rules"
@keyup.enter="handleSubmit"
style="margin-top: 25px"
>
<ElFormItem prop="username" label="账号">
<ElInput
:placeholder="$t('login.placeholder[0]')"
v-model.trim="formData.username"
/>
</ElFormItem>
<ElFormItem prop="password" label="密码">
<ElInput
:placeholder="$t('login.placeholder[1]')"
v-model.trim="formData.password"
type="password"
radius="8px"
autocomplete="off"
show-password
/>
</ElFormItem>
<ElFormItem prop="company" label="公司">
<ElSelect v-model="formData.company" class="account-select" @change="changeCompany">
<ElOption
v-for="account in companyList"
:key="account.id"
:label="account.name"
:value="account.id"
>
<span>{{ account.name }}</span>
</ElOption>
</ElSelect>
</ElFormItem>
<ElFormItem prop="company" label="系统">
<ElSelect v-model="formData.systems" class="account-select" @change="changesystems">
<ElOption
v-for="account in systemsList"
:key="account.id"
:label="account.name"
:value="account.id"
>
<span>{{ account.name }}</span>
</ElOption>
</ElSelect>
</ElFormItem>
<div class="drag-verify">
<div class="drag-verify-content" :class="{ error: !isPassing && isClickPass }">
<ArtDragVerify
ref="dragVerify"
v-model:value="isPassing"
:width="width < 500 ? 260 : 380"
:text="$t('login.sliderText')"
textColor="var(--art-gray-800)"
:successText="$t('login.sliderSuccessText')"
:progressBarBg="getCssVar('--el-color-primary')"
background="var(--art-gray-200)"
handlerBg="var(--art-main-bg-color)"
/>
</div>
<p class="error-text" :class="{ 'show-error-text': !isPassing && isClickPass }">{{
$t('login.placeholder[2]')
}}</p>
</div>
<div class="login-bottom-row">
<p>
{{ $t('login.noAccount') }}
<RouterLink :to="RoutesAlias.Register" style="color: #5d87ff">{{
$t('login.register')
}}</RouterLink>
</p>
<ElCheckbox v-model="formData.rememberPassword">{{
$t('login.rememberPwd')
}}</ElCheckbox>
</div>
<div style="margin-top: 30px">
<ElButton
class="login-btn"
type="primary"
@click="handleSubmit"
:loading="loading"
v-ripple
>
{{ $t('login.btnText') }}
</ElButton>
</div>
</ElForm>
</div>
<div v-else>
<ElForm :model="formData" style="margin-top: 25px">
<ElFormItem prop="company" label="公司">
<ElSelect v-model="formData.company" class="account-select" @change="changeCompany">
<ElOption
v-for="account in companyList"
:key="account.id"
:label="account.name"
:value="account.id"
>
<span>{{ account.name }}</span>
</ElOption>
</ElSelect>
</ElFormItem>
<ElFormItem prop="company" label="系统">
<ElSelect v-model="formData.systems" class="account-select" @change="changesystems">
<ElOption
v-for="account in systemsList"
:key="account.id"
:label="account.name"
:value="account.id"
>
<span>{{ account.name }}</span>
</ElOption>
</ElSelect>
</ElFormItem>
</ElForm>
<div class="qrcode-login" v-if="!isInFeishu">
<div id="login_container"></div>
<p class="qrcode-tip">请使用飞书App扫码登录</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import AppConfig from '@/config'
import { RoutesAlias } from '@/router/routesAlias'
import { ElNotification, ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { HOME_PAGE } from '@/router/routesAlias'
import { getCssVar } from '@/utils/ui'
import { languageOptions } from '@/locales'
import { LanguageEnum, SystemThemeEnum } from '@/enums/appEnum'
import { useI18n } from 'vue-i18n'
import { HttpError } from '@/utils/http/error'
import { onMounted, ref, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
defineOptions({ name: 'Login' })
const { t } = useI18n()
import { useSettingStore } from '@/store/modules/setting'
import type { FormInstance, FormRules } from 'element-plus'
const settingStore = useSettingStore()
const { systemThemeType } = storeToRefs(settingStore)
const dragVerify = ref()
const userStore = useUserStore()
const router = useRouter()
const isPassing = ref(false)
const isClickPass = ref(false)
const activeLoginType = ref<'password' | 'qrcode'>('qrcode')
const isInFeishu = /Lark|Feishu/i.test(navigator.userAgent)
// const isInFeishu = true;
const systemName = AppConfig.systemInfo.name
const formRef = ref<FormInstance>()
const companyid = ref('')
companyid.value = useUserStore().companyid
const systemsid = ref('')
systemsid.value = useUserStore().systemsid
const iscompany = ref(false)
const { companyabbr, systemsabbr } = useUserStore()
//获取公司 getCompanyList
const companyList = ref<any>()
//系统
const systemsList = ref<any>()
const feishuresponse = ref()
const formData = reactive({
account: '',
systems: useUserStore().systemsid ? Number(useUserStore().systemsid) : '',
company: useUserStore().companyid ? Number(useUserStore().companyid) : '',
username: '',
password: '',
rememberPassword: true
})
const rules = computed<FormRules>(() => ({
username: [{ required: true, message: t('login.placeholder[0]'), trigger: 'blur' }],
password: [{ required: true, message: t('login.placeholder[1]'), trigger: 'blur' }],
company: [{ required: true, message: t('login.placeholder[3]'), trigger: 'blur' }]
}))
const loading = ref(false)
const { width } = useWindowSize()
const getcompanyList = async () => {
const response = await UserService.getCompanyList()
companyList.value = response || []
}
const getsystemsList = async () => {
const response = await UserService.getsystemsList()
systemsList.value = response || []
}
// 切换语言
const { locale } = useI18n()
const changeLanguage = (lang: LanguageEnum) => {
if (locale.value === lang) return
locale.value = lang
userStore.setLanguage(lang)
}
const getfeishuAppList = async () => {
feishuresponse.value = await UserService.getfeishuAppList({
corp_id: useUserStore().companyid,
system_id: useUserStore().systemsid
})
if (activeLoginType.value == 'qrcode') {
feishulogin()
}
}
//切换系统
const changesystems = (systems: any) => {
const systemsdata = systemsList.value.find((c: any) => c.id === systems)
systemsid.value = systems
userStore.setSystems(systems, systemsdata?.code)
if (useUserStore().companyid && systemsid.value) {
getfeishuAppList()
}
}
//切换公司
const changeCompany = (company: any) => {
// if (companyid.value === company) return
const companyt = companyList.value.find((c: any) => c.id === company)
companyid.value = company
iscompany.value = company
userStore.setCompany(company, companyt?.abbr)
if (companyid.value && systemsid.value) {
getfeishuAppList()
}
}
if (companyabbr != '' && systemsabbr != '') {
iscompany.value = true
getfeishuAppList()
}
const feishulogin = async () => {
userStore.setLoginType('feishu')
if (isInFeishu) {
feishuSubmit()
// 飞书特定的逻辑
} else {
// 普通浏览器的逻辑
await nextTick()
// 等待 SDK 加载
const waitForQRLogin = () =>
new Promise<void>((resolve) => {
const check = () => {
// @ts-expect-error
if (window.QRLogin) resolve()
else setTimeout(check, 100)
}
check()
})
await waitForQRLogin()
// @ts-ignore
const container = document.getElementById('login_container')
if (container) container.innerHTML = ''
// @ts-ignore
// 飞书二维码登录参数(请替换为你的实际参数)
const fclient_id = feishuresponse.value?.app_id
const redirect_uri = feishuresponse.value?.r_url
const state = feishuresponse.value?.state
const feishuGotoUrl = 'https://passport.feishu.cn/suite/passport/oauth/authorize?client_id='+fclient_id+'&redirect_uri='+redirect_uri+'&response_type=code&state='+state;
// @ts-ignore
const QRLoginObj = window.QRLogin({
id: 'login_container',
goto: feishuGotoUrl,
width: '250',
height: '250',
style: 'width:350px;height:270px;border:none'
})
const handleMessage = function (event: MessageEvent) {
if (QRLoginObj.matchOrigin(event.origin) && QRLoginObj.matchData(event.data)) {
const loginTmpCode = event.data.tmp_code
window.location.href = `${feishuGotoUrl}&tmp_code=${loginTmpCode}`
}
}
window.addEventListener('message', handleMessage, false)
}
}
watch(
activeLoginType as import('vue').Ref<string>,
async (val) => {
if (val === 'qrcode') {
userStore.setLoginType('feishu')
if (companyid.value != '') {
feishulogin()
}
} else {
userStore.setLoginType('upwd')
}
},
{ immediate: true }
)
//飞书登录
const feishuSubmit = async () => {
try {
const { auth_url } = await UserService.getfeishuscope()
window.location.href = auth_url
} catch (error) {
ElMessage.error('登录失败,请稍后重试')
} finally {
resetDragVerify()
}
}
// 登录
const handleSubmit = async () => {
if (!formRef.value) return
try {
// 表单验证
const valid = await formRef.value.validate()
if (!valid) return
// 拖拽验证
if (!isPassing.value) {
isClickPass.value = true
return
}
loading.value = true
// 登录请求
const { username, password } = formData
const { data } = await UserService.login({
account: username,
password
})
// 验证token
if (!data.access_token) {
throw new Error('Login failed - no token received')
}
// 存储token和用户信息
userStore.setToken(data.access_token, data.refresh_token, data.expires_in)
const userInfo = await UserService.getUserInfo()
userStore.setUserInfo(userInfo)
userStore.setLoginStatus(true)
userStore.sethome_page(data.home_url)
localStorage.setItem('home_page', data.home_url)
// 登录成功处理
showLoginSuccessNotice()
router.push(data.home_url)
} catch (error) {
// 处理 HttpError
if (error instanceof HttpError) {
// console.log(error.code)
} else {
// 处理非 HttpError
ElMessage.error('登录失败,请稍后重试')
console.error('[Login] Unexpected error:', error)
}
} finally {
loading.value = false
resetDragVerify()
}
}
// 重置拖拽验证
const resetDragVerify = () => {
dragVerify.value.reset()
}
// 登录成功提示
const showLoginSuccessNotice = () => {
setTimeout(() => {
ElNotification({
title: t('login.success.title'),
type: 'success',
duration: 2500,
zIndex: 10000,
message: `${t('login.success.message')}, ${systemName}!`
})
}, 150)
}
const route = useRoute()
onMounted(() => {
getcompanyList()
getsystemsList()
// 自动读取 query 参数并存入 userStore
const companyid = Array.isArray(route.query.corp_id)
? route.query.corp_id[0]
: route.query.corp_id
const companyabbr = Array.isArray(route.query.corp_abbr)
? route.query.corp_abbr[0]
: route.query.corp_abbr
// const system_id = Array.isArray(route.query.system_id)
// ? route.query.system_id[0]
// : route.query.system_id
// const system_code = Array.isArray(route.query.system_code)
// ? route.query.system_code[0]
// : route.query.system_code
if (companyid) {
userStore.setCompany(companyid as string, (companyabbr as string) || '')
formData.company = Number(companyid)
}
// if (system_id) {
// userStore.setSystems(companyid as string, (system_code as string) || '')
// formData.systems = Number(system_id)
// }
// 只有两个 id 都有值时才调用
if (companyid && systemsid.value) {
getfeishuAppList()
}
})
// 切换主题
import { useTheme } from '@/composables/useTheme'
import { UserService } from '@/api/usersApi'
const toggleTheme = () => {
let { LIGHT, DARK } = SystemThemeEnum
useTheme().switchThemeStyles(systemThemeType.value === LIGHT ? DARK : LIGHT)
}
</script>
<style lang="scss" scoped>
@use './index';
.login-type-tabs {
display: flex;
justify-content: center;
margin-bottom: 20px;
span {
padding: 8px 24px;
cursor: pointer;
border-bottom: 2px solid transparent;
&.active {
color: #409eff;
border-bottom: 2px solid #409eff;
}
}
}
.qrcode-login {
display: flex;
flex-direction: column;
align-items: center;
.qrcode-tip {
margin-top: 16px;
color: #888;
}
}
.login-bottom-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 14px;
// margin-top: 16px;
}
</style>