Files
czzj-app/src/pages/mine/change-phone/bind/use-change-phone-bind.ts
2026-10-28 10:36:39 +08:00

99 lines
2.8 KiB
TypeScript

import { onLoad, onShow } from '@dcloudio/uni-app'
import { 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 { isSamePhone, isValidPhone, isValidSmsCode } from '@/utils/validate'
import { verifyNewPhone } from '../change-phone.api'
export function useChangePhoneBind() {
const phone = ref('')
const code = ref('')
const changeToken = ref('')
const boundPhone = ref('')
const loading = ref(false)
const { counting, seconds, sendCode } = useSmsCode(SMS_CODE_SCENE.changePhoneNew, {
getChangeToken: () => changeToken.value,
onChangeToken: (token) => {
changeToken.value = token
},
})
onLoad((query) => {
const raw = (query?.changeToken as string) || ''
changeToken.value = raw ? decodeURIComponent(raw) : ''
if (!changeToken.value) {
uni.showToast({ title: '请先完成原手机号验证', icon: 'none' })
setTimeout(() => uni.navigateBack(), 1500)
}
})
async function loadBoundPhone() {
try {
const profile = await fetchProfile()
boundPhone.value = profile?.phonenumber || profile?.userName || ''
} catch {
// 新号校验依赖当前绑定号;加载失败时仍走格式校验
}
}
function ensureNewPhoneDiffersFromBound(): boolean {
if (!isValidPhone(phone.value)) {
uni.showToast({ title: '请输入正确手机号', icon: 'none' })
return false
}
const bound = boundPhone.value.trim()
if (bound && isSamePhone(phone.value, bound)) {
uni.showToast({ title: '新手机号不能与当前手机号相同', icon: 'none' })
return false
}
return true
}
function onSendCode() {
if (!ensureNewPhoneDiffersFromBound()) return
sendCode(phone.value)
}
async function submit() {
if (!changeToken.value) {
uni.showToast({ title: '换绑令牌无效,请重新验证', icon: 'none' })
return
}
if (!ensureNewPhoneDiffersFromBound()) return
if (!isValidSmsCode(code.value)) {
uni.showToast({ title: '请输入验证码', icon: 'none' })
return
}
if (loading.value) return
loading.value = true
try {
await verifyNewPhone(changeToken.value, { phone: phone.value, code: code.value })
uni.showToast({ title: '手机号换绑成功', icon: 'success' })
setTimeout(() => {
uni.navigateBack({ delta: 2 })
}, 1200)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '换绑失败,请重试'), icon: 'none' })
} finally {
loading.value = false
}
}
onShow(() => {
void loadBoundPhone()
})
return {
phone,
code,
counting,
seconds,
onSendCode,
submit,
}
}