PointsCollector.vue
15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
<template>
<view class="points-collector-container">
<!-- 头部slot -->
<view v-if="$slots.header" class="points-collector-header">
<slot name="header"></slot>
</view>
<!-- 积分收集器主体 -->
<view class="points-collector" :style="{ height: height }">
<!-- 中心圆形显示总积分 -->
<view class="center-circle">
<view class="total-points" @tap="handleGoToRewards">
<text v-if="!isOwner" class="family-points-label">家庭总积分</text>
<text class="points-number" :style="{ fontSize: dynamicFontSize }">{{ animatedTotalPoints }}分</text>
<text v-if="isOwner" class="points-label">去兑换</text>
</view>
</view>
<!-- 周围漂浮的小圆圈 -->
<view
v-for="(item) in floatingItems"
:key="item.id"
class="floating-item"
:style="getItemStyle(item)"
@tap="collectItem(item)"
>
<view class="item-content">
<text class="item-value">{{ item.sourceLabel }}</text>
<text class="item-type">{{ item.points }}分</text>
</view>
</view>
<!-- 一键收取按钮 -->
<!-- <view
v-if="floatingItems.length > 0"
class="collect-all-btn"
@tap="collectAll"
>
<text>一键收取</text>
</view> -->
</view>
<!-- 底部slot -->
<view v-if="$slots.footer" class="points-collector-footer">
<slot name="footer"></slot>
</view>
</view>
</template>
<script setup>
import { ref, onMounted, defineProps, defineExpose, defineEmits, watch, computed } from 'vue'
import Taro, { useDidShow } from '@tarojs/taro'
import { collectPointAPI } from '@/api/points'
const emit = defineEmits(['collection-complete'])
const props = defineProps({
height: {
type: String,
default: '30vh'
},
pendingPoints: {
type: Array,
default: () => []
},
totalPoints: {
type: Number,
default: 0
},
familyId: {
type: [String, Number],
required: true
},
isOwner: {
type: Boolean,
default: false
},
})
// 响应式数据
const animatedTotalPoints = ref(props.totalPoints) // 动画中的总积分
const floatingItems = ref([]) // 漂浮的积分项
const isCollecting = ref(false) // 是否正在收集,防止重复触发
/**
* 根据数值长度动态计算字体大小
*/
const dynamicFontSize = computed(() => {
const pointsStr = animatedTotalPoints.value + '分'
const length = pointsStr?.length
// 基础字体大小36rpx,超过6位数开始缩小
if (length <= 6) {
return '36rpx'
} else if (length <= 8) {
return '32rpx'
} else if (length <= 10) {
return '28rpx'
} else {
return '24rpx'
}
})
// source_type 中英文映射
const sourceTypeMap = {
'WALKING': '步数积分',
'CHECK_IN': '活动打卡',
'CHECK_IN_COUNT': '完成活动',
'FAMILY_SIZE': '家庭成员',
'COMPANION_PHOTO': '陪伴拍照',
'WHEELCHAIR_COMPANION': '陪伴轮椅'
}
/**
* 根据pending_points数据生成漂浮积分项并分配随机位置
*/
const generatePointsData = () => {
if (!props.pendingPoints || props.pendingPoints?.length === 0) {
return [];
}
const pointsItems = props.pendingPoints.map(item => ({
id: item.id,
points: parseInt(item.points),
sourceType: item.source_type,
sourceLabel: sourceTypeMap[item.source_type] || item.source_type,
title: item.title,
note: item.note,
collecting: false
}));
const maxValue = Math.max(...pointsItems.map(i => i.points), 1);
const baseSize = 80;
const { windowWidth, windowHeight } = Taro.getWindowInfo();
const positionedItems = [];
// 为每个项目分配一个不重叠的随机位置
return pointsItems.map(item => {
let x, y, hasCollision;
const maxAttempts = 100; // 限制尝试次数以避免无限循环
let attempts = 0;
const centerNoFlyZone = 25; // 中心圆形25%的禁飞区半径
// 计算项目大小和半径
const sizeRatio = item.points / maxValue;
const size = baseSize + (sizeRatio * 40); // rpx
// 优化半径计算,确保在不同屏幕尺寸下都能正确计算边界
// 将rpx转换为百分比,考虑屏幕宽度和高度的比例
const sizeInVw = (size / 750) * 100; // 转换为vw单位的百分比
const aspectRatio = windowWidth / windowHeight;
const radiusPercent = (sizeInVw / 2) / aspectRatio; // 转换为高度百分比的半径
// 定义更严格的安全区域,确保积分不会跑出屏幕
const safeMargin = Math.max(radiusPercent * 1.2, 8); // 至少8%的安全边距
const minX = safeMargin;
const maxX = 100 - safeMargin;
const minY = safeMargin + 5; // 顶部额外5%边距
const maxY = Math.min(60, 100 - safeMargin); // 限制在视图的顶部60%或安全区域内
// 确保安全区域有效
if (minX >= maxX || minY >= maxY) {
console.warn('安全区域过小,使用默认位置');
x = 20 + Math.random() * 60; // 20%-80%范围
y = 15 + Math.random() * 40; // 15%-55%范围
positionedItems.push({ ...item, x, y, radiusPercent });
return { ...item, x, y };
}
do {
attempts++;
if (attempts > maxAttempts) {
// console.warn('无法为项目找到不重叠的位置,使用安全位置:', item);
// 使用安全的默认位置
x = minX + Math.random() * (maxX - minX);
y = minY + Math.random() * (maxY - minY);
break;
}
// 在计算出的边界内生成位置
x = Math.random() * (maxX - minX) + minX;
y = Math.random() * (maxY - minY) + minY;
// 二次检查边界,确保不会超出屏幕
x = Math.max(safeMargin, Math.min(100 - safeMargin, x));
y = Math.max(safeMargin, Math.min(maxY, y));
// 检查与中心禁飞区的距离
const dxCenter = x - 50;
const dyCenter = y - 75; // 中心点在75%
const distanceFromCenter = Math.sqrt(dxCenter * dxCenter + dyCenter * dyCenter);
if (distanceFromCenter < centerNoFlyZone) {
hasCollision = true;
continue;
}
// 检查与其他项目的碰撞
hasCollision = false;
for (const pItem of positionedItems) {
const dx = x - pItem.x;
const dy = y - pItem.y;
const distance = Math.sqrt(dx * dx + dy * dy);
const combinedRadius = radiusPercent + pItem.radiusPercent + 2; // 增加2%的缓冲区
if (distance < combinedRadius) {
hasCollision = true;
break;
}
}
} while (hasCollision);
positionedItems.push({ ...item, x, y, radiusPercent });
return { ...item, x, y };
});
}
/**
* 获取项目样式(位置、大小和动画)
*/
const getItemStyle = (item) => {
const baseSize = 90; // 增大基础尺寸从80到90
const maxValue = Math.max(...(floatingItems.value.map(i => i.points)?.length > 0 ? floatingItems.value.map(i => i.points) : [1]));
const sizeRatio = item.points / maxValue;
const size = baseSize + (sizeRatio * 50); // 增大最大额外尺寸从40到50
// 计算动态字体大小
const baseFontSize = 20; // 基础字体大小 rpx
const maxFontSize = 24; // 最大字体大小 rpx
const minFontSize = 18; // 最小字体大小 rpx,提高最小值确保可读性
// 根据圆圈大小和文字长度计算合适的字体大小
const labelLength = item.sourceLabel?.length || 0;
const pointsLength = (item.points + '分')?.length;
// 优化字体计算:根据圆圈大小和文字长度动态调整
let dynamicFontSize = Math.max(
minFontSize,
Math.min(
maxFontSize,
baseFontSize * (size / 100) * (8 / Math.max(8, labelLength)) // 根据文字长度调整
)
);
// 确保长文字能在一行显示
if (labelLength > 4) {
dynamicFontSize = Math.max(minFontSize, dynamicFontSize * (4 / labelLength));
}
// 确保字体大小为整数
dynamicFontSize = Math.round(dynamicFontSize);
const style = {
position: 'absolute',
left: `${item.x}%`,
top: `${item.y}%`,
width: `${size}rpx`,
height: `${size}rpx`,
transform: 'translate(-50%, -50%) scale(1)',
transition: 'all 0.8s cubic-bezier(0.5, -0.5, 0.5, 1.5)',
zIndex: 15,
'--dynamic-font-size-label': `${Math.max(16, dynamicFontSize - 1)}rpx`,
'--dynamic-font-size-points': `${dynamicFontSize}rpx`,
};
if (item.collecting) {
style.left = '50%';
style.top = '75%';
style.transform = 'translate(-50%, -50%) scale(0)';
style.opacity = 0;
style.zIndex = 20; // 飞向中心时置于顶层
}
return style;
}
/**
* 收集单个项目
*/
const collectItem = async (item) => {
if (item.collecting) return;
item.collecting = true;
try {
// 调用收集积分接口
const { code, data } = await collectPointAPI({
family_id: props.familyId,
point_id: item.id
});
if (code) {
setTimeout(() => {
// 使用接口返回的最新积分总数
const newTotal = data.new_total_points;
animateNumber(animatedTotalPoints.value, newTotal);
floatingItems.value = floatingItems.value.filter(i => i.id !== item.id);
if (floatingItems.value?.length === 0) {
emit('collection-complete', newTotal);
}
}, 800); // 动画时长
} else {
// 接口调用失败,恢复状态
item.collecting = false;
Taro.showToast({
title: '收取失败,请重试',
icon: 'none'
});
}
} catch (error) {
// 异常处理,恢复状态
item.collecting = false;
console.error('收集积分失败:', error);
Taro.showToast({
title: '收取失败,请重试',
icon: 'none'
});
}
}
/**
* 一键收取所有积分
*/
const collectAll = async () => {
if (isCollecting.value) return;
isCollecting.value = true;
try {
// 调用一键收取接口(point_id为空)
const { code, data } = await collectPointAPI({
family_id: props.familyId,
point_id: '' // 空值表示一键收取
});
if (code) {
const itemsToCollect = [...floatingItems.value];
itemsToCollect.forEach((item, index) => {
setTimeout(() => {
item.collecting = true;
}, index * 80); // 依次触发动画
});
const totalAnimationTime = itemsToCollect?.length * 80 + 800;
setTimeout(() => {
// 使用接口返回的最新积分总数
const newTotal = data.new_total_points;
animateNumber(animatedTotalPoints.value, newTotal);
floatingItems.value = [];
isCollecting.value = false;
emit('collection-complete', newTotal);
}, totalAnimationTime);
} else {
// 接口调用失败
isCollecting.value = false;
Taro.showToast({
title: '一键收取失败,请重试',
icon: 'none'
});
}
} catch (error) {
// 异常处理
isCollecting.value = false;
console.error('一键收取积分失败:', error);
Taro.showToast({
title: '一键收取失败,请重试',
icon: 'none'
});
}
}
/**
* 数字滚动动画
*/
const animateNumber = (start, end) => {
const duration = 800;
const startTime = Date.now();
const difference = end - start;
const animate = () => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeOut = 1 - Math.pow(1 - progress, 3);
animatedTotalPoints.value = Math.floor(start + difference * easeOut);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
animate();
}
// 暴露方法给父组件
defineExpose({
collectAll
})
/**
* 初始化数据
*/
const initData = async () => {
floatingItems.value = generatePointsData();
animatedTotalPoints.value = props.totalPoints;
}
// 监听props变化
watch(() => [props.pendingPoints, props.totalPoints], () => {
initData();
}, { deep: true, immediate: true })
// 组件挂载时初始化数据
onMounted(() => {
initData();
})
// 每次进入组件时重新获取数据
useDidShow(() => {
initData();
})
/**
* 处理去兑换点击事件
*/
const handleGoToRewards = () => {
if (!props.isOwner) {
return
}
Taro.navigateTo({
// url: '/pages/RewardCategories/index',
// TAG: 暂时写死以后可能会改变
url: '/pages/Rewards/index?id=health&category=health',
})
}
</script>
<style lang="less">
.points-collector-container {
background: var(--secondary-color-bg);
border-radius: 24rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
margin: 32rpx;
overflow: hidden;
}
.points-collector-header {
padding: 40rpx;
padding-bottom: 20rpx;
}
.points-collector-footer {
padding: 40rpx;
padding-top: 20rpx;
}
.points-collector {
position: relative;
width: 100%;
height: 100vh;
// background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
// TODO: 等待正式背景图
// background-image: url('https://cdn.ipadbiz.cn/lls_prog/images/bg-test-2.png');
background-image: url('https://cdn.ipadbiz.cn/lls_prog/images/dashboard_bg.png');
background-size: cover;
background-position: center bottom;
overflow: hidden;
}
.center-circle {
position: absolute;
left: 50%;
top: 75%;
transform: translate(-50%, -50%);
width: 200rpx;
height: 200rpx;
background: linear-gradient(135deg, var(--primary-color), var(--primary-color));
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 8rpx 32rpx rgba(53, 144, 255, 0.3);
z-index: 10;
}
.total-points {
text-align: center;
color: white;
}
.points-number {
display: block;
font-size: 48rpx;
font-weight: bold;
line-height: 1;
}
.points-label {
display: block;
font-size: 24rpx;
margin-top: 10rpx;
opacity: 0.9;
}
.family-points-label {
display: block;
font-size: 24rpx;
margin-bottom: 10rpx;
opacity: 0.9;
}
.floating-item {
position: absolute;
background: var(--primary-color);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
cursor: pointer;
animation: float 3s ease-in-out infinite;
}
.item-content {
text-align: center;
color: #FFF;
}
.item-value {
display: block;
font-size: var(--dynamic-font-size-label, 20rpx);
line-height: 1;
text-align: center;
max-width: 95%;
white-space: nowrap;
overflow: visible;
margin: 0 auto;
transform: scale(1);
padding: 0 2rpx;
}
.item-type {
display: block;
font-size: var(--dynamic-font-size-points, 23rpx);
margin-top: 2rpx;
line-height: 1.2;
text-align: center;
font-weight: 500;
}
.stack-count {
position: absolute;
top: -8rpx;
right: -8rpx;
width: 32rpx;
height: 32rpx;
background: #ff6b35;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 20rpx;
font-weight: bold;
}
.collect-all-btn {
position: absolute;
bottom: 100rpx;
left: 50%;
transform: translateX(-50%);
background: linear-gradient(135deg, #ff6b35, #f7931e);
color: white;
padding: 24rpx 48rpx;
border-radius: 48rpx;
font-size: 32rpx;
font-weight: bold;
box-shadow: 0 8rpx 24rpx rgba(255, 107, 53, 0.3);
z-index: 20;
}
@keyframes float {
0%, 100% {
transform: translate(-50%, -50%) translateY(0px) rotate(0deg);
}
25% {
transform: translate(-50%, -50%) translateY(-10px) rotate(1deg);
}
50% {
transform: translate(-50%, -50%) translateY(-5px) rotate(-1deg);
}
75% {
transform: translate(-50%, -50%) translateY(-15px) rotate(0.5deg);
}
}
// 响应式适配
@media screen and (max-width: 750px) {
.center-circle {
width: 160rpx;
height: 160rpx;
}
.points-number {
font-size: 36rpx;
}
.points-label {
font-size: 20rpx;
}
}
</style>