Files
JayuCloud/JY-Artist-Frontend/src/views/PasswordSettingsView.vue
T
2026-06-29 23:26:43 +08:00

344 lines
11 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="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>设置密码</h1>
<div class="empty"></div>
</header>
<div class="password-form">
<a-card :bordered="false" class="form-card">
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleSubmit"
>
<a-form-item label="手机号">
<a-input :value="userPhone || '未绑定手机号'" disabled size="large" />
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="formState.verificationCode"
placeholder="请输入验证码"
size="large"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !userPhone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item label="新密码" name="password">
<a-input-password
v-model:value="formState.password"
placeholder="请输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: var(--text-secondary)" />
</template>
</a-input-password>
<div class="password-tip">
密码长度至少 8 位,且需包含字母和数字
</div>
</a-form-item>
<a-form-item label="确认密码" name="confirmPassword">
<a-input-password
v-model:value="formState.confirmPassword"
placeholder="请再次输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: var(--text-secondary)" />
</template>
</a-input-password>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
block
:loading="loading"
>
确认设置
</a-button>
</a-form-item>
</a-form>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
/**
* PasswordSettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, LockOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import DraftActions from '@/components/DraftActions.vue'
import { userApi } from '@/api/user'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { runWithGlobalLoading } from '@/utils/action-loading'
/**
* Purpose: router supports PasswordSettingsView.vue by holding or executing the router page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const router = useRouter()
/**
* Purpose: formRef supports PasswordSettingsView.vue by holding or executing the form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
/**
* Purpose: userInfo supports PasswordSettingsView.vue by holding or executing the user info page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const userInfo = ref<{ phone?: string } | null>(null)
/**
* Purpose: draftSavedAt supports PasswordSettingsView.vue by holding or executing the draft saved at page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const draftSavedAt = ref<number | null>(null)
let countdownTimer: ReturnType<typeof setInterval> | null = null
/**
* Purpose: formState supports PasswordSettingsView.vue by holding or executing the form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formState = reactive({
verificationCode: '',
password: '',
confirmPassword: ''
})
/**
* Purpose: draftKey supports PasswordSettingsView.vue by holding or executing the draft key page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const draftKey = buildDraftStorageKey('password-settings', 'set-password')
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<typeof formState>(draftKey, 'session')
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(draftKey, { ...formState }, 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(draftKey, 'session')
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/** userPhone is a reactive state variable used by the template and event handlers. */
const userPhone = computed(() => userInfo.value?.phone || '')
/** validateConfirmPassword is a local helper used by this page script. */
const validateConfirmPassword = (_rule: any, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
}
return Promise.resolve()
}
const formRules: Record<string, Rule[]> = {
verificationCode: [
{ required: true, message: '请输入验证码', trigger: 'blur' },
{ pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少8位', trigger: 'blur' },
{ pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
],
confirmPassword: [
{ required: true, message: '请确认新密码', trigger: 'blur' },
{ validator: validateConfirmPassword, trigger: 'blur' }
]
}
/** startCountdown is a local helper used by this page script. */
const startCountdown = () => {
countdown.value = 60
if (countdownTimer) {
clearInterval(countdownTimer)
}
countdownTimer = setInterval(() => {
countdown.value -= 1
if (countdown.value <= 0 && countdownTimer) {
clearInterval(countdownTimer)
countdownTimer = null
}
}, 1000)
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as { phone?: string }
} catch (error: any) {
console.error('获取用户信息失败:', error)
message.error(error.message || '获取用户信息失败')
}
}
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: userPhone.value,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error: any) {
console.error('发送验证码失败:', error)
message.error(error.message || '发送验证码失败')
}
}
/** handleSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSubmit = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
loading.value = true
await runWithGlobalLoading(() => userApi.updatePassword({
password: formState.password,
verificationCode: formState.verificationCode
}))
message.success('密码设置成功')
handleClearDraft(false)
localStorage.removeItem('needSetPassword')
router.push('/profile')
} catch (error: any) {
console.error('设置密码失败:', error)
message.error(error.message || '设置密码失败')
} finally {
loading.value = false
}
}
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
onMounted(() => {
fetchUserInfo()
restoreDraft()
})
onUnmounted(() => {
if (countdownTimer) {
clearInterval(countdownTimer)
}
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: var(--theme-page-bg);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: var(--theme-card-bg);
border-bottom: 1px solid var(--theme-border);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.password-form {
padding: 15px;
}
.form-card {
border-radius: 16px;
overflow: hidden;
background: var(--theme-card-bg);
}
.password-tip {
margin-top: 8px;
color: var(--text-secondary);
font-size: 12px;
}
</style>