整合api请求、添加购买会员卡页面、登陆页面

This commit is contained in:
future
2026-06-23 22:17:53 +08:00
parent 1c547a717e
commit 8d8c823616
70 changed files with 7666 additions and 2656 deletions
@@ -74,84 +74,83 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getBodyTestHistory, getCompareData } from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return {
records: [],
recordA: null,
recordB: null,
compareData: null
}
},
computed: {
scoreDiff() {
if (!this.compareData) return 0
return this.compareData.recordA.score - this.compareData.recordB.score
}
},
onShow() {
const store = loadMemberStore()
this.records = getBodyTestHistory(store)
if (this.records.length >= 2 && !this.recordA) {
this.recordA = this.records[0]
this.recordB = this.records[1]
this.refreshCompare()
}
},
methods: {
onBack() {
goBackOrTab(PAGE.BODY_TEST_HISTORY)
},
pickRecord(which) {
const labels = this.records.map(
(r) => `${r.date} · ${r.score}分 · ${r.gradeLabel}`
)
uni.showActionSheet({
itemList: labels,
success: (res) => {
const picked = this.records[res.tapIndex]
if (which === 'a') this.recordA = picked
else this.recordB = picked
this.refreshCompare()
}
})
},
refreshCompare() {
if (!this.recordA || !this.recordB) {
this.compareData = null
return
}
if (this.recordA.id === this.recordB.id) {
uni.showToast({ title: '请选择两条不同记录', icon: 'none' })
this.compareData = null
return
}
const store = loadMemberStore()
this.compareData = getCompareData(store, this.recordA.id, this.recordB.id)
},
formatDiff(diff, key) {
const sign = diff > 0 ? '+' : ''
const units = { bodyFat: '%', weight: '', bmi: '', muscleMass: '', visceralFat: '', bmr: '' }
return `${sign}${diff}${units[key] || ''}`
},
diffColor(row) {
const lowerBetter = ['weight', 'bodyFat', 'visceralFat'].includes(row.key)
const good = lowerBetter ? row.diff < 0 : row.diff > 0
if (row.diff === 0) return '#8A99B4'
return good ? '#2ECC71' : '#F39C12'
}
const records = ref([])
const recordA = ref(null)
const recordB = ref(null)
const compareData = ref(null)
const scoreDiff = computed(() => {
if (!compareData.value) return 0
return compareData.value.recordA.score - compareData.value.recordB.score
})
function refreshFromStore() {
const store = loadMemberStore()
records.value = getBodyTestHistory(store)
if (records.value.length >= 2 && !recordA.value) {
recordA.value = records.value[0]
recordB.value = records.value[1]
refreshCompare()
}
}
function onBack() {
goBackOrTab(PAGE.BODY_TEST_HISTORY)
}
function pickRecord(which) {
const labels = records.value.map(
(r) => `${r.date} · ${r.score}分 · ${r.gradeLabel}`
)
uni.showActionSheet({
itemList: labels,
success: (res) => {
const picked = records.value[res.tapIndex]
if (which === 'a') recordA.value = picked
else recordB.value = picked
refreshCompare()
}
})
}
function refreshCompare() {
if (!recordA.value || !recordB.value) {
compareData.value = null
return
}
if (recordA.value.id === recordB.value.id) {
uni.showToast({ title: '请选择两条不同记录', icon: 'none' })
compareData.value = null
return
}
const store = loadMemberStore()
compareData.value = getCompareData(store, recordA.value.id, recordB.value.id)
}
function formatDiff(diff, key) {
const sign = diff > 0 ? '+' : ''
const units = { bodyFat: '%', weight: '', bmi: '', muscleMass: '', visceralFat: '', bmr: '' }
return `${sign}${diff}${units[key] || ''}`
}
function diffColor(row) {
const lowerBetter = ['weight', 'bodyFat', 'visceralFat'].includes(row.key)
const good = lowerBetter ? row.diff < 0 : row.diff > 0
if (row.diff === 0) return '#8A99B4'
return good ? '#2ECC71' : '#F39C12'
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -73,7 +73,8 @@
</view>
</template>
<script>
<script setup>
import { ref } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage, goBackOrTab } from '@/common/constants/routes.js'
import {
@@ -81,52 +82,52 @@ import {
persistMemberStore
} from '@/common/memberInfo/store.js'
import {
connectBodyTestDevice,
bodyTestMock
connectBodyTestDevice
} from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return {
device: {},
steps: bodyTestMock.connectSteps,
searching: false,
connected: false,
searchHint: '请保持手机蓝牙已开启'
}
},
onShow() {
const store = loadMemberStore()
this.device = { ...store.bodyTest.device }
this.connected = store.bodyTest.device.connected
},
methods: {
onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
},
searchDevice() {
if (this.searching) return
this.searching = true
this.searchHint = '发现 InBody 270…'
setTimeout(() => {
const store = loadMemberStore()
connectBodyTestDevice(store)
persistMemberStore(store)
this.device = { ...store.bodyTest.device }
this.connected = true
this.searching = false
uni.showToast({ title: '设备已连接', icon: 'success' })
}, 1800)
},
goMeasuring() {
navigateToPage(PAGE.BODY_TEST_MEASURING)
}
}
const device = ref({})
const steps = ref([
{ step: 1, text: '打开体测仪电源' },
{ step: 2, text: '站在体测仪上' },
{ step: 3, text: '等待测量完成' }
])
const searching = ref(false)
const connected = ref(false)
const searchHint = ref('请保持手机蓝牙已开启')
function refreshFromStore() {
const store = loadMemberStore()
device.value = { ...store.bodyTest.device }
connected.value = store.bodyTest.device.connected
}
function onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
}
function searchDevice() {
if (searching.value) return
searching.value = true
searchHint.value = '发现 InBody 270…'
setTimeout(() => {
const store = loadMemberStore()
connectBodyTestDevice(store)
persistMemberStore(store)
device.value = { ...store.bodyTest.device }
connected.value = true
searching.value = false
uni.showToast({ title: '设备已连接', icon: 'success' })
}, 1800)
}
function goMeasuring() {
navigateToPage(PAGE.BODY_TEST_MEASURING)
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -59,53 +59,52 @@
</view>
</template>
<script>
<script setup>
import { ref, computed, watch } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getBodyTestHistory, getBodyTestYears, getBodyTestChangeBadge } from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return { activeYear: 'all', years: [], allRecords: [] }
},
computed: {
records() {
const list = this.activeYear === 'all'
? this.allRecords
: this.allRecords.filter((r) => r.date.startsWith(this.activeYear))
return list.map((item, index) => {
const previous = list[index + 1]
return {
...item,
changeBadge: getBodyTestChangeBadge(item, previous)
}
})
const activeYear = ref('all')
const years = ref([])
const allRecords = ref([])
const records = computed(() => {
const list = activeYear.value === 'all'
? allRecords.value
: allRecords.value.filter((r) => r.date.startsWith(activeYear.value))
return list.map((item, index) => {
const previous = list[index + 1]
return {
...item,
changeBadge: getBodyTestChangeBadge(item, previous)
}
},
watch: {
activeYear() { this.loadList() }
},
onShow() { this.loadList() },
methods: {
loadList() {
const store = loadMemberStore()
this.years = getBodyTestYears(store)
this.allRecords = getBodyTestHistory(store)
},
onBack() { goBackOrTab(PAGE.MEMBER) },
viewReport(item) {
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${item.id}`)
},
goCompare() {
navigateToPage(PAGE.BODY_TEST_COMPARE)
}
}
})
})
function loadList() {
const store = loadMemberStore()
years.value = getBodyTestYears(store)
allRecords.value = getBodyTestHistory(store)
}
function onBack() { goBackOrTab(PAGE.MEMBER) }
function viewReport(item) {
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${item.id}`)
}
function goCompare() {
navigateToPage(PAGE.BODY_TEST_COMPARE)
}
watch(activeYear, () => { loadList() })
loadList()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -196,15 +195,7 @@ export default {
background: rgba(46, 204, 113, 0.12);
}
.mi-timeline-card__badge--good text {
font-size: 10px;
color: var(--success-green, #2ECC71);
font-weight: 600;
}
.mi-timeline-card__badge--warn text {
font-size: 10px;
color: var(--warning-amber, #F39C12);
font-weight: 600;
.mi-timeline-card__badge--warn {
background: rgba(243, 156, 18, 0.12);
}
</style>
@@ -1,47 +1,28 @@
<template>
<view class="scroll-container theme-light">
<view class="bt-page">
<MemberInfoSubNav title="智能体测" @back="goBack" />
<view class="bt-page__action-bar bt-page__action-bar--end">
<text
class="bt-page__action-link"
hover-class="mi-tap--hover"
:hover-stay-time="150"
@tap="goSettings"
>
体测设置
</text>
</view>
<MemberInfoSubNav title="体测" @back="goBack" />
<view class="bt-page__body">
<view class="bt-hero">
<view class="bt-hero__top">
<text class="bt-hero__label">最新体测评分</text>
<view class="bt-hero__badge">
<text class="bt-hero__badge-text">{{ latest?.status || '暂无数据' }}</text>
<view v-if="latest" class="bt-hero">
<view class="bt-hero__time">
<image class="bt-hero__time-icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/clock.png" mode="aspectFit" />
<text class="bt-hero__time-text">{{ latest.testTime }}</text>
</view>
<view class="bt-hero__metrics">
<view
v-for="m in previewMetrics"
:key="m.key"
class="bt-hero__metric"
>
<text class="bt-hero__metric-value">{{ m.value }}</text>
<text class="bt-hero__metric-label">{{ m.label }}</text>
</view>
</view>
<view class="bt-hero__score-row">
<text class="bt-hero__score">{{ latest?.score ?? '--' }}</text>
<text class="bt-hero__grade">{{ latest?.grade ?? '' }} {{ latest?.gradeLabel ?? '' }}</text>
</view>
<text class="bt-hero__meta">
{{ latest ? `最近测量 · ${latest.date} ${latest.time}` : '完成首次体测,获取健康画像' }}
</text>
<view class="bt-hero__actions">
<view
class="bt-btn bt-btn--primary"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap="startMeasure"
>
<image class="bt-btn__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/activity.png" mode="aspectFit" />
<text class="bt-btn__text">开始体测</text>
</view>
<view
v-if="latest"
class="bt-btn bt-btn--ghost"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap="viewLatestReport"
>
<text class="bt-btn__text">查看报告</text>
@@ -50,142 +31,145 @@
</view>
<view class="bt-card">
<text class="bt-card__title">设备状态</text>
<view class="bt-device">
<view class="bt-device__icon-wrap">
<image class="bt-device__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/mappin2.png" mode="aspectFit" />
</view>
<view class="bt-device__info">
<text class="bt-device__name">{{ device.name }}</text>
<text
class="bt-device__status"
:class="{ 'bt-device__status--on': device.connected }"
>
{{ deviceStatusText }}
</text>
</view>
<view class="bt-card__header">
<text class="bt-card__title">快捷操作</text>
</view>
<view class="bt-quick-grid">
<view
class="bt-device__dot"
:class="{ 'bt-device__dot--on': device.connected }"
></view>
v-for="link in quickLinks"
:key="link.key"
class="bt-quick-item"
hover-class="mi-tap--hover"
:hover-stay-time="150"
@tap="onQuickLink(link.key)"
>
<image class="bt-quick-item__icon" :src="link.icon" mode="aspectFit" />
<text class="bt-quick-item__label">{{ link.label }}</text>
</view>
</view>
</view>
<view class="bt-card">
<text class="bt-card__title">快捷入口</text>
<view class="bt-grid">
<view class="bt-card__header">
<text class="bt-card__title">开始体测</text>
</view>
<view class="bt-device-status" @tap="startMeasure">
<view class="bt-device-status__icon-wrap">
<image
class="bt-device-status__icon"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/bluetooth.png"
mode="aspectFit"
/>
</view>
<view class="bt-device-status__info">
<text class="bt-device-status__name">{{ device.name || '体脂秤' }}</text>
<text class="bt-device-status__text">{{ deviceStatusText }}</text>
</view>
<image
class="bt-device-status__arrow"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/rightarrow.png"
mode="aspectFit"
/>
</view>
<view class="bt-card__actions">
<view
v-for="item in quickLinks"
:key="item.key"
class="bt-grid__item"
hover-class="mi-tap--hover"
class="bt-btn bt-btn--primary"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap="onQuickLink(item.key)"
@tap="startMeasure"
>
<image class="bt-grid__icon" :src="item.icon" mode="aspectFit" />
<text class="bt-grid__label">{{ item.label }}</text>
<text class="bt-btn__text">{{ device.connected ? '开始测量' : '连接设备' }}</text>
</view>
</view>
</view>
<view v-if="latest" class="bt-card">
<text class="bt-card__title">核心指标概览</text>
<view class="bt-metrics">
<view
v-for="m in previewMetrics"
:key="m.key"
class="bt-metric"
>
<text class="bt-metric__value">{{ m.value }}</text>
<text class="bt-metric__label">{{ m.label }}</text>
</view>
</view>
<view class="bt-settings-link" @tap="goSettings">
<text class="bt-settings-link__text">体测设置</text>
<image class="bt-settings-link__arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/rightarrow.png" mode="aspectFit" />
</view>
</view>
</view>
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { PAGE, navigateToPage, backToMemberCenter } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getLatestBodyTestRecord } from '@/common/memberInfo/bodyTestStore.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
latest: null,
device: {},
quickLinks: [
{ key: 'history', label: '历史记录', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/clock.png' },
{ key: 'compare', label: '历史对比', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/trendingdown.png' },
{ key: 'trend', label: '趋势分析', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/activity.png' },
{ key: 'report', label: '体测报告', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/filetext.png' }
]
}
},
computed: {
deviceStatusText() {
if (this.device.connected) {
return `已连接 · 电量 ${this.device.battery}%`
}
return '未连接 · 点击开始体测进行配对'
},
previewMetrics() {
if (!this.latest?.metrics) return []
const m = this.latest.metrics
return [
{ key: 'weight', label: '体重(kg)', value: m.weight },
{ key: 'bmi', label: 'BMI', value: m.bmi },
{ key: 'bodyFat', label: '体脂率(%)', value: m.bodyFat },
{ key: 'muscleMass', label: '肌肉量(kg)', value: m.muscleMass }
]
}
},
onShow() {
this.refreshFromStore()
},
methods: {
refreshFromStore() {
const store = loadMemberStore()
this.latest = getLatestBodyTestRecord(store)
this.device = { ...store.bodyTest.device }
},
startMeasure() {
const store = loadMemberStore()
if (store.bodyTest.device.connected) {
navigateToPage(PAGE.BODY_TEST_MEASURING)
} else {
navigateToPage(PAGE.BODY_TEST_CONNECT)
}
},
viewLatestReport() {
if (!this.latest) return
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${this.latest.id}`)
},
goSettings() {
navigateToPage(PAGE.BODY_TEST_SETTINGS)
},
onQuickLink(key) {
const routes = {
history: PAGE.BODY_TEST_HISTORY,
compare: PAGE.BODY_TEST_COMPARE,
trend: PAGE.BODY_TEST_TREND,
report: this.latest
? `${PAGE.BODY_TEST_REPORT}?id=${this.latest.id}`
: PAGE.BODY_TEST_HISTORY
}
navigateToPage(routes[key] || PAGE.BODY_TEST_HOME)
}
const latest = ref(null)
const device = ref({})
const quickLinks = ref([
{ key: 'history', label: '历史记录', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/clock.png' },
{ key: 'compare', label: '历史对比', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/trendingdown.png' },
{ key: 'trend', label: '趋势分析', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/activity.png' },
{ key: 'report', label: '体测报告', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/filetext.png' }
])
const deviceStatusText = computed(() => {
if (device.value.connected) {
return `已连接 · 电量 ${device.value.battery}%`
}
return '未连接 · 点击开始体测进行配对'
})
const previewMetrics = computed(() => {
if (!latest.value?.metrics) return []
const m = latest.value.metrics
return [
{ key: 'weight', label: '体重(kg)', value: m.weight },
{ key: 'bmi', label: 'BMI', value: m.bmi },
{ key: 'bodyFat', label: '体脂率(%)', value: m.bodyFat },
{ key: 'muscleMass', label: '肌肉量(kg)', value: m.muscleMass }
]
})
function refreshFromStore() {
const store = loadMemberStore()
latest.value = getLatestBodyTestRecord(store)
device.value = { ...store.bodyTest.device }
}
function goBack() {
backToMemberCenter()
}
function startMeasure() {
const store = loadMemberStore()
if (store.bodyTest.device.connected) {
navigateToPage(PAGE.BODY_TEST_MEASURING)
} else {
navigateToPage(PAGE.BODY_TEST_CONNECT)
}
}
function viewLatestReport() {
if (!latest.value) return
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${latest.value.id}`)
}
function goSettings() {
navigateToPage(PAGE.BODY_TEST_SETTINGS)
}
function onQuickLink(key) {
const routes = {
history: PAGE.BODY_TEST_HISTORY,
compare: PAGE.BODY_TEST_COMPARE,
trend: PAGE.BODY_TEST_TREND,
report: latest.value
? `${PAGE.BODY_TEST_REPORT}?id=${latest.value.id}`
: PAGE.BODY_TEST_HISTORY
}
navigateToPage(routes[key] || PAGE.BODY_TEST_HOME)
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -38,7 +38,8 @@
</view>
</template>
<script>
<script setup>
import { ref, computed, onUnmounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage, goBackOrTab } from '@/common/constants/routes.js'
import {
@@ -57,108 +58,106 @@ const PHASES = [
{ until: 100, hint: '即将完成', text: '生成健康报告中…' }
]
export default {
components: { MemberInfoSubNav },
data() {
return {
progress: 0,
liveMetrics: {},
timer: null,
finished: false
}
},
computed: {
ringRotation() {
return -90 + (this.progress / 100) * 360
},
phaseHint() {
const phase = PHASES.find((p) => this.progress <= p.until)
return phase?.hint || '完成'
},
statusText() {
const phase = PHASES.find((p) => this.progress <= p.until)
return phase?.text || '测量完成'
},
liveDisplay() {
const m = this.liveMetrics
return [
{ key: 'weight', label: '体重(kg)', value: m.weight ?? '--' },
{ key: 'bodyFat', label: '体脂率(%)', value: m.bodyFat ?? '--' },
{ key: 'muscleMass', label: '肌肉量(kg)', value: m.muscleMass ?? '--' },
{ key: 'bmr', label: '基础代谢', value: m.bmr ?? '--' }
]
}
},
onLoad() {
const store = loadMemberStore()
if (!store.bodyTest.device.connected) {
uni.showToast({ title: '请先连接设备', icon: 'none' })
setTimeout(() => {
navigateToPage(PAGE.BODY_TEST_CONNECT)
}, 800)
const progress = ref(0)
const liveMetrics = ref({})
let timer = null
const finished = ref(false)
const ringRotation = computed(() => {
return -90 + (progress.value / 100) * 360
})
const phaseHint = computed(() => {
const phase = PHASES.find((p) => progress.value <= p.until)
return phase?.hint || '完成'
})
const statusText = computed(() => {
const phase = PHASES.find((p) => progress.value <= p.until)
return phase?.text || '测量完成'
})
const liveDisplay = computed(() => {
const m = liveMetrics.value
return [
{ key: 'weight', label: '体重(kg)', value: m.weight ?? '--' },
{ key: 'bodyFat', label: '体脂率(%)', value: m.bodyFat ?? '--' },
{ key: 'muscleMass', label: '肌肉量(kg)', value: m.muscleMass ?? '--' },
{ key: 'bmr', label: '基础代谢', value: m.bmr ?? '--' }
]
})
function clearTimer() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function startMeasurement() {
const store = loadMemberStore()
liveMetrics.value = interpolateMeasuringMetrics(0, store.profile)
timer = setInterval(() => {
if (progress.value >= 100) {
completeMeasurement()
return
}
this.startMeasurement()
},
onUnload() {
this.clearTimer()
},
methods: {
clearTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
progress.value = Math.min(100, progress.value + 2)
const s = loadMemberStore()
liveMetrics.value = interpolateMeasuringMetrics(progress.value, s.profile)
}, 120)
}
function completeMeasurement() {
if (finished.value) return
finished.value = true
clearTimer()
const store = loadMemberStore()
const record = saveSimulatedBodyTestRecord(store, {
...liveMetrics.value,
visceralFat: 6,
boneMass: 2.42,
bodyWater: liveMetrics.value.bodyWater || 52.8,
protein: 16.4
})
persistMemberStore(store)
uni.showToast({ title: '测量完成', icon: 'success' })
setTimeout(() => {
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${record.id}&new=1`)
}, 600)
}
function onCancel() {
if (finished.value) return
uni.showModal({
title: '取消测量',
content: '确定要中断当前体测吗?',
success: (res) => {
if (res.confirm) {
clearTimer()
goBackOrTab(PAGE.BODY_TEST_HOME)
}
},
startMeasurement() {
const store = loadMemberStore()
this.liveMetrics = interpolateMeasuringMetrics(0, store.profile)
this.timer = setInterval(() => {
if (this.progress >= 100) {
this.completeMeasurement()
return
}
this.progress = Math.min(100, this.progress + 2)
const s = loadMemberStore()
this.liveMetrics = interpolateMeasuringMetrics(this.progress, s.profile)
}, 120)
},
completeMeasurement() {
if (this.finished) return
this.finished = true
this.clearTimer()
const store = loadMemberStore()
const record = saveSimulatedBodyTestRecord(store, {
...this.liveMetrics,
visceralFat: 6,
boneMass: 2.42,
bodyWater: this.liveMetrics.bodyWater || 52.8,
protein: 16.4
})
persistMemberStore(store)
uni.showToast({ title: '测量完成', icon: 'success' })
setTimeout(() => {
navigateToPage(`${PAGE.BODY_TEST_REPORT}?id=${record.id}&new=1`)
}, 600)
},
onCancel() {
if (this.finished) return
uni.showModal({
title: '取消测量',
content: '确定要中断当前体测吗?',
success: (res) => {
if (res.confirm) {
this.clearTimer()
goBackOrTab(PAGE.BODY_TEST_HOME)
}
}
})
}
}
})
}
onUnmounted(() => {
clearTimer()
})
// Initialize
const store = loadMemberStore()
if (!store.bodyTest.device.connected) {
uni.showToast({ title: '请先连接设备', icon: 'none' })
setTimeout(() => {
navigateToPage(PAGE.BODY_TEST_CONNECT)
}, 800)
} else {
startMeasurement()
}
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -169,7 +169,8 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import BodyTestRadarChart from '@/components/memberInfo/BodyTestRadarChart.vue'
import BodyTestTrendChart from '@/components/memberInfo/BodyTestTrendChart.vue'
@@ -180,127 +181,139 @@ import {
getBodyTestTrendData,
getRecommendedCourses,
computeChanges,
formatChangeValue,
bodyTestMock
formatChangeValue
} from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav, BodyTestRadarChart, BodyTestTrendChart },
data() {
const recordId = ref(null)
const record = ref(null)
const previous = ref(null)
const chartWidth = ref(300)
const radarLabels = computed(() => {
return ['体重', 'BMI', '体脂率', '肌肉量', '内脏脂肪', '基础代谢']
})
const radarKeys = ['weight', 'bmi', 'bodyFat', 'muscleMass', 'visceralFat', 'bmr']
const radarValues = computed(() => {
if (!record.value?.radar) return []
return radarKeys.map((k) => record.value.radar[k] || 0)
})
const metricDefs = [
{ key: 'weight', label: '体重', unit: 'kg' },
{ key: 'bmi', label: 'BMI' },
{ key: 'bodyFat', label: '体脂率', unit: '%' },
{ key: 'muscleMass', label: '肌肉量', unit: 'kg' },
{ key: 'visceralFat', label: '内脏脂肪', unit: '级' },
{ key: 'bmr', label: '基础代谢', unit: 'kcal' },
{ key: 'bodyWater', label: '体水分', unit: '%' },
{ key: 'boneMass', label: '骨量', unit: 'kg' }
]
const metricCards = computed(() => {
if (!record.value?.metrics) return []
const changesVal = changes.value
const defs = metricDefs.slice(0, 8)
return defs.map((def) => {
const val = record.value.metrics[def.key]
const diff = changesVal[def.key]
let changeText = ''
let changeClass = ''
if (diff !== undefined && diff !== null) {
changeText = formatChangeValue(def.key, diff)
const lowerBetter = ['weight', 'bodyFat', 'visceralFat'].includes(def.key)
const isGood = lowerBetter ? diff < 0 : diff > 0
changeClass = isGood ? 'bt-metric__change--down' : 'bt-metric__change--up'
}
const display = def.unit ? `${val}${def.unit === '%' ? '%' : def.unit === 'kg' ? '' : ` ${def.unit}`}` : val
return {
recordId: null,
record: null,
previous: null,
chartWidth: 300
}
},
computed: {
radarLabels() {
return bodyTestMock.radarLabels.map((l) => l.label)
},
radarValues() {
if (!this.record?.radar) return []
const keys = bodyTestMock.radarLabels.map((l) => l.key)
return keys.map((k) => this.record.radar[k] || 0)
},
metricCards() {
if (!this.record?.metrics) return []
const changes = this.changes
const defs = bodyTestMock.metricDefs.slice(0, 8)
return defs.map((def) => {
const val = this.record.metrics[def.key]
const diff = changes[def.key]
let changeText = ''
let changeClass = ''
if (diff !== undefined && diff !== null) {
changeText = formatChangeValue(def.key, diff)
const lowerBetter = ['weight', 'bodyFat', 'visceralFat'].includes(def.key)
const isGood = lowerBetter ? diff < 0 : diff > 0
changeClass = isGood ? 'bt-metric__change--down' : 'bt-metric__change--up'
}
const display = def.unit ? `${val}${def.unit === '%' ? '%' : def.unit === 'kg' ? '' : ` ${def.unit}`}` : val
return {
key: def.key,
label: def.label + (def.unit && def.unit !== '%' && def.unit !== 'kg' ? `(${def.unit})` : def.unit === 'kg' ? '(kg)' : def.unit === '%' ? '(%)' : ''),
display: def.key === 'bodyFat' ? `${val}%` : def.key === 'bodyWater' ? `${val}%` : def.unit === 'kg' ? val : def.unit ? `${val}` : val,
changeText,
changeClass
}
})
},
changes() {
if (this.record?.changes) return this.record.changes
if (this.previous) return computeChanges(this.record, this.previous)
return {}
},
trendPreview() {
const store = loadMemberStore()
return getBodyTestTrendData(store, 'weight', 4)
},
courses() {
return getRecommendedCourses(this.record)
}
},
onLoad(options) {
this.recordId = options?.id ? Number(options.id) : null
this.chartWidth = uni.getSystemInfoSync().windowWidth - 64
this.loadRecord()
},
methods: {
loadRecord() {
const store = loadMemberStore()
const records = store.bodyTest.records
if (this.recordId) {
this.record = getBodyTestRecordById(store, this.recordId)
} else {
this.record = records.length ? { ...records[0] } : null
}
if (this.record) {
const idx = records.findIndex((r) => r.id === this.record.id)
this.previous = idx >= 0 && records[idx + 1] ? records[idx + 1] : null
}
},
onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
},
goTrend() {
navigateToPage(`${PAGE.BODY_TEST_TREND}?metric=weight`)
},
exportReport() {
uni.showLoading({ title: '生成中…' })
setTimeout(() => {
uni.hideLoading()
uni.showToast({ title: '报告已保存到相册', icon: 'success' })
}, 1200)
},
shareReport() {
uni.showActionSheet({
itemList: ['分享给微信好友', '生成分享海报', '复制报告链接'],
success: (res) => {
const msgs = ['已唤起微信分享', '海报已生成', '链接已复制']
uni.showToast({ title: msgs[res.tapIndex] || '分享成功', icon: 'none' })
}
})
},
onCourseTap(course) {
uni.showModal({
title: course.title,
content: `${course.coach}\n${course.schedule}\n\n是否前往预约?`,
success: (res) => {
if (res.confirm) {
navigateToPage(PAGE.COURSE_LIST)
}
}
})
},
retest() {
navigateToPage(PAGE.BODY_TEST_HOME)
key: def.key,
label: def.label + (def.unit && def.unit !== '%' && def.unit !== 'kg' ? `(${def.unit})` : def.unit === 'kg' ? '(kg)' : def.unit === '%' ? '(%)' : ''),
display: def.key === 'bodyFat' ? `${val}%` : def.key === 'bodyWater' ? `${val}%` : def.unit === 'kg' ? val : def.unit ? `${val}` : val,
changeText,
changeClass
}
})
})
const changes = computed(() => {
if (record.value?.changes) return record.value.changes
if (previous.value) return computeChanges(record.value, previous.value)
return {}
})
const trendPreview = computed(() => {
const store = loadMemberStore()
return getBodyTestTrendData(store, 'weight', 4)
})
const courses = computed(() => {
return getRecommendedCourses(record.value)
})
function loadRecord() {
const store = loadMemberStore()
const records = store.bodyTest.records
if (recordId.value) {
record.value = getBodyTestRecordById(store, recordId.value)
} else {
record.value = records.length ? { ...records[0] } : null
}
if (record.value) {
const idx = records.findIndex((r) => r.id === record.value.id)
previous.value = idx >= 0 && records[idx + 1] ? records[idx + 1] : null
}
}
function onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
}
function goTrend() {
navigateToPage(`${PAGE.BODY_TEST_TREND}?metric=weight`)
}
function exportReport() {
uni.showLoading({ title: '生成中…' })
setTimeout(() => {
uni.hideLoading()
uni.showToast({ title: '报告已保存到相册', icon: 'success' })
}, 1200)
}
function shareReport() {
uni.showActionSheet({
itemList: ['分享给微信好友', '生成分享海报', '复制报告链接'],
success: (res) => {
const msgs = ['已唤起微信分享', '海报已生成', '链接已复制']
uni.showToast({ title: msgs[res.tapIndex] || '分享成功', icon: 'none' })
}
})
}
function onCourseTap(course) {
uni.showModal({
title: course.title,
content: `${course.coach}\n${course.schedule}\n\n是否前往预约?`,
success: (res) => {
if (res.confirm) {
navigateToPage(PAGE.COURSE_LIST)
}
}
})
}
function retest() {
navigateToPage(PAGE.BODY_TEST_HOME)
}
// Initialize
chartWidth.value = uni.getSystemInfoSync().windowWidth - 64
loadRecord()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -3,97 +3,99 @@
<view class="bt-page">
<MemberInfoSubNav title="体测设置" @back="onBack" />
<view class="bt-page__body">
<view class="bt-card">
<text class="bt-card__title">连接与同步</text>
<view class="bt-setting">
<view>
<text class="bt-setting__label">蓝牙自动连接</text>
<text class="bt-setting__desc">进入体测页时自动搜索已配对设备</text>
</view>
<switch
:checked="settings.bluetoothEnabled"
color="#FF6B35"
@change="onSwitch('bluetoothEnabled', $event)"
/>
</view>
<view class="bt-setting">
<view>
<text class="bt-setting__label">测量完成自动同步</text>
<text class="bt-setting__desc">结果自动保存至云端与本地</text>
</view>
<switch
:checked="settings.autoSync"
color="#FF6B35"
@change="onSwitch('autoSync', $event)"
/>
</view>
</view>
<view class="bt-card">
<text class="bt-card__title">通知与隐私</text>
<view class="bt-setting">
<view>
<text class="bt-setting__label">测量完成通知</text>
<text class="bt-setting__desc">体测结束后推送报告摘要</text>
</view>
<switch
:checked="settings.notifyOnComplete"
color="#FF6B35"
@change="onSwitch('notifyOnComplete', $event)"
/>
</view>
<view class="bt-setting">
<view>
<text class="bt-setting__label">分享时匿名化</text>
<text class="bt-setting__desc">隐藏姓名与手机号</text>
</view>
<switch
:checked="settings.shareAnonymous"
color="#FF6B35"
@change="onSwitch('shareAnonymous', $event)"
/>
</view>
</view>
<view class="bt-card">
<text class="bt-card__title">单位制</text>
<view class="bt-setting">
<view>
<text class="bt-setting__label">度量单位</text>
<text class="bt-setting__desc">{{ unitLabel }}</text>
</view>
<view
hover-class="mi-tap--hover"
:hover-stay-time="150"
@tap="toggleUnit"
>
<text style="font-size: 14px; color: #1A4A6F; font-weight: 600;">切换</text>
<view class="bt-setting-row" @tap="toggleUnit">
<text class="bt-setting-row__label">单位制</text>
<view class="bt-setting-row__value">
<text class="bt-setting-row__text">{{ unitLabel }}</text>
<image
class="bt-setting-row__arrow"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/rightarrow.png"
mode="aspectFit"
/>
</view>
</view>
</view>
<view class="bt-card">
<text class="bt-card__title">设备管理</text>
<view class="bt-device">
<view class="bt-device__icon-wrap">
<image class="bt-device__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/mappin2.png" mode="aspectFit" />
<view class="bt-device-row">
<view class="bt-device-row__icon">
<image
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/bluetooth.png"
mode="aspectFit"
/>
</view>
<view class="bt-device__info">
<text class="bt-device__name">{{ device.name }}</text>
<text class="bt-device__status">
{{ device.connected ? '已连接' : '未连接' }}
· 上次 {{ device.lastConnected || '--' }}
<view class="bt-device-row__info">
<text class="bt-device-row__name">{{ device.name || '未连接设备' }}</text>
<text class="bt-device-row__status">
{{ device.connected ? `已连接 · 电量 ${device.battery}%` : '点击连接体脂秤' }}
</text>
</view>
<view
v-if="device.connected"
class="bt-device-row__disconnect"
hover-class="mi-tap-btn--hover"
@tap="disconnect"
>
<text class="bt-device-row__disconnect-text">解除</text>
</view>
</view>
<view
class="bt-btn bt-btn--outline"
style="margin-top: 12px;"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap="disconnect"
>
<text class="bt-btn__text">解除设备配对</text>
</view>
<view class="bt-card">
<text class="bt-card__title">通知提醒</text>
<view class="bt-setting-row">
<text class="bt-setting-row__label">体测提醒</text>
<switch
:checked="settings.remindEnabled"
@change="(e) => onSwitch('remindEnabled', e)"
/>
</view>
<view v-if="settings.remindEnabled" class="bt-setting-row">
<text class="bt-setting-row__label">提醒周期</text>
<picker
mode="selector"
:range="['每周', '每两周', '每月']"
:value="settings.remindInterval"
@change="(e) => onSwitch('remindInterval', e)"
>
<view class="bt-setting-row__value">
<text class="bt-setting-row__text">
{{ ['每周', '每两周', '每月'][settings.remindInterval] }}
</text>
<image
class="bt-setting-row__arrow"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/rightarrow.png"
mode="aspectFit"
/>
</view>
</picker>
</view>
</view>
<view class="bt-card">
<text class="bt-card__title">隐私设置</text>
<view class="bt-setting-row">
<text class="bt-setting-row__label">数据可见性</text>
<picker
mode="selector"
:range="['仅本人', '教练可见', '完全公开']"
:value="settings.privacy"
@change="(e) => onSwitch('privacy', e)"
>
<view class="bt-setting-row__value">
<text class="bt-setting-row__text">
{{ ['仅本人', '教练可见', '完全公开'][settings.privacy] }}
</text>
<image
class="bt-setting-row__arrow"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/rightarrow.png"
mode="aspectFit"
/>
</view>
</picker>
</view>
</view>
</view>
@@ -101,7 +103,8 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import {
@@ -113,65 +116,59 @@ import {
disconnectBodyTestDevice
} from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return {
settings: {},
device: {}
}
},
computed: {
unitLabel() {
return this.settings.unitSystem === 'imperial' ? '英制 (lb / in)' : '公制 (kg / cm)'
}
},
onShow() {
this.refreshFromStore()
},
methods: {
refreshFromStore() {
const store = loadMemberStore()
this.settings = { ...store.bodyTest.settings }
this.device = { ...store.bodyTest.device }
},
onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
},
onSwitch(key, e) {
const store = loadMemberStore()
updateBodyTestSettings(store, { [key]: e.detail.value })
persistMemberStore(store)
this.settings = { ...store.bodyTest.settings }
uni.showToast({ title: '已保存', icon: 'success' })
},
toggleUnit() {
const store = loadMemberStore()
const next = this.settings.unitSystem === 'metric' ? 'imperial' : 'metric'
updateBodyTestSettings(store, { unitSystem: next })
persistMemberStore(store)
this.settings = { ...store.bodyTest.settings }
uni.showToast({ title: `已切换为${this.unitLabel}`, icon: 'none' })
},
disconnect() {
uni.showModal({
title: '解除配对',
content: '解除后下次体测需重新连接设备,确定继续?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
disconnectBodyTestDevice(store)
persistMemberStore(store)
this.refreshFromStore()
uni.showToast({ title: '已解除配对', icon: 'success' })
}
})
}
}
const settings = ref({})
const device = ref({})
const unitLabel = computed(() => {
return settings.value.unitSystem === 'imperial' ? '英制 (lb / in)' : '公制 (kg / cm)'
})
function refreshFromStore() {
const store = loadMemberStore()
settings.value = { ...store.bodyTest.settings }
device.value = { ...store.bodyTest.device }
}
function onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
}
function onSwitch(key, e) {
const store = loadMemberStore()
updateBodyTestSettings(store, { [key]: e.detail.value })
persistMemberStore(store)
refreshFromStore()
uni.showToast({ title: '已保存', icon: 'success' })
}
function toggleUnit() {
const store = loadMemberStore()
const next = settings.value.unitSystem === 'metric' ? 'imperial' : 'metric'
updateBodyTestSettings(store, { unitSystem: next })
persistMemberStore(store)
refreshFromStore()
uni.showToast({ title: `已切换为${unitLabel.value}`, icon: 'none' })
}
function disconnect() {
uni.showModal({
title: '解除配对',
content: '解除后下次体测需重新连接设备,确定继续?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
disconnectBodyTestDevice(store)
persistMemberStore(store)
refreshFromStore()
uni.showToast({ title: '已解除配对', icon: 'success' })
}
})
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -56,91 +56,100 @@
</view>
</template>
<script>
<script setup>
import { ref, computed, onMounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import BodyTestTrendChart from '@/components/memberInfo/BodyTestTrendChart.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getBodyTestTrendData, bodyTestMock } from '@/common/memberInfo/bodyTestStore.js'
import { getBodyTestTrendData } from '@/common/memberInfo/bodyTestStore.js'
export default {
components: { MemberInfoSubNav, BodyTestTrendChart },
data() {
return {
tabs: bodyTestMock.trendMetrics,
activeMetric: 'weight',
trendPoints: [],
chartWidth: 300
}
},
computed: {
activeLabel() {
return this.tabs.find((t) => t.key === this.activeMetric)?.label || ''
},
activeUnit() {
const units = {
weight: 'kg',
bodyFat: '%',
muscleMass: 'kg',
bmi: ''
}
return units[this.activeMetric] || ''
},
trendPointsReversed() {
return [...this.trendPoints].reverse()
},
summaryText() {
if (this.trendPoints.length < 2) return ''
const first = this.trendPoints[0].value
const last = this.trendPoints[this.trendPoints.length - 1].value
const diff = Math.round((last - first) * 10) / 10
const sign = diff > 0 ? '上升' : diff < 0 ? '下降' : '持平'
const abs = Math.abs(diff)
const lowerBetter = ['weight', 'bodyFat'].includes(this.activeMetric)
let advice = ''
if (diff !== 0) {
const good = lowerBetter ? diff < 0 : diff > 0
advice = good ? ',变化方向符合健康目标' : ',建议关注饮食与训练计划'
}
return `期间${this.activeLabel}${sign} ${abs}${this.activeUnit}${advice}`
}
},
onLoad(options) {
if (options?.metric) {
this.activeMetric = options.metric
}
this.chartWidth = uni.getSystemInfoSync().windowWidth - 64
this.loadTrend()
},
methods: {
onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
},
switchMetric(key) {
this.activeMetric = key
this.loadTrend()
},
loadTrend() {
const store = loadMemberStore()
this.trendPoints = getBodyTestTrendData(store, this.activeMetric, 6)
},
rowDiffText(current, older) {
const diff = Math.round((current.value - older.value) * 10) / 10
const sign = diff > 0 ? '+' : ''
return `${sign}${diff}${this.activeUnit}`
},
rowDiffColor(current, older) {
const diff = current.value - older.value
if (diff === 0) return '#8A99B4'
const lowerBetter = ['weight', 'bodyFat'].includes(this.activeMetric)
const good = lowerBetter ? diff < 0 : diff > 0
return good ? '#2ECC71' : '#F39C12'
}
}
const tabs = ref([
{ key: 'weight', label: '体重' },
{ key: 'bodyFat', label: '体脂率' },
{ key: 'muscleMass', label: '肌肉量' },
{ key: 'bmi', label: 'BMI' }
])
const activeMetric = ref('weight')
const trendPoints = ref([])
const chartWidth = ref(300)
const units = {
weight: 'kg',
bodyFat: '%',
muscleMass: 'kg',
bmi: ''
}
const activeLabel = computed(() => {
return tabs.value.find((t) => t.key === activeMetric.value)?.label || ''
})
const activeUnit = computed(() => {
return units[activeMetric.value] || ''
})
const trendPointsReversed = computed(() => {
return [...trendPoints.value].reverse()
})
const summaryText = computed(() => {
if (trendPoints.value.length < 2) return ''
const first = trendPoints.value[0].value
const last = trendPoints.value[trendPoints.value.length - 1].value
const diff = Math.round((last - first) * 10) / 10
const sign = diff > 0 ? '上升' : diff < 0 ? '下降' : '持平'
const abs = Math.abs(diff)
const lowerBetter = ['weight', 'bodyFat'].includes(activeMetric.value)
let advice = ''
if (diff !== 0) {
const good = lowerBetter ? diff < 0 : diff > 0
advice = good ? ',变化方向符合健康目标' : ',建议关注饮食与训练计划'
}
return `期间${activeLabel.value}${sign} ${abs}${activeUnit.value}${advice}`
})
function onBack() {
goBackOrTab(PAGE.BODY_TEST_HOME)
}
function switchMetric(key) {
activeMetric.value = key
loadTrend()
}
function loadTrend() {
const store = loadMemberStore()
trendPoints.value = getBodyTestTrendData(store, activeMetric.value, 6)
}
function rowDiffText(current, older) {
const diff = Math.round((current.value - older.value) * 10) / 10
const sign = diff > 0 ? '+' : ''
return `${sign}${diff}${activeUnit.value}`
}
function rowDiffColor(current, older) {
const diff = current.value - older.value
if (diff === 0) return '#8A99B4'
const lowerBetter = ['weight', 'bodyFat'].includes(activeMetric.value)
const good = lowerBetter ? diff < 0 : diff > 0
return good ? '#2ECC71' : '#F39C12'
}
onMounted(() => {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const options = currentPage?.options || {}
if (options?.metric) {
activeMetric.value = options.metric
}
chartWidth.value = uni.getSystemInfoSync().windowWidth - 64
loadTrend()
})
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
+136 -75
View File
@@ -99,14 +99,25 @@
<view class="bk-card__footer">
<text class="bk-card__footer-info">{{ item.footerText }}</text>
<view
v-if="item.canCancel"
class="bk-card__cancel"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap.stop="cancelBooking(item)"
>
<text class="bk-card__cancel-text">取消预约</text>
<view class="bk-card__actions">
<view
v-if="item.canSignin"
class="bk-card__signin"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap.stop="signinCourse(item)"
>
<text class="bk-card__signin-text">签到</text>
</view>
<view
v-if="item.canCancel"
class="bk-card__cancel"
hover-class="mi-tap-btn--hover"
:hover-stay-time="150"
@tap.stop="cancelBooking(item)"
>
<text class="bk-card__cancel-text">取消预约</text>
</view>
</view>
</view>
</view>
@@ -122,83 +133,133 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { bookingMock } from '@/common/memberInfo/mockData.js'
import { PAGE, navigateToPage, backToMemberCenter } from '@/common/constants/routes.js'
import {
loadMemberStore,
cancelOngoingBooking,
formatUpcomingAlert
} from '@/common/memberInfo/store.js'
import { canCancelBooking } from '@/common/memberInfo/bookingStore.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
import { canCancelBooking, canSigninCourse } from '@/common/memberInfo/bookingStore.js'
import { signinGroupCourse, cancelBooking as cancelBookingApi } from '@/api/main.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
tabs: bookingMock.tabs,
ongoingBookings: [],
historyBookings: [],
activeTab: 'ongoing'
}
},
computed: {
displayedBookings() {
return this.activeTab === 'ongoing'
? this.ongoingBookings
: this.historyBookings
},
upcomingAlert() {
return formatUpcomingAlert(this.ongoingBookings[0])
}
},
onShow() {
this.refreshFromStore()
},
methods: {
refreshFromStore() {
const store = loadMemberStore()
this.ongoingBookings = store.ongoingBookings.map((item) => ({
...item,
canCancel: canCancelBooking(item)
}))
this.historyBookings = store.historyBookings.map((item) => ({ ...item }))
},
goCourseList() {
navigateToPage(PAGE.COURSE_LIST)
},
setActiveTab(tab) {
this.activeTab = tab
},
cancelBooking(item) {
if (!canCancelBooking(item)) {
uni.showToast({ title: '距开课不足2小时,无法取消', icon: 'none' })
return
}
uni.showModal({
title: '取消预约',
content: `确定要取消「${item.title}」吗?`,
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
const result = cancelOngoingBooking(store, item.id)
if (!result.ok) {
uni.showToast({ title: result.message, icon: 'none' })
return
}
this.refreshFromStore()
uni.showToast({ title: '已取消', icon: 'success' })
}
})
}
}
const tabs = ref([])
const ongoingBookings = ref([])
const historyBookings = ref([])
const activeTab = ref('ongoing')
const displayedBookings = computed(() => {
return activeTab.value === 'ongoing'
? ongoingBookings.value
: historyBookings.value
})
const upcomingAlert = computed(() => {
return formatUpcomingAlert(ongoingBookings.value[0])
})
function refreshFromStore() {
const store = loadMemberStore()
ongoingBookings.value = store.ongoingBookings.map((item) => ({
...item,
canCancel: canCancelBooking(item),
canSignin: canSigninCourse(item)
}))
historyBookings.value = store.historyBookings.map((item) => ({ ...item }))
}
function goBack() {
backToMemberCenter()
}
function goCourseList() {
navigateToPage(PAGE.COURSE_LIST)
}
function setActiveTab(tab) {
activeTab.value = tab
}
// 签到团课
async function signinCourse(item) {
const store = loadMemberStore()
const memberId = store.memberProfile?.id || store.profile?.id
if (!memberId) {
uni.showToast({ title: '请先登录', icon: 'none' })
return
}
uni.showModal({
title: '确认签到',
content: `确认签到「${item.title}」吗?`,
success: async (res) => {
if (!res.confirm) return
uni.showLoading({ title: '签到中...', mask: true })
try {
const result = await signinGroupCourse(Number(memberId), Number(item.courseId || item.id))
uni.hideLoading()
if (result.code === 200 || result.success) {
uni.showToast({ title: '签到成功', icon: 'success' })
// 更新本地状态
refreshFromStore()
} else {
uni.showToast({ title: result.message || '签到失败', icon: 'none' })
}
} catch (e) {
uni.hideLoading()
console.error('[booking] 签到失败:', e)
uni.showToast({ title: e.message || '签到失败', icon: 'none' })
}
}
})
}
// 取消预约
async function cancelBooking(item) {
if (!canCancelBooking(item)) {
uni.showToast({ title: '距开课不足2小时,无法取消', icon: 'none' })
return
}
uni.showModal({
title: '取消预约',
content: `确定要取消「${item.title}」吗?`,
success: async (res) => {
if (!res.confirm) return
uni.showLoading({ title: '取消中...', mask: true })
try {
// 调用后端API取消预约
const result = await cancelBookingApi(Number(item.id))
uni.hideLoading()
if (result.code === 200 || result.success) {
// 更新本地状态
const store = loadMemberStore()
const localResult = cancelOngoingBooking(store, item.id)
if (localResult.ok) {
refreshFromStore()
}
uni.showToast({ title: '已取消', icon: 'success' })
} else {
uni.showToast({ title: result.message || '取消失败', icon: 'none' })
}
} catch (e) {
uni.hideLoading()
console.error('[booking] 取消预约失败:', e)
uni.showToast({ title: e.message || '取消失败', icon: 'none' })
}
}
})
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -46,45 +46,48 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { moduleMock, getCheckInHistory } from '@/common/memberInfo/moduleStore.js'
import { getCheckInHistory } from '@/common/memberInfo/moduleStore.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
import { backToMemberCenter } from '@/common/constants/routes.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
tabs: moduleMock.checkInTabs,
activeFilter: 'all',
list: []
}
},
computed: {
filteredList() {
if (this.activeFilter === 'all') return this.list
return this.list.filter((i) => i.tagTheme === this.activeFilter)
}
},
onShow() {
const store = loadMemberStore()
this.list = getCheckInHistory(store, 'all')
},
methods: {
showDetail(item) {
uni.showModal({
title: item.title,
content: `${item.time}\n地点:${item.location}\n类型:${item.tag}`,
showCancel: false
})
}
}
const tabs = ref([
{ key: 'all', label: '全部' },
{ key: 'signin', label: '签到' },
{ key: 'trial', label: '体验' },
{ key: 'event', label: '活动' }
])
const activeFilter = ref('all')
const list = ref([])
const filteredList = computed(() => {
if (activeFilter.value === 'all') return list.value
return list.value.filter((i) => i.tagTheme === activeFilter.value)
})
function refresh() {
const store = loadMemberStore()
list.value = getCheckInHistory(store, 'all')
}
function goBack() {
backToMemberCenter()
}
function showDetail(item) {
uni.showModal({
title: item.title,
content: `${item.time}\n地点:${item.location}\n类型:${item.tag}`,
showCancel: false
})
}
refresh()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -33,38 +33,37 @@
</view>
</template>
<script>
<script setup>
import { ref, onMounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore, persistMemberStore } from '@/common/memberInfo/store.js'
import { getCouponCenterList, claimCouponFromCenter } from '@/common/memberInfo/moduleStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return { list: [] }
},
onShow() {
const store = loadMemberStore()
this.list = getCouponCenterList(store)
},
methods: {
onBack() { goBackOrTab(PAGE.COUPONS) },
claim(item) {
if (item.claimed) return
const store = loadMemberStore()
const result = claimCouponFromCenter(store, item.id)
uni.showToast({ title: result.message, icon: result.ok ? 'success' : 'none' })
if (result.ok) {
persistMemberStore(store)
this.list = getCouponCenterList(store)
}
}
const list = ref([])
onMounted(() => {
const store = loadMemberStore()
list.value = getCouponCenterList(store)
})
function onBack() {
goBackOrTab(PAGE.COUPONS)
}
function claim(item) {
if (item.claimed) return
const store = loadMemberStore()
const result = claimCouponFromCenter(store, item.id)
uni.showToast({ title: result.message, icon: result.ok ? 'success' : 'none' })
if (result.ok) {
persistMemberStore(store)
list.value = getCouponCenterList(store)
}
}
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -36,31 +36,33 @@
</view>
</template>
<script>
<script setup>
import { ref, onMounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getCouponById } from '@/common/memberInfo/moduleStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return { coupon: null }
},
onLoad(options) {
const store = loadMemberStore()
this.coupon = getCouponById(store, options?.id)
},
methods: {
onBack() { goBackOrTab(PAGE.COUPONS) },
useNow() {
navigateToPage(PAGE.COURSE_LIST)
}
}
const coupon = ref(null)
onMounted(() => {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const options = currentPage?.options || {}
const store = loadMemberStore()
coupon.value = getCouponById(store, options?.id)
})
function onBack() {
goBackOrTab(PAGE.COUPONS)
}
function useNow() {
navigateToPage(PAGE.COURSE_LIST)
}
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
+71 -68
View File
@@ -61,81 +61,84 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { moduleMock, getCouponsByStatus, useCoupon, deleteExpiredCoupon } from '@/common/memberInfo/moduleStore.js'
import { PAGE, navigateToPage, backToMemberCenter } from '@/common/constants/routes.js'
import { getCouponsByStatus, useCoupon, deleteExpiredCoupon } from '@/common/memberInfo/moduleStore.js'
import { loadMemberStore, persistMemberStore } from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
tabs: moduleMock.couponTabs,
activeTab: 'available',
coupons: []
}
},
computed: {
displayedCoupons() {
return this.coupons.filter((c) => c.status === this.activeTab)
},
countByTab() {
return {
available: this.coupons.filter((c) => c.status === 'available').length,
used: this.coupons.filter((c) => c.status === 'used').length,
expired: this.coupons.filter((c) => c.status === 'expired').length
}
},
activeTabLabel() {
return this.tabs.find((t) => t.key === this.activeTab)?.label || ''
}
},
onShow() {
this.refreshList()
},
methods: {
refreshList() {
const store = loadMemberStore()
this.coupons = [
...getCouponsByStatus(store, 'available'),
...getCouponsByStatus(store, 'used'),
...getCouponsByStatus(store, 'expired')
]
},
onCouponTap(item) {
navigateToPage(`${PAGE.COUPON_DETAIL}?id=${item.id}`)
},
useNow(item) {
uni.showModal({
title: '使用优惠券',
content: `确认使用「${item.title}」?`,
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
useCoupon(store, item.id)
persistMemberStore(store)
this.refreshList()
navigateToPage(PAGE.COURSE_LIST)
}
})
},
removeExpired(item) {
const store = loadMemberStore()
deleteExpiredCoupon(store, item.id)
persistMemberStore(store)
this.refreshList()
},
goCenter() {
navigateToPage(PAGE.COUPON_CENTER)
}
const tabs = ref([
{ key: 'available', label: '可用' },
{ key: 'used', label: '已用' },
{ key: 'expired', label: '已失效' }
])
const activeTab = ref('available')
const coupons = ref([])
const displayedCoupons = computed(() => {
return coupons.value.filter((c) => c.status === activeTab.value)
})
const countByTab = computed(() => {
return {
available: coupons.value.filter((c) => c.status === 'available').length,
used: coupons.value.filter((c) => c.status === 'used').length,
expired: coupons.value.filter((c) => c.status === 'expired').length
}
})
const activeTabLabel = computed(() => {
return tabs.value.find((t) => t.key === activeTab.value)?.label || ''
})
function refreshList() {
const store = loadMemberStore()
coupons.value = [
...getCouponsByStatus(store, 'available'),
...getCouponsByStatus(store, 'used'),
...getCouponsByStatus(store, 'expired')
]
}
function goBack() {
backToMemberCenter()
}
function onCouponTap(item) {
navigateToPage(`${PAGE.COUPON_DETAIL}?id=${item.id}`)
}
function useNow(item) {
uni.showModal({
title: '使用优惠券',
content: `确认使用「${item.title}」?`,
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
useCoupon(store, item.id)
persistMemberStore(store)
refreshList()
navigateToPage(PAGE.COURSE_LIST)
}
})
}
function removeExpired(item) {
const store = loadMemberStore()
deleteExpiredCoupon(store, item.id)
persistMemberStore(store)
refreshList()
}
function goCenter() {
navigateToPage(PAGE.COUPON_CENTER)
}
refreshList()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -0,0 +1,569 @@
<template>
<view class="login-page">
<!-- 自定义Toast弹窗 -->
<view class="custom-toast" :class="{ show: toastShow }">
<text class="toast-text">{{ toastMessage }}</text>
</view>
<view class="login-header">
<view class="logo-wrapper">
<image class="logo-image" src="/static/logo.png" mode="aspectFit" />
<text class="app-name">活氧舱欢迎您</text>
<text class="app-slogan">享受运动拥抱健康</text>
</view>
</view>
<view class="card-container">
<!-- 手机号+验证码登录卡片 -->
<view class="login-card sms-card" :class="{ active: activeCard === 'sms' }">
<view class="card-body">
<text class="phone-display">验证码登录</text>
<text class="auth-tip">认证服务由中国移动提供</text>
<view class="form-group">
<view class="input-wrapper" :class="{ focused: isSmsPhoneFocused }">
<input
v-model="smsPhone"
type="number"
placeholder="请输入手机号"
maxlength="11"
class="phone-input"
confirm-type="next"
@focus="isSmsPhoneFocused = true"
@blur="isSmsPhoneFocused = false"
/>
</view>
</view>
<view class="form-group">
<view class="input-wrapper code-input" :class="{ focused: isCodeFocused }">
<input
v-model="code"
type="number"
placeholder="请输入验证码"
maxlength="6"
class="phone-input"
confirm-type="done"
@focus="isCodeFocused = true"
@blur="isCodeFocused = false"
/>
<button
class="send-code-btn"
:class="{ disabled: countdown > 0 || isLoading }"
@tap="handleSendCode"
:disabled="countdown > 0 || isLoading"
>
<text>{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}</text>
</button>
</view>
</view>
<button class="login-btn primary" :class="{ disabled: !canSmsSubmit, loading: isLoading }" @tap="handleSmsLogin" :disabled="!canSmsSubmit || isLoading">
<text>{{ isLoading ? '登录中...' : '验证码登录' }}</text>
</button>
<button class="login-btn secondary" @tap="switchToPhone">
<text>其他登录方式</text>
</button>
<view class="agreement-text" :class="{ shake: shakeAgreement }">
<checkbox-group @change="onAgreementChange">
<checkbox :checked="agreed" value="agreed" color="#FF8C42" />
</checkbox-group>
<text>登录即表示同意</text>
<text class="link" @tap="showAgreement">用户协议</text>
<text></text>
<text class="link" @tap="showPrivacy">隐私政策</text>
</view>
</view>
</view>
<!-- 手机号一键登录卡片 -->
<view class="login-card phone-card" :class="{ active: activeCard === 'phone' }">
<view class="card-body">
<text class="phone-display">本机号码登录</text>
<text class="auth-tip">认证服务由中国移动提供</text>
<view class="form-group phone-login">
<view class="input-wrapper" :class="{ focused: isInputFocused }">
<input
v-model="phone"
type="number"
placeholder="请输入手机号"
maxlength="11"
class="phone-input"
confirm-type="done"
@focus="isInputFocused = true"
@blur="isInputFocused = false"
/>
</view>
</view>
<button class="login-btn primary" :class="{ disabled: !canSubmit, loading: isLoading }" @tap="handlePhoneLogin" :disabled="!canSubmit || isLoading">
<text>{{ isLoading ? '登录中...' : '一键登录' }}</text>
</button>
<button class="login-btn secondary" @tap="switchToSms">
<text>其他登录方式</text>
</button>
<view class="agreement-text" :class="{ shake: shakeAgreement }">
<checkbox-group @change="onAgreementChange">
<checkbox :checked="agreed" value="agreed" color="#FF8C42" />
</checkbox-group>
<text>登录即表示同意</text>
<text class="link" @tap="showAgreement">用户协议</text>
<text></text>
<text class="link" @tap="showPrivacy">隐私政策</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { setToken } from '@/utils/request.js'
// 测试数据
const TEST_TOKEN = 'test_token_123456'
const TEST_MEMBER_INFO = {
memberId: 10001,
memberNo: 'M001',
phone: '13800138000',
nickname: '测试用户',
avatar: '/static/logo.png',
accessToken: TEST_TOKEN,
isNewUser: false
}
const activeCard = ref('phone')
const phone = ref('')
const isLoading = ref(false)
const isInputFocused = ref(false)
const agreed = ref(false)
const shakeAgreement = ref(false)
const smsPhone = ref('')
const isSmsPhoneFocused = ref(false)
const code = ref('')
const isCodeFocused = ref(false)
const countdown = ref(0)
let timer = null
// 自定义Toast
const toastShow = ref(false)
const toastMessage = ref('')
let toastTimer = null
function showToast(msg) {
if (toastTimer) clearTimeout(toastTimer)
toastMessage.value = msg
toastShow.value = true
toastTimer = setTimeout(() => {
toastShow.value = false
}, 2000)
}
const canSubmit = computed(() => {
return /^1[3-9]\d{9}$/.test(phone.value) && !isLoading.value
})
const canSmsSubmit = computed(() => {
return /^1[3-9]\d{9}$/.test(smsPhone.value) && /^\d{6}$/.test(code.value) && !isLoading.value
})
function onAgreementChange(e) {
agreed.value = e.detail.value.includes('agreed')
}
function switchToSms() {
activeCard.value = 'sms'
}
function switchToPhone() {
activeCard.value = 'phone'
phone.value = ''
phoneError.value = ''
}
function showAgreement() {
uni.showModal({ title: '用户协议', content: '这里是用户协议内容...', showCancel: false })
}
function showPrivacy() {
uni.showModal({ title: '隐私政策', content: '这里是隐私政策内容...', showCancel: false })
}
function validatePhone() {
if (!phone.value) {
showToast('请输入手机号')
return false
}
if (!/^1[3-9]\d{9}$/.test(phone.value)) {
showToast('请输入正确的手机号')
return false
}
return true
}
function validateSmsPhone() {
if (!smsPhone.value) {
showToast('请输入手机号')
return false
}
if (!/^1[3-9]\d{9}$/.test(smsPhone.value)) {
showToast('请输入正确的手机号')
return false
}
return true
}
async function handlePhoneLogin() {
if (!agreed.value) {
triggerAgreementShake()
return
}
if (!validatePhone()) return
isLoading.value = true
setTimeout(() => {
setToken(TEST_TOKEN)
uni.setStorageSync('memberInfo', TEST_MEMBER_INFO)
uni.setStorageSync('isLogin', true)
showToast('登录成功')
setTimeout(() => {
uni.switchTab({ url: '/pages/memberInfo/memberInfo' })
}, 1500)
isLoading.value = false
}, 500)
}
function triggerAgreementShake() {
shakeAgreement.value = true
showToast('请先同意用户协议和隐私政策')
setTimeout(() => {
shakeAgreement.value = false
}, 500)
}
async function handleSendCode() {
if (countdown.value > 0) {
showToast('验证码在有效期内,请勿重复发送')
return
}
if (!validateSmsPhone()) return
isLoading.value = true
setTimeout(() => {
countdown.value = 300
startCountdown()
showToast('验证码已发送')
isLoading.value = false
}, 300)
}
function startCountdown() {
if (timer) clearInterval(timer)
timer = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
clearInterval(timer)
timer = null
}
}, 1000)
}
async function handleSmsLogin() {
if (!agreed.value) {
triggerAgreementShake()
return
}
if (!validateSmsPhone()) return
if (!code.value) {
showToast('请输入验证码')
return
}
if (!/^\d{6}$/.test(code.value)) {
showToast('请输入6位验证码')
return
}
isLoading.value = true
setTimeout(() => {
setToken(TEST_TOKEN)
uni.setStorageSync('memberInfo', TEST_MEMBER_INFO)
showToast('登录成功')
setTimeout(() => {
uni.switchTab({ url: '/pages/memberInfo/memberInfo' })
}, 1500)
isLoading.value = false
}, 500)
}
onUnmounted(() => {
if (timer) clearInterval(timer)
})
</script>
<style lang="scss" scoped>
// 自定义Toast弹窗样式
.custom-toast {
position: fixed;
top: -100rpx;
left: 50%;
transform: translateX(-50%) translateY(0);
background: rgba(0, 0, 0, 0.8);
border-radius: $radius-lg;
padding: 24rpx 48rpx;
z-index: 9999;
opacity: 0;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
&.show {
top: 120rpx;
opacity: 1;
}
.toast-text {
color: $text-inverse;
font-size: 28rpx;
white-space: nowrap;
}
}
button::after {
display: none;
}
.login-page {
min-height: 100vh;
background: $bg-gradient-primary;
display: flex;
flex-direction: column;
padding: 48rpx;
}
.login-header {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 80rpx;
}
.logo-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
.logo-image {
width: 140rpx;
height: 140rpx;
border-radius: $radius-lg;
box-shadow: $shadow-lg;
}
.app-name {
margin-top: 24rpx;
font-size: 42rpx;
font-weight: $font-weight-extrabold;
color: $primary-dark;
letter-spacing: 4rpx;
}
.app-slogan {
margin-top: 12rpx;
font-size: 26rpx;
color: $text-light;
}
.card-container {
position: relative;
width: 100%;
height: 620rpx;
}
.login-card {
position: absolute;
height: 700rpx;
background: $bg-white;
border-radius: $radius-lg;
padding: 48rpx 40rpx;
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
will-change: transform, z-index, filter;
}
.sms-card {
z-index: 1;
top: -60rpx;
left: -100rpx;
box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.12);
filter: blur(10rpx);
&.active {
z-index: 10;
top: 0;
left: 0;
box-shadow: 0 24rpx 60rpx rgba(0, 0, 0, 0.18), 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
filter: blur(0);
}
}
.phone-card {
z-index: 10;
top: 0;
left: 0;
box-shadow: 0 24rpx 60rpx rgba(0, 0, 0, 0.18), 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
filter: blur(0);
&:not(.active) {
z-index: 1;
top: -60rpx;
left: -100rpx;
box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.12);
filter: blur(10rpx);
}
}
.card-body {
display: flex;
flex-direction: column;
align-items: center;
}
.phone-display {
font-size: 48rpx;
font-weight: $font-weight-bold;
color: $text-dark;
margin-bottom: 12rpx;
}
.auth-tip {
font-size: 24rpx;
color: $text-light;
margin-bottom: 40rpx;
}
.form-group {
width: 100%;
margin-bottom: 24rpx;
}
.phone-login{
margin-bottom: 150rpx;
}
.input-wrapper {
display: flex;
align-items: center;
background: transparent;
padding: 0 32rpx;
height: 100rpx;
border-bottom: 2rpx solid $border-light;
&.code-input {
padding-right: 16rpx;
}
}
.phone-input {
flex: 1;
font-size: 34rpx;
color: $text-dark;
letter-spacing: 2rpx;
}
.send-code-btn {
width: 200rpx;
height: 72rpx;
background: $accent-orange;
color: $text-inverse;
font-size: 26rpx;
border-radius: $radius-sm;
border: none;
&.disabled {
background: $border-light;
color: $text-light;
}
}
.login-btn {
width: 100%;
height: 100rpx;
border-radius: $radius-md;
border: none;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.3s ease;
&.primary {
background: $gradient-orange;
color: $text-inverse;
font-size: 34rpx;
font-weight: $font-weight-bold;
box-shadow: $shadow-orange-glow;
&:active {
transform: scale(0.98);
opacity: 0.9;
}
&.disabled {
background: $border-light;
color: $text-light;
box-shadow: none;
}
&.loading {
background: $accent-orange;
}
}
&.secondary {
background: #F8F9FA;
color: $text-dark;
font-size: 30rpx;
font-weight: $font-weight-medium;
margin-top: 24rpx;
&:active {
background: #E9ECEF;
}
}
}
.agreement-text {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
font-size: 24rpx;
color: $text-light;
margin-top: 36rpx;
.link {
color: $accent-orange;
margin: 0 6rpx;
}
&.shake {
animation: shake 0.5s ease-in-out;
}
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-8rpx); }
20%, 40%, 60%, 80% { transform: translateX(8rpx); }
}
</style>
@@ -117,77 +117,74 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { memberCardMock } from '@/common/memberInfo/mockData.js'
import {
loadMemberStore,
computeRemainingDays,
renewMemberCard
} from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
import { backToMemberCenter } from '@/common/constants/routes.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
card: {},
recordTabs: memberCardMock.recordTabs,
records: [],
rules: memberCardMock.rules,
activeFilter: 'all'
}
},
computed: {
filteredRecords() {
if (this.activeFilter === 'all') {
return this.records
}
return this.records.filter((item) => item.type === this.activeFilter)
},
remainingDays() {
return computeRemainingDays(this.card.validityEnd)
}
},
onShow() {
this.refreshFromStore()
},
methods: {
refreshFromStore() {
const store = loadMemberStore()
this.card = { ...store.card }
this.records = store.records.map((item) => ({ ...item }))
},
switchFilter(filter) {
this.activeFilter = filter
},
renewCard() {
uni.showModal({
title: '续费会员卡',
content: '确认续费 90 天?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
renewMemberCard(store, 90)
this.activeFilter = 'all'
this.refreshFromStore()
uni.showToast({ title: '续费成功', icon: 'success' })
}
})
},
showRecordDetail(item) {
uni.showModal({
title: item.title,
content: `${item.time}\n变动:${item.value}`,
showCancel: false
})
}
const card = ref({})
const recordTabs = ref([])
const records = ref([])
const rules = ref([])
const activeFilter = ref('all')
const filteredRecords = computed(() => {
if (activeFilter.value === 'all') {
return records.value
}
return records.value.filter((item) => item.type === activeFilter.value)
})
const remainingDays = computed(() => {
return computeRemainingDays(card.value.validityEnd)
})
function refreshFromStore() {
const store = loadMemberStore()
card.value = { ...store.card }
records.value = store.records.map((item) => ({ ...item }))
}
function goBack() {
backToMemberCenter()
}
function switchFilter(filter) {
activeFilter.value = filter
}
function renewCard() {
uni.showModal({
title: '续费会员卡',
content: '确认续费 90 天?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
renewMemberCard(store, 90)
activeFilter.value = 'all'
refreshFromStore()
uni.showToast({ title: '续费成功', icon: 'success' })
}
})
}
function showRecordDetail(item) {
uni.showModal({
title: item.title,
content: `${item.time}\n变动:${item.value}`,
showCancel: false
})
}
refreshFromStore()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -0,0 +1,758 @@
<template>
<scroll-view scroll-y class="scroll-container theme-light">
<view class="member-page">
<!-- Header: 用户信息区 -->
<view class="profile-header">
<view class="profile-header__toolbar" :style="toolbarStyle">
<view class="profile-header__nav">
<view class="profile-header__nav-left">
<image
class="profile-header__icon-bell"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/bell.png"
mode="aspectFit"
/>
<image
class="profile-header__icon-settings"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/settings.png"
mode="aspectFit"
/>
</view>
<text class="profile-header__title">个人中心</text>
<view class="profile-header__nav-right" :style="navRightStyle"></view>
</view>
</view>
<view class="profile-header__toolbar-spacer" :style="toolbarSpacerStyle"></view>
<view class="profile-header__hero">
<view class="profile-header__inner">
<view class="profile-header__user" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goUserInfo">
<view class="profile-header__user-inner">
<view class="profile-header__avatar-wrap">
<view class="profile-header__avatar-ring">
<image
class="profile-header__avatar"
:key="userInfo.avatar"
:src="displayAvatar"
mode="aspectFill"
/>
</view>
<view class="profile-header__avatar-badge">
<image
class="profile-header__avatar-badge-icon"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/camera.png"
mode="aspectFit"
/>
</view>
</view>
<view class="profile-header__user-meta">
<view class="profile-header__user-meta-inner">
<text class="profile-header__name">{{ userInfo.name }}</text>
<text class="profile-header__phone">{{ userInfo.phone }}</text>
<view class="profile-header__badge">
<image
class="profile-header__badge-icon"
src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/crown0.png"
mode="aspectFit"
/>
<text class="profile-header__level">{{ userInfo.memberLevel }}</text>
</view>
</view>
</view>
</view>
</view>
<view class="profile-header__stats">
<view class="profile-header__stats-inner">
<view class="profile-header__stat">
<view class="profile-header__stat-inner">
<text class="profile-header__stat-value">{{ stats.checkInCount }}</text>
<text class="profile-header__stat-label">累计签到</text>
</view>
</view>
<view class="profile-header__stat-divider"></view>
<view class="profile-header__stat">
<view class="profile-header__stat-inner">
<text class="profile-header__stat-value">{{ stats.trainingHours }}</text>
<text class="profile-header__stat-label">训练时长</text>
</view>
</view>
<view class="profile-header__stat-divider"></view>
<view class="profile-header__stat">
<view class="profile-header__stat-inner">
<text class="profile-header__stat-value">{{ stats.pointsBalance }}</text>
<text class="profile-header__stat-label">累计积分</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="member-page__body">
<view class="member-page__sections">
<!-- 会员卡区域 -->
<view class="member-card-section">
<view class="member-card-section__inner">
<view class="member-card-section__head">
<view class="member-card-section__head-inner">
<text class="member-card-section__title">我的会员卡</text>
<view class="member-card-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goMemberCard">
<text class="member-card-section__link-text">查看全部</text>
<image class="member-card-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright12.png" mode="aspectFit" />
</view>
</view>
</view>
<view class="member-card-preview" hover-class="mi-tap-card--hover" :hover-stay-time="150" @tap="goMemberCard">
<view class="member-card-preview__inner">
<view class="member-card-preview__head">
<view class="member-card-preview__head-inner">
<view class="member-card-preview__type-row">
<view class="member-card-preview__icon-wrap">
<view class="member-card-preview__icon-border">
<view class="member-card-preview__icon-bg"></view>
<view class="member-card-preview__icon-stroke"></view>
</view>
<image class="member-card-preview__icon-line" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Line_2_468.png" mode="aspectFill" />
</view>
<text class="member-card-preview__name">{{ cardInfo.name }}</text>
</view>
<view class="member-card-preview__tag">
<text class="member-card-preview__tag-text">{{ cardInfo.detailTag || '详情' }}</text>
</view>
</view>
</view>
<text class="member-card-preview__expire">{{ cardInfo.expireDate }}</text>
<view class="member-card-preview__footer">
<view class="member-card-preview__footer-inner">
<view class="member-card-preview__days">
<text class="member-card-preview__days-num">{{ cardInfo.remainingDays }}</text>
<text class="member-card-preview__days-unit">天剩余</text>
</view>
<view class="member-card-preview__renew" hover-class="mi-tap-btn--hover" :hover-stay-time="150" @tap.stop="onRenewCard">
<text class="member-card-preview__renew-text">续费</text>
</view>
</view>
</view>
</view>
</view>
<view class="member-card-tip">
<view class="member-card-tip__inner">
<view class="member-card-tip__content">
<image class="member-card-tip__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/clock1.png" mode="aspectFit" />
<text class="member-card-tip__text">{{ cardInfo.tip }}</text>
</view>
</view>
<view class="member-card-tip__border"></view>
</view>
</view>
</view>
<!-- 快捷操作区域 -->
<view class="quick-actions">
<view class="quick-actions__inner">
<view class="quick-actions__grid">
<view class="quick-actions__grid-inner">
<view v-for="item in quickActionsRow1" :key="item.key" class="quick-actions__item" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="onQuickAction(item.key)">
<view class="quick-actions__item-inner">
<view class="quick-actions__icon-wrap">
<view class="quick-actions__icon-wrap-inner">
<view v-if="item.key === 'booking'" class="quick-actions__icon">
<image class="quick-actions__icon-part" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Vector_2_490.png" mode="aspectFit" />
<image class="quick-actions__icon-part" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Vector_2_491.png" mode="aspectFit" />
<view class="quick-actions__border-wrap">
<view class="quick-actions__rect"></view>
<view class="quick-actions__border"></view>
</view>
<image class="quick-actions__icon-part" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Vector_2_493.png" mode="aspectFit" />
<image class="quick-actions__icon-part" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Vector_2_494.png" mode="aspectFit" />
</view>
<image v-else class="quick-actions__icon-img" :src="item.icon" mode="aspectFit" />
</view>
</view>
<text :class="item.textClass">{{ item.label }}</text>
</view>
</view>
</view>
</view>
<view class="quick-actions__divider"></view>
<view class="quick-actions__grid">
<view class="quick-actions__grid-inner">
<view v-for="item in quickActionsRow2" :key="item.key" class="quick-actions__item" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="onQuickAction(item.key)">
<view class="quick-actions__item-inner">
<view class="quick-actions__icon-wrap">
<view class="quick-actions__icon-wrap-inner">
<image class="quick-actions__icon-img" :src="item.icon" mode="aspectFit" />
</view>
</view>
<text :class="item.textClass">{{ item.label }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- 预约课程区域 -->
<view class="booking-section">
<view class="booking-section__inner">
<view class="booking-section__header">
<view class="booking-section__header-inner">
<text class="booking-section__title">我的预约</text>
<view class="booking-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goBooking">
<text class="booking-section__view-all">预约记录</text>
<image class="booking-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright4.png" mode="aspectFit" />
</view>
</view>
</view>
<view v-for="item in bookingPreview" :key="item.id" class="booking-section__item" hover-class="mi-tap-row--hover" :hover-stay-time="150" @tap="goBooking">
<view class="booking-section__item-inner">
<view class="booking-section__date">
<view class="booking-section__date-inner">
<text class="booking-section__num">{{ item.dateDay }}</text>
<text class="booking-section__date-sub">{{ item.dateMonth }}</text>
</view>
</view>
<view class="booking-section__content">
<view class="booking-section__content-inner">
<text class="booking-section__desc">{{ item.desc }}</text>
<view class="booking-section__meta">
<view class="booking-section__meta-inner">
<image class="booking-section__icon-coach" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/user2.png" mode="aspectFit" />
<text class="booking-section__coach">教练{{ item.coach }}</text>
<image class="booking-section__icon-location" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/mappin1.png" mode="aspectFit" />
<text class="booking-section__text">{{ item.location }}</text>
</view>
</view>
</view>
</view>
<view class="booking-section__status-wrap">
<view class="booking-section__status-badge" :class="'booking-section__status-badge--' + item.status">
<text class="booking-section__status-text" :class="{ 'booking-section__status-text--pending': item.status === 'pending' }">{{ item.statusLabel }}</text>
</view>
</view>
</view>
</view>
<view v-if="!bookingPreview.length" class="booking-section__empty">
<text class="booking-section__empty-text">暂无进行中的预约</text>
</view>
</view>
</view>
<!-- 签到记录区域 -->
<view class="checkin-section">
<view class="checkin-section__inner">
<view class="checkin-section__header">
<view class="checkin-section__header-inner">
<text class="checkin-section__title">签到记录</text>
<view class="checkin-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goCheckInHistory">
<text class="checkin-section__view-all">查看全部</text>
<image class="checkin-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright2.png" mode="aspectFit" />
</view>
</view>
</view>
<view class="checkin-section__list">
<view class="checkin-section__list-inner">
<view v-for="(item, index) in checkIns" :key="item.id" class="checkin-section__row">
<view v-if="index > 0" class="checkin-section__divider"></view>
<view class="checkin-section__item" hover-class="mi-tap-row--hover" :hover-stay-time="150" @tap="onCheckInTap(item)">
<view class="checkin-section__item-inner">
<view class="checkin-section__dot" :class="'checkin-section__dot--' + item.tagTheme"></view>
<view class="checkin-section__content">
<view class="checkin-section__content-inner">
<text class="checkin-section__desc">{{ item.title }}</text>
<text class="checkin-section__text">{{ item.time }}</text>
</view>
</view>
<view class="checkin-section__tag-badge" :class="'checkin-section__tag-badge--' + item.tagTheme">
<text class="checkin-section__tag-text" :class="'checkin-section__tag-text--' + item.tagTheme">{{ item.tag }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- 体测报告区域 -->
<view class="body-report-section">
<view class="body-report-section__inner">
<view class="body-report-section__header">
<view class="body-report-section__header-inner">
<text class="body-report-section__title">体测报告</text>
<view class="body-report-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goBodyTestHistory">
<text class="body-report-section__history-link">历史记录</text>
<image class="body-report-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright3.png" mode="aspectFit" />
</view>
</view>
</view>
<view class="body-report-section__card">
<view class="body-report-section__card-inner">
<view class="body-report-section__card-head">
<view class="body-report-section__card-head-inner">
<text class="body-report-section__desc">最新数据 · {{ bodyReport.date }}</text>
<view class="body-report-section__view-btn" hover-class="mi-tap-btn--hover" :hover-stay-time="150" @tap="goBodyReport">
<image class="body-report-section__view-icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/filetext.png" mode="aspectFit" />
<text class="body-report-section__view-report">查看报告</text>
</view>
</view>
</view>
<view class="body-report-section__metrics">
<view class="body-report-section__metrics-inner">
<view class="body-report-section__metric">
<view class="body-report-section__metric-inner">
<text class="body-report-section__text">{{ bodyReport.weight }}</text>
<text class="body-report-section__metric-value">体重(kg)</text>
</view>
</view>
<view class="body-report-section__metric-divider"></view>
<view class="body-report-section__metric">
<view class="body-report-section__metric-inner">
<text class="body-report-section__text-2">{{ bodyReport.bmi }}</text>
<text class="body-report-section__text-3">BMI</text>
</view>
</view>
<view class="body-report-section__metric-divider"></view>
<view class="body-report-section__metric">
<view class="body-report-section__metric-inner">
<text class="body-report-section__text-4">{{ bodyReport.bodyFat }}</text>
<text class="body-report-section__metric-label">体脂率</text>
</view>
</view>
<view class="body-report-section__metric-divider"></view>
<view class="body-report-section__metric">
<view class="body-report-section__metric-inner">
<text class="body-report-section__num">{{ bodyReport.bmr }}</text>
<text class="body-report-section__text-5">BMR</text>
</view>
</view>
</view>
</view>
<view class="body-report-section__summary">
<view class="body-report-section__summary-inner">
<view class="body-report-section__goal">
<image class="body-report-section__goal-icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/target.png" mode="aspectFit" />
<text class="body-report-section__goal-text">状态{{ bodyReport.status }}</text>
</view>
<view class="body-report-section__change">
<image class="body-report-section__change-icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/trendingdown.png" mode="aspectFit" />
<text class="body-report-section__metric-value-2">较上次 {{ bodyReport.change }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- 优惠券&积分区域 -->
<view class="coupon-section">
<view class="coupon-section__inner">
<view class="coupon-section__header">
<view class="coupon-section__header-inner">
<text class="coupon-section__title">优惠券 & 积分</text>
<view class="coupon-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goCoupons">
<text class="coupon-section__view-all">更多详情</text>
<image class="coupon-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright5.png" mode="aspectFit" />
</view>
</view>
</view>
<view class="coupon-section__cards">
<view class="coupon-section__cards-inner">
<view class="coupon-section__coupon" hover-class="mi-tap-card--hover" :hover-stay-time="150" @tap="goCoupons">
<view class="coupon-section__coupon-inner">
<text class="coupon-section__amount">{{ couponPoints.amount }}</text>
<text class="coupon-section__desc">{{ couponPoints.couponDesc }}</text>
<view class="coupon-section__coupon-status">
<text class="coupon-section__status">{{ couponPoints.couponAction }}</text>
</view>
</view>
</view>
<view class="coupon-section__points" hover-class="mi-tap-card--hover" :hover-stay-time="150" @tap="goPoints">
<view class="coupon-section__points-inner">
<text class="coupon-section__num">{{ couponPoints.points }}</text>
<text class="coupon-section__points-label">{{ couponPoints.pointsLabel }}</text>
<view class="coupon-section__points-action">
<text class="coupon-section__text">{{ couponPoints.pointsAction }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- 推荐奖励区域 -->
<view class="referral-section">
<view class="referral-section__inner">
<view class="referral-section__header">
<text class="referral-section__title">推荐奖励</text>
<view class="referral-section__link" hover-class="mi-tap--hover" :hover-stay-time="150" @tap="goReferral">
<text class="referral-section__records-link">规则说明</text>
<image class="referral-section__link-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright11.png" mode="aspectFit" />
</view>
</view>
<view class="referral-section__code-row">
<view class="referral-section__code-box">
<text class="referral-section__code-label">我的邀请码</text>
<text class="referral-section__code-value">{{ referral.code }}</text>
</view>
<view class="referral-section__copy-btn" hover-class="mi-tap-btn--hover" :hover-stay-time="150" @tap="copyReferralCode">
<view class="referral-section__copy-icon">
<view class="referral-section__copy-sheet referral-section__copy-sheet--back"></view>
<view class="referral-section__copy-sheet referral-section__copy-sheet--front"></view>
</view>
<text class="referral-section__copy-text">复制</text>
</view>
</view>
<view class="referral-section__stats">
<view class="referral-section__stat">
<text class="referral-section__stat-num referral-section__stat-num--orange">{{ referral.invited }}</text>
<text class="referral-section__stat-label">已推荐</text>
</view>
<view class="referral-section__stat-divider"></view>
<view class="referral-section__stat">
<text class="referral-section__stat-num referral-section__stat-num--green">{{ referral.registered }}</text>
<text class="referral-section__stat-label">已注册</text>
</view>
<view class="referral-section__stat-divider"></view>
<view class="referral-section__stat">
<text class="referral-section__stat-num referral-section__stat-num--amber">{{ referral.purchased }}</text>
<text class="referral-section__stat-label">已购课</text>
</view>
</view>
</view>
</view>
<!-- 设置区域 -->
<view class="settings-section">
<view class="settings-section__inner">
<text class="settings-section__title">设置与安全</text>
<view class="settings-section__list">
<view class="settings-section__list-inner">
<view v-for="(item, index) in settingsItems" :key="item.key">
<view v-if="index > 0" class="settings-section__item-divider"></view>
<view class="settings-section__item" :class="{ 'settings-section__item--tall': item.subtitle }" hover-class="mi-tap-row--hover" :hover-stay-time="150" @tap="onSetting(item.key)">
<view class="settings-section__item-inner">
<view class="settings-section__item-icon-wrap" :class="item.iconWrapClass">
<image class="settings-section__item-icon" :src="item.icon" mode="aspectFit" />
</view>
<view v-if="item.subtitle" class="settings-section__item-texts">
<text class="settings-section__item-title">{{ item.label }}</text>
<text class="settings-section__item-desc">{{ item.subtitle }}</text>
</view>
<text v-else class="settings-section__item-label" :class="item.labelClass">{{ item.label }}</text>
<image class="settings-section__item-arrow" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/chevronright10.png" mode="aspectFit" />
</view>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- 退出登录 -->
<view class="logout-section">
<view class="logout-section__btn" hover-class="mi-tap-btn--hover" :hover-stay-time="150" @tap="handleLogout">
<image class="logout-section__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/logout.png" mode="aspectFit" />
<text class="logout-section__text">退出登录</text>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
<!-- 固定 TabBar -->
<view class="tabbar-fixed">
<TabBar />
</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { loadMemberStore, getCenterPageData, renewMemberCard } from '@/common/memberInfo/store.js'
import TabBar from '@/components/TabBar.vue'
// 页面数据
const userInfo = ref({})
const stats = ref({})
const cardInfo = ref({})
const bookingPreview = ref([])
const checkIns = ref([])
const bodyReport = ref({})
const couponPoints = ref({})
const referral = ref({})
// 导航栏样式
const toolbarStyle = ref({})
const toolbarSpacerStyle = ref({})
const navRightStyle = ref({})
// 快捷操作配置
const quickActionsRow1 = ref([
{ key: 'booking', label: '预约课程', textClass: 'quick-actions__title', icon: '' },
{ key: 'bodyTest', label: '智能体测', textClass: 'quick-actions__title-2', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/mappin2.png' },
{ key: 'bodyReport', label: '体测报告', textClass: 'quick-actions__title-3', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/activity.png' },
{ key: 'trainReport', label: '训练报告', textClass: 'quick-actions__coach', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/usercheck.png' }
])
const quickActionsRow2 = ref([
{ key: 'coupon', label: '我的优惠券', textClass: 'quick-actions__text', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/ticket.png' },
{ key: 'points', label: '我的积分', textClass: 'quick-actions__points-desc', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/star.png' },
{ key: 'referral', label: '邀请好友', textClass: 'quick-actions__title-4', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/share2.png' },
{ key: 'course', label: '我的课程', textClass: 'quick-actions__text-2', icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/play.png' }
])
// 设置项配置
const settingsItems = ref([
{
key: 'notify',
label: '通知设置',
icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/bell.png',
iconWrapClass: ''
},
{
key: 'password',
label: '修改密码',
icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/Vector_2_727.png',
iconWrapClass: 'settings-section__item-icon-wrap--blue'
},
{
key: 'privacy',
label: '隐私政策',
icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/shield.png',
iconWrapClass: 'settings-section__item-icon-wrap--green'
},
{
key: 'nfc',
label: 'NFC 门禁卡',
subtitle: '已绑定',
icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/ticket.png',
iconWrapClass: ''
},
{
key: 'delete',
label: '注销账户',
icon: 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/userx.png',
iconWrapClass: 'settings-section__item-icon-wrap--red',
labelClass: 'settings-section__item-label--danger'
}
])
// 计算属性
const displayAvatar = computed(() => {
return userInfo.value.avatar || 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/AvatarEditWrap.png'
})
// 方法
function syncNavSafeArea() {
try {
const sys = uni.getSystemInfoSync()
const statusBarHeight = sys.statusBarHeight || 0
const navHeight = 44
const menu = uni.getMenuButtonBoundingClientRect?.()
toolbarStyle.value = {
paddingTop: `${statusBarHeight}px`
}
toolbarSpacerStyle.value = {
height: `${statusBarHeight + navHeight}px`
}
if (menu && menu.width) {
const capsuleGap = sys.windowWidth - menu.left + 8
navRightStyle.value = {
width: `${capsuleGap}px`,
minWidth: `${capsuleGap}px`
}
}
} catch (e) {
toolbarSpacerStyle.value = { height: '44px' }
}
}
function refreshFromStore() {
const store = loadMemberStore()
const pageData = getCenterPageData(store)
userInfo.value = pageData.userInfo
stats.value = pageData.stats
cardInfo.value = pageData.cardInfo
bookingPreview.value = pageData.bookingPreview
checkIns.value = pageData.checkIns
bodyReport.value = pageData.bodyReport
couponPoints.value = pageData.couponPoints
referral.value = pageData.referral
}
function goUserInfo() {
navigateToPage(PAGE.USER_INFO)
}
function goMemberCard() {
navigateToPage(PAGE.MEMBER_CARD)
}
function goBooking() {
navigateToPage(PAGE.BOOKING)
}
function goCheckInHistory() {
navigateToPage(PAGE.CHECK_IN_HISTORY)
}
function goBodyTestHistory() {
navigateToPage(PAGE.BODY_TEST_HISTORY)
}
function goBodyReport() {
const id = bodyReport.value?.recordId
const url = id ? `${PAGE.BODY_TEST_REPORT}?id=${id}` : PAGE.BODY_TEST_HISTORY
navigateToPage(url)
}
function goCoupons() {
navigateToPage(PAGE.COUPONS)
}
function goPoints() {
navigateToPage(PAGE.POINTS)
}
function goReferral() {
navigateToPage(PAGE.REFERRAL)
}
function onRenewCard() {
uni.showModal({
title: '续费会员卡',
content: '确认续费 90 天?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
renewMemberCard(store, 90)
refreshFromStore()
uni.showToast({ title: '续费成功', icon: 'success' })
}
})
}
function onQuickAction(type) {
const routes = {
booking: PAGE.COURSE_LIST,
bodyTest: PAGE.BODY_TEST_HOME,
bodyReport: PAGE.BODY_TEST_HISTORY,
trainReport: PAGE.TRAIN_REPORT,
coupon: PAGE.COUPONS,
points: PAGE.POINTS,
referral: PAGE.REFERRAL,
course: PAGE.MY_COURSES
}
if (routes[type]) {
navigateToPage(routes[type])
}
}
function onCheckInTap(item) {
uni.showModal({
title: item.title,
content: item.time,
showCancel: false
})
}
function copyReferralCode() {
uni.setClipboardData({
data: referral.value.code,
success: () => {
uni.showToast({ title: '已复制', icon: 'success' })
}
})
}
function onSetting(key) {
const labels = {
notify: '通知设置',
password: '修改密码',
privacy: '隐私政策',
nfc: 'NFC 门禁卡',
delete: '注销账户'
}
if (key === 'delete') {
uni.showModal({
title: '注销账户',
content: '注销后数据将无法恢复,确定继续吗?',
confirmColor: '#E74C3C'
})
return
}
if (key === 'privacy') {
uni.showModal({
title: '隐私政策',
content: '我们重视您的隐私,详细政策请前往官网查看。',
showCancel: false
})
return
}
uni.showToast({
title: `${labels[key] || '设置'}开发中`,
icon: 'none'
})
}
function handleLogout() {
uni.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
uni.showToast({ title: '已退出', icon: 'success' })
}
}
})
}
onMounted(() => {
syncNavSafeArea()
refreshFromStore()
})
</script>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-tap.css';
@import '@/common/style/memberInfo/member-info-page.css';
@import '@/common/style/memberInfo/member-info-header.css';
@import '@/common/style/memberInfo/member-info-member-card.css';
@import '@/common/style/memberInfo/member-info-quick-actions.css';
@import '@/common/style/memberInfo/member-info-booking-list.css';
@import '@/common/style/memberInfo/member-info-check-in-list.css';
@import '@/common/style/memberInfo/member-info-body-report.css';
@import '@/common/style/memberInfo/member-info-coupon-points.css';
@import '@/common/style/memberInfo/member-info-referral.css';
@import '@/common/style/memberInfo/member-info-settings.css';
@import '@/common/style/memberInfo/member-info-logout.css';
.tabbar-fixed {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 1000;
background-color: transparent;
}
.booking-section__empty {
display: flex;
align-items: center;
justify-content: center;
padding: 24px 16px;
}
.booking-section__empty-text {
font-size: 14px;
color: #8A99B4;
}
</style>
+315 -152
View File
@@ -5,7 +5,9 @@
<MemberInfoHeader
:user-info="userInfo"
:stats="stats"
:isLogin="isLogin"
@user-info="goUserInfo"
@guest-login="handleGuestLogin"
/>
<view class="member-page__body">
<view class="member-page__sections">
@@ -13,35 +15,41 @@
:card-info="cardInfo"
@view-all="goMemberCard"
@renew="onRenewCard"
@purchase="goPurchaseCard"
/>
<MemberInfoQuickActions @action="onQuickAction" />
<MemberInfoBookingList
v-if="isLogin"
:items="bookingPreview"
@view-all="goBooking"
@item-tap="goBooking"
/>
<MemberInfoCheckInList
v-if="isLogin"
:items="checkIns"
@view-all="onCheckInViewAll"
@item-tap="onCheckInTap"
/>
<MemberInfoBodyReport
v-if="isLogin"
:report="bodyReport"
@view-history="onBodyReportHistory"
@view-report="onBodyReportView"
/>
<MemberInfoCouponPoints
v-if="isLogin"
:data="couponPoints"
@view-all="onCouponViewAll"
@use-coupon="onUseCoupon"
@redeem-points="onRedeemPoints"
/>
<MemberInfoReferral
v-if="isLogin"
:data="referral"
@view-rules="onReferralRules"
/>
<MemberInfoSettings @setting="onSetting" />
<MemberInfoLogout @logout="handleLogout" />
<MemberInfoSettings v-if="isLogin" @setting="onSetting" />
<MemberInfoLogout v-if="isLogin" @logout="handleLogout" />
</view>
</view>
</view>
@@ -53,13 +61,19 @@
</view>
</template>
<script>
<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import {
loadMemberStore,
getCenterPageData,
renewMemberCard
renewMemberCard,
saveMemberStore,
getDefaultStore
} from '@/common/memberInfo/store.js'
import { login as miniappLogin, getUserInfo, getMemberDetail, getCheckInStats, updateUserInfo } from '@/api/main.js'
import { setToken, getToken, clearToken } from '@/utils/request.js'
import MemberInfoHeader from '@/components/memberInfo/MemberInfoHeader.vue'
import MemberInfoMemberCard from '@/components/memberInfo/MemberInfoMemberCard.vue'
import MemberInfoQuickActions from '@/components/memberInfo/MemberInfoQuickActions.vue'
@@ -72,162 +86,311 @@ import MemberInfoSettings from '@/components/memberInfo/MemberInfoSettings.vue'
import MemberInfoLogout from '@/components/memberInfo/MemberInfoLogout.vue'
import TabBar from '@/components/TabBar.vue'
export default {
components: {
MemberInfoHeader,
MemberInfoMemberCard,
MemberInfoQuickActions,
MemberInfoBookingList,
MemberInfoCheckInList,
MemberInfoBodyReport,
MemberInfoCouponPoints,
MemberInfoReferral,
MemberInfoSettings,
MemberInfoLogout,
TabBar
},
data() {
return {
userInfo: {},
stats: {},
cardInfo: {},
bookingPreview: [],
checkIns: [],
bodyReport: {},
couponPoints: {},
referral: {}
}
},
onShow() {
this.refreshFromStore()
},
methods: {
refreshFromStore() {
const userInfo = ref({})
const stats = ref({})
const cardInfo = ref({})
const bookingPreview = ref([])
const checkIns = ref([])
const bodyReport = ref({})
const couponPoints = ref({})
const referral = ref({})
const loading = ref(false)
const hasActiveCard = ref(false)
const isLogin = ref(false)
// 页面加载时检查token
onMounted(() => {
const token = getToken()
const isLoginStorage = uni.getStorageSync('isLogin')
if (token || isLoginStorage) {
isLogin.value = true
}
})
async function fetchMemberInfo() {
if (loading.value) return
loading.value = true
console.log('[memberInfo] fetchMemberInfo 开始执行')
try {
const res = await getUserInfo({ cache: false })
console.log('[memberInfo] API返回,res =', res)
const apiData = res.data || res
console.log('[memberInfo] apiData =', apiData)
if (apiData && (apiData.nickname !== undefined || apiData.phone !== undefined || apiData.id !== undefined)) {
console.log('[memberInfo] 收到有效数据,更新store')
const store = loadMemberStore()
const pageData = getCenterPageData(store)
this.userInfo = pageData.userInfo
this.stats = pageData.stats
this.cardInfo = pageData.cardInfo
this.bookingPreview = pageData.bookingPreview
this.checkIns = pageData.checkIns
this.bodyReport = pageData.bodyReport
this.couponPoints = pageData.couponPoints
this.referral = pageData.referral
},
goMemberCard() {
navigateToPage(PAGE.MEMBER_CARD)
},
goBooking() {
navigateToPage(PAGE.BOOKING)
},
goUserInfo() {
navigateToPage(PAGE.USER_INFO)
},
onRenewCard() {
uni.showModal({
title: '续费会员卡',
content: '确认续费 90 天?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
renewMemberCard(store, 90)
this.refreshFromStore()
uni.showToast({ title: '续费成功', icon: 'success' })
// 更新memberProfile
store.memberProfile = {
...store.memberProfile,
id: apiData.id,
name: apiData.nickname || apiData.name,
phone: apiData.phone,
avatar: apiData.avatar,
memberLevel: apiData.memberLevel || '普通会员'
}
// 更新profile
store.profile = {
...store.profile,
id: apiData.id,
name: apiData.nickname || apiData.name,
phone: apiData.phone,
avatar: apiData.avatar,
gender: apiData.gender,
genderDesc: apiData.genderDesc,
birthday: apiData.birthday,
height: apiData.height,
weight: apiData.weight,
hasPhone: apiData.hasPhone,
isSubscribed: apiData.isSubscribed,
memberLevel: apiData.memberLevel || '普通会员'
}
// 获取会员详细信息(会员卡、积分)
try {
const detailRes = await getMemberDetail()
console.log('[memberInfo] getMemberDetail 返回:', JSON.stringify(detailRes, null, 2))
const detailData = detailRes.data || {}
store.card = detailData.memberCards ? detailData.memberCards[0] || {} : {}
store.cardInfo = {
name: detailData.memberCards?.[0]?.memberCardName || '暂无会员卡',
type: detailData.memberCards?.[0]?.memberCardTypeDesc || '',
remainingTimes: detailData.memberCards?.[0]?.memberCardTotalTimes || 0,
status: detailData.memberCards?.[0]?.memberCardStatusDesc || ''
}
})
},
onQuickAction(type) {
const routes = {
booking: PAGE.COURSE_LIST,
bodyTest: PAGE.BODY_TEST_HOME,
bodyReport: PAGE.BODY_TEST_HISTORY,
trainReport: PAGE.TRAIN_REPORT,
coupon: PAGE.COUPONS,
points: PAGE.POINTS,
referral: PAGE.REFERRAL,
course: PAGE.MY_COURSES
}
if (routes[type]) {
navigateToPage(routes[type])
}
},
onCheckInViewAll() {
navigateToPage(PAGE.CHECK_IN_HISTORY)
},
onCheckInTap(item) {
uni.showModal({
title: item.title,
content: item.time,
showCancel: false
})
},
onBodyReportHistory() {
navigateToPage(PAGE.BODY_TEST_HISTORY)
},
onBodyReportView() {
const id = this.bodyReport?.recordId
const url = id
? `${PAGE.BODY_TEST_REPORT}?id=${id}`
: PAGE.BODY_TEST_HISTORY
navigateToPage(url)
},
onCouponViewAll() {
navigateToPage(PAGE.COUPONS)
},
onUseCoupon() {
navigateToPage(PAGE.COUPONS)
},
onRedeemPoints() {
navigateToPage(PAGE.POINTS)
},
onReferralRules() {
navigateToPage(PAGE.REFERRAL)
},
onSetting(key) {
const labels = {
notify: '通知设置',
password: '修改密码',
privacy: '隐私政策',
nfc: 'NFC 门禁卡',
delete: '注销账户'
}
if (key === 'delete') {
uni.showModal({
title: '注销账户',
content: '注销后数据将无法恢复,确定继续吗?',
confirmColor: '#E74C3C'
})
return
}
if (key === 'privacy') {
uni.showModal({
title: '隐私政策',
content: '我们重视您的隐私,详细政策请前往官网查看。',
showCancel: false
})
return
}
uni.showToast({
title: `${labels[key] || '设置'}开发中`,
icon: 'none'
})
},
handleLogout() {
uni.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
uni.showToast({ title: '已退出', icon: 'success' })
}
hasActiveCard.value = (detailData.activeCardCount || 0) > 0
store.stats = {
...store.stats,
pointsBalance: detailData.pointsBalance || 0
}
})
} catch (e) {
console.error('[memberInfo] 获取会员详情失败:', e)
}
// 获取签到统计
try {
const statsRes = await getCheckInStats()
console.log('[memberInfo] getCheckInStats 返回:', JSON.stringify(statsRes, null, 2))
const statsData = statsRes.data || {}
store.stats.checkInCount = statsData.totalCount || 0
} catch (e) {
console.error('[memberInfo] 获取签到统计失败:', e)
store.stats.checkInCount = 0
}
saveMemberStore(store)
refreshFromStore()
console.log('[memberInfo] store已更新')
} else {
console.log('[memberInfo] 未登录或数据无效,使用默认空数据')
const store = loadMemberStore()
store.memberProfile = {}
store.profile = {}
store.stats.checkInCount = 0
hasActiveCard.value = false
saveMemberStore(store)
refreshFromStore()
}
} catch (err) {
console.error('[memberInfo] 获取会员信息失败:', err)
// 失败时使用默认空数据
const store = loadMemberStore()
store.memberProfile = {}
store.profile = {}
store.stats.checkInCount = 0
hasActiveCard.value = false
saveMemberStore(store)
refreshFromStore()
} finally {
loading.value = false
console.log('[memberInfo] fetchMemberInfo 执行完成')
}
}
function refreshFromStore() {
const store = loadMemberStore()
const pageData = getCenterPageData(store)
console.log('[memberInfo] refreshFromStore - pageData.userInfo:', JSON.stringify(pageData.userInfo))
userInfo.value = pageData.userInfo
stats.value = pageData.stats
cardInfo.value = pageData.cardInfo
bookingPreview.value = pageData.bookingPreview
checkIns.value = pageData.checkIns
bodyReport.value = pageData.bodyReport
couponPoints.value = pageData.couponPoints
referral.value = pageData.referral
console.log('[memberInfo] refreshFromStore - userInfo.value:', JSON.stringify(userInfo.value))
}
function goMemberCard() {
navigateToPage(PAGE.MEMBER_CARD)
}
function goPurchaseCard() {
navigateToPage(PAGE.PURCHASE_CARD)
}
function goBooking() {
navigateToPage(PAGE.BOOKING)
}
function goUserInfo() {
navigateToPage(PAGE.USER_INFO)
}
function handleGuestLogin() {
console.log('[memberInfo] 用户点击登录区域')
uni.navigateTo({
url: '/pages/memberInfo/login'
})
}
function onRenewCard() {
uni.showModal({
title: '续费会员卡',
content: '确认续费 90 天?',
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
renewMemberCard(store, 90)
refreshFromStore()
uni.showToast({ title: '续费成功', icon: 'success' })
}
})
}
function onQuickAction(type) {
const routes = {
booking: PAGE.COURSE_LIST,
bodyTest: PAGE.BODY_TEST_HOME,
bodyReport: PAGE.BODY_TEST_HISTORY,
trainReport: PAGE.TRAIN_REPORT,
coupon: PAGE.COUPONS,
points: PAGE.POINTS,
referral: PAGE.REFERRAL,
course: PAGE.MY_COURSES
}
if (routes[type]) {
navigateToPage(routes[type])
}
}
function onCheckInViewAll() {
navigateToPage(PAGE.CHECK_IN_HISTORY)
}
function onCheckInTap(item) {
uni.showModal({
title: item.title,
content: item.time,
showCancel: false
})
}
function onBodyReportHistory() {
navigateToPage(PAGE.BODY_TEST_HISTORY)
}
function onBodyReportView() {
const id = bodyReport.value?.recordId
const url = id
? `${PAGE.BODY_TEST_REPORT}?id=${id}`
: PAGE.BODY_TEST_HISTORY
navigateToPage(url)
}
function onCouponViewAll() {
navigateToPage(PAGE.COUPONS)
}
function onUseCoupon() {
navigateToPage(PAGE.COUPONS)
}
function onRedeemPoints() {
navigateToPage(PAGE.POINTS)
}
function onReferralRules() {
navigateToPage(PAGE.REFERRAL)
}
function onSetting(key) {
const labels = {
notify: '通知设置',
password: '修改密码',
privacy: '隐私政策',
nfc: 'NFC 门禁卡',
delete: '注销账户'
}
if (key === 'delete') {
uni.showModal({
title: '注销账户',
content: '注销后数据将无法恢复,确定继续吗?',
confirmColor: '#E74C3C'
})
return
}
if (key === 'privacy') {
uni.showModal({
title: '隐私政策',
content: '我们重视您的隐私,详细政策请前往官网查看。',
showCancel: false
})
return
}
uni.showToast({
title: `${labels[key] || '设置'}开发中`,
icon: 'none'
})
}
function handleLogout() {
uni.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
// 清除token
clearToken()
// 重置登录状态
isLogin.value = false
// 重置store为默认状态
const defaultStore = getDefaultStore()
saveMemberStore(defaultStore)
// 重置页面数据
userInfo.value = {}
stats.value = {}
cardInfo.value = {}
bookingPreview.value = []
checkIns.value = []
bodyReport.value = {}
couponPoints.value = {}
referral.value = {}
hasActiveCard.value = false
refreshFromStore()
uni.showToast({ title: '已退出', icon: 'success' })
}
}
})
}
refreshFromStore()
onShow(() => {
console.log('[memberInfo] onShow 被调用')
// 检查登录状态
const token = getToken()
const isLoginStorage = uni.getStorageSync('isLogin')
if (token || isLoginStorage) {
isLogin.value = true
} else {
isLogin.value = false
}
fetchMemberInfo()
})
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-tap.css';
+24 -22
View File
@@ -52,35 +52,37 @@
</view>
</template>
<script>
<script setup>
import { ref } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { PAGE, navigateToPage, backToMemberCenter } from '@/common/constants/routes.js'
import { getPointsPageData } from '@/common/memberInfo/moduleStore.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return { balance: 0, config: {}, historyPreview: [] }
},
onShow() {
const data = getPointsPageData(loadMemberStore())
this.balance = data.balance
this.config = data.config
this.historyPreview = data.history.slice(0, 5)
},
methods: {
goMall() { navigateToPage(PAGE.POINTS_MALL) },
goHistory() { navigateToPage(PAGE.POINTS_HISTORY) },
goReferral() { navigateToPage(PAGE.REFERRAL) },
checkIn() { uni.showToast({ title: '签到成功 +10 积分', icon: 'success' }) }
}
const balance = ref(0)
const config = ref({})
const historyPreview = ref([])
function refresh() {
const data = getPointsPageData(loadMemberStore())
balance.value = data.balance
config.value = data.config
historyPreview.value = data.history.slice(0, 5)
}
function goBack() {
backToMemberCenter()
}
function goMall() { navigateToPage(PAGE.POINTS_MALL) }
function goHistory() { navigateToPage(PAGE.POINTS_HISTORY) }
function goReferral() { navigateToPage(PAGE.REFERRAL) }
function checkIn() { uni.showToast({ title: '签到成功 +10 积分', icon: 'success' }) }
refresh()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -41,40 +41,34 @@
</view>
</template>
<script>
<script setup>
import { ref, watch } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { filterPointsHistory } from '@/common/memberInfo/moduleStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return {
filter: 'all',
tabs: [
{ key: 'all', label: '全部' },
{ key: 'earn', label: '获取' },
{ key: 'spend', label: '消耗' }
],
list: []
}
},
watch: {
filter() { this.loadList() }
},
onShow() { this.loadList() },
methods: {
onBack() { goBackOrTab(PAGE.POINTS) },
loadList() {
const store = loadMemberStore()
this.list = filterPointsHistory(store, this.filter)
}
}
const filter = ref('all')
const tabs = ref([
{ key: 'all', label: '全部' },
{ key: 'earn', label: '获取' },
{ key: 'spend', label: '消耗' }
])
const list = ref([])
function onBack() { goBackOrTab(PAGE.POINTS) }
function loadList() {
const store = loadMemberStore()
list.value = filterPointsHistory(store, filter.value)
}
watch(filter, () => { loadList() })
loadList()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -39,49 +39,50 @@
</view>
</template>
<script>
<script setup>
import { ref } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore, persistMemberStore } from '@/common/memberInfo/store.js'
import { getPointsPageData, redeemPointsReward } from '@/common/memberInfo/moduleStore.js'
export default {
components: { MemberInfoSubNav },
data() {
return { balance: 0, rewards: [], redeemRecords: [] }
},
onShow() {
const data = getPointsPageData(loadMemberStore())
this.balance = data.balance
this.rewards = data.rewards
this.redeemRecords = data.redeemRecords
},
methods: {
onBack() { goBackOrTab(PAGE.POINTS) },
redeem(item) {
uni.showModal({
title: '确认兑换',
content: `使用 ${item.cost} 积分兑换「${item.name}」?`,
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
const result = redeemPointsReward(store, item.id)
uni.showToast({ title: result.message, icon: result.ok ? 'success' : 'none' })
if (result.ok) {
persistMemberStore(store)
const data = getPointsPageData(store)
this.balance = data.balance
this.rewards = data.rewards
this.redeemRecords = data.redeemRecords
}
}
})
}
}
const balance = ref(0)
const rewards = ref([])
const redeemRecords = ref([])
function loadData() {
const data = getPointsPageData(loadMemberStore())
balance.value = data.balance
rewards.value = data.rewards
redeemRecords.value = data.redeemRecords
}
function onBack() { goBackOrTab(PAGE.POINTS) }
function redeem(item) {
uni.showModal({
title: '确认兑换',
content: `使用 ${item.cost} 积分兑换「${item.name}」?`,
success: (res) => {
if (!res.confirm) return
const store = loadMemberStore()
const result = redeemPointsReward(store, item.id)
uni.showToast({ title: result.message, icon: result.ok ? 'success' : 'none' })
if (result.ok) {
persistMemberStore(store)
const data = getPointsPageData(store)
balance.value = data.balance
rewards.value = data.rewards
redeemRecords.value = data.redeemRecords
}
}
})
}
loadData()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -0,0 +1,694 @@
<template>
<view class="scroll-container theme-light">
<view class="purchase-card-page">
<MemberInfoSubNav title="购买会员卡" @back="goBack" />
<view class="purchase-card-page__body">
<!-- 头部 -->
<view class="pc-intro">
<view class="pc-intro__icon">
<image src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/crown0.png" mode="aspectFit" />
</view>
<text class="pc-intro__title">选择会员卡类型</text>
<text class="pc-intro__desc">购买后立即生效享受专属会员权益</text>
</view>
<!-- 卡列表 -->
<view class="pc-list">
<view
v-for="card in cardTypes"
:key="card.id"
class="pc-card"
:class="{ 'pc-card--selected': selectedCardId === card.id }"
@tap="selectCard(card)"
>
<view class="pc-card__check">
<view
class="pc-card__check-inner"
:class="{ 'pc-card__check-inner--checked': selectedCardId === card.id }"
></view>
</view>
<view class="pc-card__content">
<view class="pc-card__header">
<text class="pc-card__name">{{ card.cardName }}</text>
<view class="pc-card__tag" :class="'pc-card__tag--' + getTagClass(card.cardType)">
<text class="pc-card__tag-text">{{ getCardTypeName(card.cardType) }}</text>
</view>
</view>
<view class="pc-card__info">
<view class="pc-card__info-row" v-if="card.validityDays">
<text class="pc-card__info-label">有效期</text>
<text class="pc-card__info-value">{{ card.validityDays }}</text>
</view>
<view class="pc-card__info-row" v-if="card.cardType === 'COUNT' && card.totalTimes">
<text class="pc-card__info-label">总次数</text>
<text class="pc-card__info-value">{{ card.totalTimes }}</text>
</view>
<view class="pc-card__info-row" v-if="card.cardType === 'BALANCE' && card.amount">
<text class="pc-card__info-label">储值金额</text>
<text class="pc-card__info-value">{{ card.amount }}</text>
</view>
<view class="pc-card__info-row" v-if="card.description">
<text class="pc-card__info-label">说明</text>
<text class="pc-card__info-value">{{ card.description }}</text>
</view>
</view>
<view class="pc-card__footer">
<text class="pc-card__price">¥{{ card.price }}</text>
<text class="pc-card__original-price" v-if="card.originalPrice && card.originalPrice !== card.price">¥{{ card.originalPrice }}</text>
</view>
</view>
</view>
</view>
<!-- 支付方式 -->
<view class="pc-payment">
<text class="pc-payment__title">支付方式</text>
<view class="pc-payment__methods">
<view class="pc-payment__method pc-payment__method--selected">
<image src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/alipay.png" mode="aspectFit" class="pc-payment__icon" />
<text class="pc-payment__name">支付宝支付</text>
<view class="pc-payment__check"></view>
</view>
</view>
</view>
<!-- 底部 -->
<view class="pc-bottom">
<view class="pc-bottom__total">
<text class="pc-bottom__total-label">合计</text>
<text class="pc-bottom__total-price">¥{{ selectedCard?.price || 0 }}</text>
</view>
<view
class="pc-bottom__btn"
:class="{ 'pc-bottom__btn--disabled': !selectedCard || loading }"
@tap="handlePurchase"
>
<text class="pc-bottom__btn-text">{{ loading ? '处理中...' : '立即购买' }}</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onBackPress } from '@dcloudio/uni-app'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { purchaseMemberCard, createPayment, getPaymentStatus } from '@/api/main.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
const cardTypes = ref([
{ id: 1, cardName: '月卡', cardType: 'DURATION', validityDays: 30, price: 1, originalPrice: 399 },
{ id: 2, cardName: '季卡', cardType: 'DURATION', validityDays: 90, price: 1, originalPrice: 999 },
{ id: 3, cardName: '年卡', cardType: 'DURATION', validityDays: 365, price: 1, originalPrice: 2999 },
{ id: 4, cardName: '10次卡', cardType: 'COUNT', validityDays: 90, totalTimes: 10, price: 1 },
{ id: 5, cardName: '50次卡', cardType: 'COUNT', validityDays: 180, totalTimes: 50, price: 1 },
{ id: 6, cardName: '100次卡', cardType: 'COUNT', validityDays: 365, totalTimes: 100, price: 1 },
{ id: 7, cardName: '储值500', cardType: 'BALANCE', validityDays: 365, amount: 500, price: 1 },
{ id: 8, cardName: '储值1000', cardType: 'BALANCE', validityDays: 365, amount: 1000, price: 1 },
])
const selectedCardId = ref(null)
const loading = ref(false)
const selectedCard = ref(null)
const pollingTimer = ref(null)
const isPolling = ref(false)
// 支付方式
const TRADE_TYPE = 'ALIPAY'
// ==================== 工具函数 ====================
function getCardTypeName(type) {
const map = { DURATION: '时长卡', COUNT: '次卡', BALANCE: '储值卡' }
return map[type] || type
}
function getTagClass(type) {
const map = { DURATION: 'time', COUNT: 'count', BALANCE: 'value' }
return map[type] || 'default'
}
function selectCard(card) {
selectedCardId.value = card.id
selectedCard.value = card
}
function goBack() {
uni.redirectTo({
url: '/pages/memberInfo/memberCard'
})
}
onBackPress(() => {
uni.redirectTo({
url: '/pages/memberInfo/memberCard'
})
return true
})
// ==================== 唤起支付宝 App ====================
function invokeAlipayApp(payUrl) {
return new Promise((resolve, reject) => {
if (!payUrl) {
reject(new Error('支付链接为空'))
return
}
console.log('[Alipay] 准备唤起支付宝:', payUrl)
// 检查是否在 App 环境
if (typeof plus === 'undefined') {
uni.showModal({
title: '提示',
content: '请在 App 内完成支付',
showCancel: false
})
reject(new Error('非 App 环境'))
return
}
// 使用 plus.runtime.openURL 唤起支付宝
plus.runtime.openURL(payUrl, function(err) {
console.error('[Alipay] 唤起支付宝失败:', err)
uni.showModal({
title: '提示',
content: '无法唤起支付宝,请确认已安装支付宝 App',
showCancel: false
})
reject(new Error('唤起支付宝失败: ' + (err?.message || '未知错误')))
})
// 直接 resolve,支付结果由轮询处理
resolve()
})
}
// ==================== 轮询支付状态 ====================
function startPolling(orderId) {
return new Promise((resolve, reject) => {
if (isPolling.value) return
isPolling.value = true
let pollCount = 0
const maxRetry = 60 // 60秒
let isResolved = false
// 监听 App 回到前台
const handleResume = () => {
if (isResolved) return
console.log('[Poll] App 回到前台,立即查询')
doQuery()
}
if (typeof plus !== 'undefined') {
plus.globalEvent.addEventListener('resume', handleResume)
}
function doQuery() {
if (isResolved) return
pollCount++
getPaymentStatus(orderId)
.then(res => {
if (res.code === 200 && res.data) {
const status = res.data.status || res.data.payStatus
console.log(`[Poll] 第 ${pollCount} 次查询,状态:`, status)
if (status === 'SUCCESS') {
isResolved = true
cleanup()
resolve(true)
return
} else if (status === 'FAIL' || status === 'CLOSED') {
isResolved = true
cleanup()
reject(new Error('支付失败'))
return
}
}
// 继续轮询
if (pollCount < maxRetry && !isResolved) {
pollingTimer.value = setTimeout(doQuery, 1000)
} else if (!isResolved) {
isResolved = true
cleanup()
reject(new Error('支付超时,请确认是否已完成支付'))
}
})
.catch(err => {
console.error('[Poll] 查询异常:', err)
if (pollCount < maxRetry && !isResolved) {
pollingTimer.value = setTimeout(doQuery, 1000)
} else if (!isResolved) {
isResolved = true
cleanup()
reject(new Error('支付超时,请确认是否已完成支付'))
}
})
}
function cleanup() {
isPolling.value = false
if (pollingTimer.value) {
clearTimeout(pollingTimer.value)
pollingTimer.value = null
}
if (typeof plus !== 'undefined') {
plus.globalEvent.removeEventListener('resume', handleResume)
}
}
// 延迟 1.5 秒开始轮询
pollingTimer.value = setTimeout(doQuery, 1500)
})
}
// ==================== 核心购买逻辑 ====================
async function handlePurchase() {
if (!selectedCard.value) {
uni.showToast({ title: '请选择会员卡', icon: 'none' })
return
}
if (loading.value) return
loading.value = true
try {
const store = loadMemberStore()
const memberId = store.memberProfile?.id || store.profile?.id
// if (!memberId) {
// uni.showToast({ title: '请先登录', icon: 'none' })
// loading.value = false
// return
// }
// 金额转换:元 -> 分
const transAmt = String(Math.round(selectedCard.value.price * 100))
const cardName = selectedCard.value.cardName
// 1. 创建支付订单
uni.showLoading({ title: '创建订单中...' })
const payRes = await createPayment({
memberId: memberId,
orderType: 'MEMBER_CARD',
goodsDesc: `购买${cardName}`,
transAmt: transAmt,
tradeType: TRADE_TYPE,
remark: `会员卡类型ID:${selectedCard.value.id}`
})
if (payRes.code !== 200) {
uni.hideLoading()
uni.showToast({ title: payRes.message || '创建支付订单失败', icon: 'none' })
loading.value = false
return
}
const payData = payRes.data
const orderId = payData.orderId
// 2. 获取支付链接
const payUrl = payData.payUrl || payData.payInfo || payData.h5PayUrl
if (!payUrl) {
uni.hideLoading()
uni.showToast({ title: '获取支付链接失败', icon: 'none' })
loading.value = false
return
}
// 3. 唤起支付宝 App
uni.hideLoading()
uni.showLoading({ title: '正在唤起支付宝...' })
try {
await invokeAlipayApp(payUrl)
} catch (err) {
uni.hideLoading()
uni.showToast({ title: '唤起支付宝失败,请确认已安装支付宝', icon: 'none' })
loading.value = false
return
}
// 4. 轮询支付状态
uni.showLoading({ title: '等待支付结果...' })
await startPolling(orderId)
// 5. 支付成功,购买会员卡
uni.hideLoading()
const memberRes = await purchaseMemberCard({
memberId: memberId,
memberCardId: selectedCard.value.id,
sourceOrderId: orderId
})
if (memberRes.code === 200) {
uni.showToast({ title: '购买成功 🎉', icon: 'success' })
setTimeout(() => {
uni.redirectTo({
url: '/pages/memberInfo/memberCard'
})
}, 1500)
} else {
uni.showToast({ title: memberRes.message || '会员卡购买失败', icon: 'none' })
}
} catch (e) {
console.error('[purchaseCard] 购买失败:', e)
uni.hideLoading()
const errorMsg = e.message || '购买失败'
uni.showToast({ title: errorMsg, icon: 'none' })
} finally {
loading.value = false
}
}
// ==================== 生命周期 ====================
onMounted(() => {
if (cardTypes.value.length > 0) {
selectCard(cardTypes.value[0])
}
})
onUnmounted(() => {
// 清理轮询
if (pollingTimer.value) {
clearTimeout(pollingTimer.value)
pollingTimer.value = null
}
isPolling.value = false
if (typeof plus !== 'undefined') {
plus.globalEvent.removeEventListener('resume', () => {})
}
})
</script>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@import '@/common/style/memberInfo/member-info-component-reset.css';
@import '@/common/style/memberInfo/member-info-sub-nav.css';
@import '@/common/style/memberInfo/member-info-tap.css';
.purchase-card-page {
min-height: 100vh;
background: #F5F7FA;
}
.purchase-card-page__body {
padding-bottom: 100px;
}
.pc-intro {
display: flex;
flex-direction: column;
align-items: center;
padding: 32px 24px;
background: linear-gradient(135deg, #1A365D 0%, #2C5282 100%);
}
.pc-intro__icon {
width: 64px;
height: 64px;
margin-bottom: 16px;
background: rgba(255, 255, 255, 0.1);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
image {
width: 40px;
height: 40px;
}
}
.pc-intro__title {
font-size: 20px;
font-weight: 600;
color: #FFFFFF;
margin-bottom: 8px;
}
.pc-intro__desc {
font-size: 14px;
color: rgba(255, 255, 255, 0.7);
}
.pc-list {
padding: 16px;
}
.pc-payment {
padding: 16px;
margin: 0 16px;
background: #FFFFFF;
border-radius: 16px;
}
.pc-payment__title {
font-size: 16px;
font-weight: 600;
color: #1A202C;
margin-bottom: 16px;
}
.pc-payment__methods {
display: flex;
gap: 16px;
}
.pc-payment__method {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 16px;
border: 2px solid #1677FF;
border-radius: 12px;
background: #F0F7FF;
position: relative;
&--selected {
border-color: #1677FF;
background: #F0F7FF;
}
}
.pc-payment__icon {
width: 40px;
height: 40px;
margin-bottom: 8px;
}
.pc-payment__name {
font-size: 14px;
color: #2D3748;
}
.pc-payment__check {
position: absolute;
top: 8px;
right: 8px;
width: 20px;
height: 20px;
background: #1677FF;
border-radius: 50%;
&::after {
content: '';
display: block;
width: 6px;
height: 6px;
background: #FFFFFF;
border-radius: 50%;
margin: 4px auto;
}
}
.pc-card {
display: flex;
align-items: flex-start;
background: #FFFFFF;
border-radius: 16px;
padding: 20px;
margin-bottom: 16px;
border: 2px solid transparent;
transition: all 0.2s;
&--selected {
border-color: #2C5282;
background: #F7FAFC;
}
}
.pc-card__check {
width: 24px;
height: 24px;
margin-right: 16px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.pc-card__check-inner {
width: 20px;
height: 20px;
border: 2px solid #CBD5E0;
border-radius: 50%;
transition: all 0.2s;
&--checked {
border-color: #2C5282;
background: #2C5282;
&::after {
content: '';
display: block;
width: 6px;
height: 6px;
background: #FFFFFF;
border-radius: 50%;
margin: 4px auto;
}
}
}
.pc-card__content {
flex: 1;
}
.pc-card__header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.pc-card__name {
font-size: 18px;
font-weight: 600;
color: #1A202C;
}
.pc-card__tag {
padding: 4px 12px;
border-radius: 20px;
font-size: 12px;
&--time {
background: #EBF8FF;
.pc-card__tag-text { color: #2B6CB0; }
}
&--count {
background: #FEF3E2;
.pc-card__tag-text { color: #D69E2E; }
}
&--value {
background: #F0FFF4;
.pc-card__tag-text { color: #38A169; }
}
&--default {
background: #E2E8F0;
.pc-card__tag-text { color: #718096; }
}
}
.pc-card__tag-text {
font-size: 12px;
font-weight: 500;
}
.pc-card__info {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
margin-bottom: 12px;
}
.pc-card__info-row {
display: flex;
align-items: center;
gap: 8px;
}
.pc-card__info-label {
font-size: 13px;
color: #718096;
}
.pc-card__info-value {
font-size: 13px;
font-weight: 600;
color: #2D3748;
}
.pc-card__footer {
display: flex;
align-items: baseline;
gap: 8px;
}
.pc-card__price {
font-size: 24px;
font-weight: 700;
color: #E53E3E;
}
.pc-card__original-price {
font-size: 14px;
color: #A0AEC0;
text-decoration: line-through;
}
.pc-bottom {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 24px;
padding-bottom: calc(16px + env(safe-area-inset-bottom));
background: #FFFFFF;
box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);
z-index: 100;
}
.pc-bottom__total {
display: flex;
align-items: baseline;
gap: 8px;
}
.pc-bottom__total-label {
font-size: 14px;
color: #718096;
}
.pc-bottom__total-price {
font-size: 28px;
font-weight: 700;
color: #E53E3E;
}
.pc-bottom__btn {
background: #1677FF;
border-radius: 12px;
padding: 16px 48px;
transition: all 0.2s;
&--disabled {
background: #A0AEC0;
}
}
.pc-bottom__btn-text {
font-size: 16px;
font-weight: 600;
color: #FFFFFF;
}
</style>
+23 -35
View File
@@ -104,45 +104,37 @@
</view>
</template>
<script>
<script setup>
import { ref } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { getReferralPageData } from '@/common/memberInfo/moduleStore.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
import { backToMemberCenter } from '@/common/constants/routes.js'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
data: { code: '', invited: 0, registered: 0, purchased: 0, records: [], rules: [] }
const data = ref(getReferralPageData(loadMemberStore()))
function goBack() {
backToMemberCenter()
}
function copyCode() {
uni.setClipboardData({
data: data.value.code,
success: () => uni.showToast({ title: '已复制', icon: 'success' })
})
}
function shareInvite() {
uni.showActionSheet({
itemList: ['分享给微信好友', '生成分享海报'],
success: (res) => {
uni.showToast({ title: ['已唤起微信分享', '海报已生成'][res.tapIndex] || '分享成功', icon: 'none' })
}
},
onShow() {
const store = loadMemberStore()
this.data = getReferralPageData(store)
},
methods: {
copyCode() {
uni.setClipboardData({
data: this.data.code,
success: () => uni.showToast({ title: '邀请码已复制', icon: 'success' })
})
},
shareInvite() {
uni.showActionSheet({
itemList: ['分享给微信好友', '生成邀请海报', '复制分享链接'],
success: (res) => {
const msgs = ['已唤起分享', '海报已生成', '链接已复制']
uni.showToast({ title: msgs[res.tapIndex] || '分享成功', icon: 'none' })
}
})
}
}
})
}
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -151,8 +143,4 @@ export default {
@import '@/common/style/memberInfo/member-info-tap.css';
@import '@/common/style/memberInfo/pages/body-test-common.css';
@import '@/common/style/memberInfo/pages/module-pages-common.css';
.mi-mod-referral-hero .bt-hero__actions {
margin-top: 16px;
}
</style>
@@ -69,64 +69,57 @@
</view>
</template>
<script>
<script setup>
import { ref, computed } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import BodyTestTrendChart from '@/components/memberInfo/BodyTestTrendChart.vue'
import { PAGE, navigateToPage } from '@/common/constants/routes.js'
import { PAGE, navigateToPage, backToMemberCenter } from '@/common/constants/routes.js'
import { getTrainingReportData, filterTrainingSessions } from '@/common/memberInfo/moduleStore.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
export default {
components: { MemberInfoSubNav, BodyTestTrendChart },
mixins: [subPageMixin],
data() {
return {
period: 'week',
periods: [
{ key: 'week', label: '本周' },
{ key: 'month', label: '本月' }
],
typeFilter: 'all',
typeFilters: [
{ key: 'all', label: '全部' },
{ key: 'group', label: '团课' },
{ key: 'private', label: '私教' },
{ key: 'free', label: '自由' }
],
report: { summary: {}, trendHours: [], trendCalories: [], sessions: [] },
sessions: [],
chartWidth: 300
}
},
onLoad() {
this.chartWidth = uni.getSystemInfoSync().windowWidth - 64
this.refresh()
},
onShow() { this.refresh() },
methods: {
refresh() {
const store = loadMemberStore()
this.report = getTrainingReportData(store, this.period)
this.sessions = filterTrainingSessions(store, { type: this.typeFilter })
},
switchPeriod(key) {
this.period = key
this.refresh()
},
goSession(item) {
navigateToPage(`${PAGE.TRAIN_SESSION}?id=${item.id}`)
}
},
watch: {
typeFilter() {
this.sessions = filterTrainingSessions(loadMemberStore(), { type: this.typeFilter })
}
}
const period = ref('week')
const periods = ref([
{ key: 'week', label: '本周' },
{ key: 'month', label: '本月' }
])
const typeFilter = ref('all')
const typeFilters = ref([
{ key: 'all', label: '全部' },
{ key: 'group', label: '团课' },
{ key: 'private', label: '私教' },
{ key: 'free', label: '自由' }
])
const report = ref({ summary: {}, trendHours: [], trendCalories: [], sessions: [] })
const chartWidth = ref(300)
const sessions = computed(() => {
return filterTrainingSessions(report.value.sessions, typeFilter.value)
})
function switchPeriod(p) {
period.value = p
refresh()
}
function refresh() {
const store = loadMemberStore()
report.value = getTrainingReportData(store, period.value)
}
function goBack() {
backToMemberCenter()
}
function goSession(item) {
navigateToPage(`${PAGE.TRAIN_SESSION_DETAIL}?id=${item.id}`)
}
// Initialize
chartWidth.value = uni.getSystemInfoSync().windowWidth - 64
refresh()
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
@@ -31,25 +31,28 @@
</view>
</template>
<script>
<script setup>
import { ref, onMounted } from 'vue'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { PAGE, goBackOrTab } from '@/common/constants/routes.js'
import { loadMemberStore } from '@/common/memberInfo/store.js'
import { getTrainingSessionById } from '@/common/memberInfo/moduleStore.js'
export default {
components: { MemberInfoSubNav },
data() { return { session: null } },
onLoad(options) {
this.session = getTrainingSessionById(loadMemberStore(), options?.id)
},
methods: {
onBack() { goBackOrTab(PAGE.TRAIN_REPORT) }
}
const session = ref(null)
onMounted(() => {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const options = currentPage?.options || {}
session.value = getTrainingSessionById(loadMemberStore(), options?.id)
})
function onBack() {
goBackOrTab(PAGE.TRAIN_REPORT)
}
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';
+315 -231
View File
@@ -210,13 +210,13 @@
</view>
</template>
<script>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import { fitnessGoalOptions } from '@/common/memberInfo/mockData.js'
import { loadMemberStore, saveUserProfile } from '@/common/memberInfo/store.js'
import { getUserInfo, updateUserInfo } from '@/api/main.js'
import { previewImage, persistChosenImage } from '@/common/memberInfo/media.js'
import { maskPhone, normalizePhoneForStore } from '@/common/memberInfo/format.js'
import { subPageMixin } from '@/common/memberInfo/mixins.js'
import {
validateName,
validatePhoneForRebind,
@@ -227,246 +227,330 @@ import {
validateUserProfile,
showValidationError
} from '@/common/memberInfo/validate.js'
import { backToMemberCenter } from '@/common/constants/routes.js'
const DEFAULT_AVATAR = 'https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/AvatarEditWrap.png'
export default {
components: { MemberInfoSubNav },
mixins: [subPageMixin],
data() {
return {
name: '',
phone: '',
gender: 'female',
birthday: '',
height: '',
weight: '',
fitnessGoals: [],
avatar: DEFAULT_AVATAR,
avatarKey: 0,
avatarDirty: false,
fitnessGoalOptions
}
},
computed: {
avatarSrc() {
return this.avatar || DEFAULT_AVATAR
},
displayPhone() {
return maskPhone(this.phone)
},
birthdayValue() {
const match = String(this.birthday).match(/(\d{4})年(\d{2})月(\d{2})日/)
if (match) {
return `${match[1]}-${match[2]}-${match[3]}`
}
return '1995-06-15'
}
},
onShow() {
// 从相册/相机返回会再次触发 onShow,不能覆盖刚选未保存的头像
this.loadProfile({ preserveLocalAvatar: true })
},
methods: {
loadProfile(options = {}) {
const store = loadMemberStore()
const profile = store.profile
this.name = profile.name
this.phone = profile.phone
this.gender = profile.gender
this.birthday = profile.birthday
this.height = profile.height
this.weight = profile.weight
this.fitnessGoals = [...(profile.fitnessGoals || [])]
const name = ref('')
const phone = ref('')
const gender = ref('female')
const birthday = ref('')
const height = ref('')
const weight = ref('')
const fitnessGoals = ref([])
const avatar = ref(DEFAULT_AVATAR)
const avatarKey = ref(0)
const avatarDirty = ref(false)
const fitnessGoalOptions = ref(['减脂1', '增肌', '塑形', '增重', '康复', '体能'])
const loading = ref(false)
const storedAvatar = profile.avatar || DEFAULT_AVATAR
const hasUnsavedLocalAvatar =
options.preserveLocalAvatar &&
this.avatarDirty &&
this.avatar &&
this.avatar !== storedAvatar
const avatarSrc = computed(() => {
return avatar.value || DEFAULT_AVATAR
})
if (!hasUnsavedLocalAvatar) {
this.setAvatar(storedAvatar)
this.avatarDirty = false
}
},
setAvatar(path) {
const next = path || DEFAULT_AVATAR
if (this.avatar !== next) {
this.avatar = next
this.avatarKey += 1
}
},
getProfilePayload() {
return {
name: this.name,
phone: normalizePhoneForStore(this.phone),
gender: this.gender,
birthday: this.birthday,
height: this.height,
weight: this.weight,
fitnessGoals: [...this.fitnessGoals],
avatar: this.avatar
}
},
handleSave() {
const result = validateUserProfile(
this.getProfilePayload(),
this.fitnessGoalOptions
)
if (!result.ok) {
showValidationError(result.message)
return
}
const displayPhone = computed(() => {
return maskPhone(phone.value)
})
const store = loadMemberStore()
saveUserProfile(store, result.value)
this.applyValidatedProfile(result.value)
this.avatarDirty = false
uni.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => this.goBack(), 600)
},
applyValidatedProfile(profile) {
this.name = profile.name
this.phone = profile.phone
this.gender = profile.gender
this.birthday = profile.birthday
this.height = profile.height
this.weight = profile.weight
this.fitnessGoals = [...profile.fitnessGoals]
},
changeAvatar() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempPath =
res.tempFilePaths?.[0] || res.tempFiles?.[0]?.tempFilePath
if (!tempPath) return
const birthdayValue = computed(() => {
const match = String(birthday.value).match(/(\d{4})年(\d{2})月(\d{2})日/)
if (match) {
return `${match[1]}-${match[2]}-${match[3]}`
}
return '1995-06-15'
})
// 真机先用 tempFilePath 立即展示,避免 saveFile 异步期间被 onShow 覆盖
this.setAvatar(tempPath)
this.avatarDirty = true
uni.showToast({ title: '头像已选择', icon: 'success' })
function goBack() {
backToMemberCenter()
}
persistChosenImage(tempPath).then((savedPath) => {
if (savedPath && savedPath !== this.avatar) {
this.setAvatar(savedPath)
}
})
}
})
},
previewAvatar() {
previewImage(this.avatarSrc, DEFAULT_AVATAR)
},
editName() {
uni.showModal({
title: '修改姓名',
editable: true,
placeholderText: '请输入姓名(2-8字)',
content: this.name,
success: (res) => {
if (!res.confirm) return
const result = validateName(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
this.name = result.value
}
})
},
rebindPhone() {
uni.showModal({
title: '换绑手机号',
editable: true,
placeholderText: '请输入11位手机号',
content: normalizePhoneForStore(this.phone) || this.phone,
success: (res) => {
if (!res.confirm) return
const result = validatePhoneForRebind(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
this.phone = result.value
uni.showToast({ title: '手机号已更新', icon: 'success' })
}
})
},
selectGender(gender) {
this.gender = gender
},
onBirthdayChange(e) {
const value = e.detail.value
const [y, m, d] = value.split('-')
const formatted = `${y}${m}${d}`
const result = validateBirthday(formatted)
if (!result.ok) {
showValidationError(result.message)
return
}
this.birthday = result.value
},
editHeight() {
uni.showModal({
title: '修改身高',
editable: true,
placeholderText: '50-250,单位 cm',
content: String(this.height),
success: (res) => {
if (!res.confirm) return
const result = validateHeight(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
this.height = result.value
}
})
},
editWeight() {
uni.showModal({
title: '修改体重',
editable: true,
placeholderText: '20-300,单位 kg',
content: String(this.weight),
success: (res) => {
if (!res.confirm) return
const result = validateWeight(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
this.weight = result.value
}
})
},
toggleGoal(goal) {
const index = this.fitnessGoals.indexOf(goal)
if (index >= 0) {
this.fitnessGoals.splice(index, 1)
return
}
const preview = [...this.fitnessGoals, goal]
const result = validateFitnessGoals(preview, this.fitnessGoalOptions)
if (!result.ok) {
showValidationError(result.message)
return
}
this.fitnessGoals.push(goal)
},
isGoalSelected(goal) {
return this.fitnessGoals.includes(goal)
function mapApiToProfile(apiData) {
const genderMap = {
'MALE': 'male',
'FEMALE': 'female',
'UNKNOWN': 'female'
}
let birthdayVal = ''
if (apiData.birthday) {
const parts = apiData.birthday.split('-')
if (parts.length === 3) {
birthdayVal = `${parts[0]}${parts[1]}${parts[2]}`
}
}
return {
name: apiData.nickname || '',
phone: apiData.phone || '',
gender: genderMap[apiData.gender] || 'female',
birthday: birthdayVal,
avatar: apiData.avatar || DEFAULT_AVATAR
}
}
function mapProfileToApi(profile) {
const genderMap = {
'male': 'MALE',
'female': 'FEMALE'
}
let birthdayVal = ''
if (profile.birthday) {
const match = String(profile.birthday).match(/(\d{4})年(\d{2})月(\d{2})日/)
if (match) {
birthdayVal = `${match[1]}-${match[2]}-${match[3]}`
}
}
return {
nickname: profile.name,
gender: genderMap[profile.gender] || 'UNKNOWN',
birthday: birthdayVal,
avatar: profile.avatar
}
}
async function fetchUserInfo() {
// 如果正在加载中,不重复请求
if (loading.value) {
console.log('[userInfo] 正在加载中,跳过重复请求')
return
}
loading.value = true
console.log('[userInfo] fetchUserInfo 开始执行')
console.log('[userInfo] 步骤1: 调用 getUserInfo API...')
try {
const res = await getUserInfo({ cache: false })
console.log('[userInfo] 步骤2: API返回,res =', res)
console.log('[userInfo] 步骤3: res类型 =', typeof res, 'res.data =', res?.data)
// 兼容两种数据格式:1.直接返回数据对象 2.返回 {code, data, message} 格式
const apiData = res.data || res
console.log('[userInfo] 步骤4: apiData =', apiData)
if (apiData && (apiData.nickname !== undefined || apiData.phone !== undefined)) {
console.log('[userInfo] 步骤5: 收到有效数据,更新页面')
const profile = mapApiToProfile(apiData)
console.log('[userInfo] 步骤6: 映射后数据 =', profile)
name.value = profile.name
phone.value = profile.phone
gender.value = profile.gender
birthday.value = profile.birthday
setAvatar(profile.avatar)
console.log('[userInfo] 步骤7: 页面数据已更新,name =', name.value)
} else {
console.log('[userInfo] 步骤5: 数据无效,跳过更新')
}
} catch (err) {
console.error('[userInfo] 获取用户信息失败:', err)
uni.showToast({ title: '获取信息失败: ' + (err.message || '网络错误'), icon: 'none' })
} finally {
loading.value = false
console.log('[userInfo] fetchUserInfo 执行完成')
}
}
function loadProfile(options = {}) {
// API模式下从data直接获取,不从store获取
}
function setAvatar(path) {
const next = path || DEFAULT_AVATAR
if (avatar.value !== next) {
avatar.value = next
avatarKey.value += 1
}
}
function getProfilePayload() {
return {
name: name.value,
phone: normalizePhoneForStore(phone.value),
gender: gender.value,
birthday: birthday.value,
height: height.value,
weight: weight.value,
fitnessGoals: [...fitnessGoals.value],
avatar: avatar.value
}
}
function handleSave() {
const result = validateUserProfile(
getProfilePayload(),
fitnessGoalOptions.value
)
if (!result.ok) {
showValidationError(result.message)
return
}
applyValidatedProfile(result.value)
avatarDirty.value = false
saveUserInfo(result.value)
}
async function saveUserInfo(profile) {
loading.value = true
try {
const apiData = mapProfileToApi(profile)
console.log('[userInfo] PUT /api/member/info 请求:', apiData)
const res = await updateUserInfo(apiData)
console.log('[userInfo] PUT /api/member/info 返回:', res)
uni.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => goBack(), 600)
} catch (err) {
console.error('保存用户信息失败', err)
uni.showToast({ title: '保存失败', icon: 'none' })
} finally {
loading.value = false
}
}
function applyValidatedProfile(profile) {
name.value = profile.name
phone.value = profile.phone
gender.value = profile.gender
birthday.value = profile.birthday
height.value = profile.height
weight.value = profile.weight
fitnessGoals.value = [...profile.fitnessGoals]
}
function changeAvatar() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempPath =
res.tempFilePaths?.[0] || res.tempFiles?.[0]?.tempFilePath
if (!tempPath) return
avatarDirty.value = true
setAvatar(tempPath)
persistChosenImage(tempPath)
}
})
}
function previewAvatar() {
previewImage(avatarSrc.value)
}
function editName() {
uni.showModal({
title: '修改姓名',
editable: true,
placeholderText: '请输入姓名',
content: String(name.value),
success: (res) => {
if (!res.confirm) return
const result = validateName(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
name.value = result.value
}
})
}
function rebindPhone() {
uni.showModal({
title: '换绑手机号',
editable: true,
placeholderText: '请输入新手机号',
content: '',
success: (res) => {
if (!res.confirm) return
const result = validatePhoneForRebind(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
phone.value = normalizePhoneForStore(result.value)
}
})
}
function selectGender(g) {
gender.value = g
}
function onBirthdayChange(e) {
const val = e.detail.value
if (!val) return
const parts = val.split('-')
if (parts.length === 3) {
birthday.value = `${parts[0]}${parts[1]}${parts[2]}`
}
}
function editHeight() {
uni.showModal({
title: '修改身高',
editable: true,
placeholderText: '100-250,单位 cm',
content: String(height.value),
success: (res) => {
if (!res.confirm) return
const result = validateHeight(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
height.value = result.value
}
})
}
function editWeight() {
uni.showModal({
title: '修改体重',
editable: true,
placeholderText: '20-300,单位 kg',
content: String(weight.value),
success: (res) => {
if (!res.confirm) return
const result = validateWeight(res.content)
if (!result.ok) {
showValidationError(result.message)
return
}
weight.value = result.value
}
})
}
function toggleGoal(goal) {
const index = fitnessGoals.value.indexOf(goal)
if (index >= 0) {
fitnessGoals.value.splice(index, 1)
return
}
const preview = [...fitnessGoals.value, goal]
const result = validateFitnessGoals(preview, fitnessGoalOptions.value)
if (!result.ok) {
showValidationError(result.message)
return
}
fitnessGoals.value.push(goal)
}
function isGoalSelected(goal) {
return fitnessGoals.value.includes(goal)
}
onMounted(() => {
console.log('[userInfo] onMounted 被调用,开始获取用户信息')
fetchUserInfo()
})
onShow(() => {
console.log('[userInfo] onShow 被调用')
// 每次进入页面都尝试获取最新数据
fetchUserInfo()
})
</script>
<style>
<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';