import { onLoad, onShow } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { fetchProfile } from '@/api/profile' import { useSmsCode } from '@/hooks/use-sms-code' import { getErrorMessage } from '@/utils/api-error' import { getStoredToken } from '@/utils/auth-token' import { isValidPhone, isValidSmsCode } from '@/utils/validate' import { SMS_CODE_SCENE } from '@/types/api' import { verifyForgetPasswordCode } from './forgot-password.api' export function useForgotPassword() { const phone = ref('') const code = ref('') const loading = ref(false) const fromPrivacy = ref(false) const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.reset) const pageTitle = computed(() => (fromPrivacy.value ? '修改登录密码' : '忘记密码')) onLoad((query) => { fromPrivacy.value = query?.from === 'privacy' }) async function loadBoundPhone() { if (!getStoredToken()) return try { const profile = await fetchProfile() const bound = profile?.phonenumber || profile?.userName || '' if (bound) { phone.value = bound } } catch { // 未登录或加载失败时保持手动输入 } } function onSendCode() { sendCode(phone.value) } async function nextStep() { if (!isValidPhone(phone.value)) { uni.showToast({ title: '请输入正确手机号', icon: 'none' }) return } if (!isValidSmsCode(code.value)) { uni.showToast({ title: '请输入验证码', icon: 'none' }) return } if (loading.value) return loading.value = true try { const res = await verifyForgetPasswordCode({ phone: phone.value, code: code.value }) if (!res.resetToken) { uni.showToast({ title: '验证失败,未获取重置令牌', icon: 'none' }) return } uni.navigateTo({ url: `/pages/change-password/index?resetToken=${encodeURIComponent(res.resetToken)}&from=${fromPrivacy.value ? 'privacy' : 'login'}`, }) } catch (err) { uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' }) } finally { loading.value = false } } onShow(() => { void loadBoundPhone() }) return { phone, code, counting, seconds, pageTitle, onSendCode, nextStep } }