import { onShow } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { fetchProfile } from '@/api/profile' import { useSmsCode } from '@/hooks/use-sms-code' import { SMS_CODE_SCENE } from '@/types/api' import { getErrorMessage } from '@/utils/api-error' import { isValidPhone, isValidSmsCode } from '@/utils/validate' import { verifyOldPhone } from './change-phone.api' function maskPhone(phone: string): string { const digits = phone.replace(/\D/g, '') if (digits.length < 7) return phone return digits.replace(/(\d{3})\d{4}(\d+)/, '$1****$2') } export function useChangePhoneVerify() { const phone = ref('') const code = ref('') const boundPhone = ref('') const loading = ref(false) const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneOld) const maskedBoundPhone = computed(() => maskPhone(boundPhone.value)) const subtitle = computed(() => { const masked = maskedBoundPhone.value if (!masked) return '请输入该账号绑定的原手机号,完成手机验证' return `请输入该账号绑定的原手机号${masked},完成手机验证` }) async function loadBoundPhone() { try { const profile = await fetchProfile() boundPhone.value = profile?.phonenumber || profile?.userName || '' } catch (err) { uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' }) } } function onSendCode() { sendCode(phone.value) } function onUnavailablePhone() { uni.showModal({ title: '原手机号不可用', content: '如原手机号已停用,请联系在线客服协助处理。', confirmText: '联系客服', success: (res) => { if (!res.confirm) return uni.navigateTo({ url: '/pages/mine/support/index' }) }, }) } 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 changeToken = await verifyOldPhone({ phone: phone.value, code: code.value }) if (!changeToken) { uni.showToast({ title: '验证失败,未获取换绑令牌', icon: 'none' }) return } uni.navigateTo({ url: `/pages/mine/change-phone/bind/index?changeToken=${encodeURIComponent(changeToken)}`, }) } catch (err) { uni.showToast({ title: getErrorMessage(err, '验证失败,请重试'), icon: 'none' }) } finally { loading.value = false } } onShow(() => { void loadBoundPhone() }) return { phone, code, counting, seconds, subtitle, onSendCode, onUnavailablePhone, nextStep, } }