import { onShow } from '@dcloudio/uni-app' import { computed, ref } from 'vue' import { cancelAccount, logout } from '@/api/auth' import { fetchProfile } from '@/api/profile' import { getErrorMessage } from '@/utils/api-error' import { teardownMessageInbox } from '@/hooks/use-message-inbox' import { clearStoredToken } from '@/utils/auth-token' import type { PrivacySection } from './privacy.types' function maskPhone(phone?: string): string { const value = phone?.trim() || '' if (value.length < 7) return value || '未绑定' return `${value.slice(0, 3)}****${value.slice(-4)}` } export function usePrivacy() { const phone = ref('') const cancelAccountDialogVisible = ref(false) const cancelingAccount = ref(false) const sections = computed(() => [ { id: 'login', title: '登录安全', items: [ { id: 'password', title: '登录密码', desc: '上次修改:30天前', }, { id: 'phone', title: '绑定手机号', desc: maskPhone(phone.value), }, ], }, { id: 'device', title: '设备安全', items: [ { id: 'delete-account', title: '注销账号', desc: '永久删除账号和所有数据', danger: true, }, ], }, ]) async function loadProfile() { try { const profile = await fetchProfile() phone.value = profile?.phonenumber || profile?.userName || '' } catch (err) { uni.showToast({ title: getErrorMessage(err, '加载账号信息失败'), icon: 'none' }) } } function onItemTap(itemId: string) { if (itemId === 'password') { uni.navigateTo({ url: '/pages/forgot-password/index?from=privacy' }) return } if (itemId === 'phone') { uni.navigateTo({ url: '/pages/mine/change-phone/index' }) return } if (itemId === 'delete-account') { cancelAccountDialogVisible.value = true } } async function onConfirmCancelAccount() { if (cancelingAccount.value) return cancelingAccount.value = true try { await cancelAccount() teardownMessageInbox() clearStoredToken() uni.showToast({ title: '账号已注销', icon: 'success' }) uni.reLaunch({ url: '/pages/login/index' }) } catch (err) { uni.showToast({ title: getErrorMessage(err, '注销失败'), icon: 'none' }) } finally { cancelingAccount.value = false } } function onLogout() { uni.showModal({ title: '退出登录', content: '确定要退出当前账号吗?', success: (res) => { if (!res.confirm) return void (async () => { try { await logout() } catch (err) { uni.showToast({ title: getErrorMessage(err, '退出登录失败'), icon: 'none', }) } finally { teardownMessageInbox() clearStoredToken() uni.reLaunch({ url: '/pages/login/index' }) } })() }, }) } onShow(() => { void loadProfile() }) return { sections, cancelAccountDialogVisible, onItemTap, onLogout, onConfirmCancelAccount, } }