-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.tsx
More file actions
7403 lines (6759 loc) · 279 KB
/
index.tsx
File metadata and controls
7403 lines (6759 loc) · 279 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useRef, useMemo, useCallback, lazy, Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { Heart, Zap, Plus, Trash2, CheckCircle, AlertCircle, Calendar, Thermometer, ChevronLeft, ChevronDown, LogOut, Clock, User, Home, Sparkles, BarChart3, Search, Settings, X, QrCode, Camera, Image as ImageIcon, Users, TrendingUp, TrendingDown } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { BarcodeScanner } from '@capacitor-mlkit/barcode-scanning';
import LZString from 'lz-string';
import jsQR from 'jsqr';
import { GoogleGenAI } from "@google/genai";
import { motion, AnimatePresence } from 'framer-motion';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, Area, AreaChart } from 'recharts';
import {
pageVariants,
listContainerVariants,
listItemVariants,
buttonTapAnimation,
fabPulseVariants,
modalVariants,
counterAnimation,
circularProgressVariants,
tagVariants,
forgiveAnimationVariants,
emptyStateVariants,
searchOverlayVariants,
heartbeatVariants,
springConfigs,
shouldReduceMotion,
} from './animations';
import { CardSkeleton, StatsSkeleton } from './components/SkeletonLoader';
// --- Types ---
type Role = 'bf' | 'gf' | null;
type GrudgeStatus = 'active' | 'forgiven';
// 情绪类型定义
type MoodType = '愤怒' | '失望' | '委屈' | '无奈' | '嫌弃' | '无语';
interface MoodOption {
type: MoodType;
emoji: string;
label: string;
color: string; // Tailwind color class
}
interface Grudge {
id: string;
title: string;
description: string;
severity: number; // 1-100, 现在表示情绪强度
moodType: MoodType; // 情绪类型
date: string;
tags: string[];
penalty: string;
status: GrudgeStatus;
forgivenAt?: string; // 原谅时间
isPrivate?: boolean; // 是否私密(不同步给对方)
authorDeviceId?: string; // 作者设备ID(用于区分谁创建的)
photos?: string[]; // 图片ID数组(存储在IndexedDB中)
}
interface PartnerInfo {
id: string; // 对方设备唯一ID
name: string; // 对方昵称
role: Role; // 对方角色
callName: string; // 我叫Ta什么
callsMe: string; // Ta叫我什么
}
interface RelationshipInfo {
anniversary?: string; // 纪念日
pairDate: string; // 配对日期
partnerBirthday?: string; // 对方生日
}
interface SpaceConfig {
grudgeSpaceName: string; // 负面记录空间名称
memorySpaceName: string; // 正面回忆空间名称
}
interface UserProfile {
role: Role;
name: string;
onboarded: boolean;
// 配对信息
paired: boolean;
pairId: string | null; // 配对ID(两台设备共享)
deviceId: string; // 本设备唯一ID
partner?: PartnerInfo;
relationship?: RelationshipInfo;
// 自定义称呼
customCallName?: string; // 自定义的对方称呼(默认"男朋友"/"女朋友")
customSelfName?: string; // 自定义的自己称呼(如"小公主"、"大宝贝")
// 空间配置
spaceConfig?: SpaceConfig;
}
// --- Memory Types (正向记录) ---
interface Memory {
id: string;
title: string;
description: string;
sweetness: number; // 1-100, 甜蜜度
date: string;
tags: string[];
feeling: string; // 当时的心情描述
isPrivate?: boolean; // 是否私密(不同步给对方)
authorDeviceId?: string; // 作者设备ID(用于区分谁创建的)
photos?: string[]; // 图片ID数组(存储在IndexedDB中)
}
// --- Statistics Types (统计数据) ---
interface Statistics {
totalGrudges: number;
totalMemories: number;
forgivenCount: number;
activeGrudgeCount: number;
avgAngerLevel: number;
avgSweetnessLevel: number;
harmonyScore: number; // 和谐度评分 0-100
mostCommonTags: { tag: string; count: number }[];
forgivenessRate: number; // 原谅率 0-100
}
// --- Photo Interface (预留接口) ---
interface Photo {
id: string;
data: string; // base64 编码
thumbnail: string; // 缩略图
timestamp: string;
size: number;
}
// --- Achievement Interface (预留接口) ---
interface Achievement {
id: string;
name: string;
description: string;
icon: string;
unlocked: boolean;
unlockedAt: string | null;
progress: number;
target: number;
category: 'grudge' | 'memory' | 'harmony';
}
// --- Preset Constants (预设常量库) ---
// 女友可能叫男友的预设
const GIRLFRIEND_CALL_BOYFRIEND_PRESETS = {
romantic: ['老公', '宝宝', '亲爱的', 'Darling'],
cute: ['猪猪', '笨蛋', '憨憨', '大宝贝'],
cool: ['臭男人', '小王', '你这个人']
};
// 男友可能叫女友的预设
const BOYFRIEND_CALL_GIRLFRIEND_PRESETS = {
romantic: ['老婆', '宝贝', '小可爱', '心肝'],
cute: ['猪猪', '傻瓜', '小笨蛋', '小公主'],
sweet: ['甜心', '小仙女', '小祖宗', '女王大人']
};
// 负面空间名称预设(中性化,男女通用)
const GRUDGE_SPACE_PRESETS = {
record: ['黑名单', '吐槽专区', '账本', '备忘录'],
archive: ['事件档案', '争议记录', '矛盾本', '反思日志'],
fun: ['小本本', '翻旧账专区', '历史遗留问题', '待解决事项'],
emotion: ['情绪记录', '不爽时刻', '需要改进的地方']
};
// 正面空间名称预设(通用)
const MEMORY_SPACE_PRESETS = [
'甜蜜回忆', '浪漫瞬间', '幸福时光', '爱的记录',
'温馨时刻', '美好瞬间', '心动合集'
];
// 默认空间名称
const DEFAULT_GRUDGE_SPACE_NAME = {
gf: '记仇本本',
bf: '生存记录'
};
const DEFAULT_MEMORY_SPACE_NAME = '甜蜜回忆';
// --- App Settings ---
// 已迁移至 theme.config.ts,使用ThemeConfig类型
// --- Pairing Types (配对相关类型) ---
interface PairInvite {
type: 'pair_invite';
version: string;
timestamp: number;
inviter: {
id: string;
role: Role;
name: string;
callName: string; // 期望对方叫自己什么
};
}
interface PairConfirm {
type: 'pair_confirm';
version: string;
timestamp: number;
responder: {
id: string;
role: Role;
name: string;
callName: string; // 期望对方叫自己什么
};
relationship: {
partnerCallsMe: string; // 对方叫我什么
myCallName: string; // 我叫对方什么
anniversary?: string;
};
linkTo: string; // 关联到邀请者ID
}
interface SyncData {
type: 'data_sync';
version: string;
from: string; // 发送者设备ID
timestamp: number;
syncId: string;
data: {
grudges: Grudge[];
memories: Memory[];
};
stats: {
totalGrudges: number;
totalMemories: number;
};
}
type QRCodeData = PairInvite | PairConfirm | SyncData;
// --- Utility Functions (预留接口) ---
/**
* IndexedDB 存储服务
*/
class IndexedDBService {
private static DB_NAME = 'LoveLedgerDB';
private static DB_VERSION = 1;
private static STORE_PHOTOS = 'photos';
private static STORE_DATA = 'appData';
private static db: IDBDatabase | null = null;
// 初始化数据库
static async init(): Promise<IDBDatabase> {
if (this.db) {
return this.db;
}
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = () => {
reject(new Error('无法打开IndexedDB'));
};
request.onsuccess = () => {
this.db = request.result;
resolve(request.result);
};
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// 创建照片存储
if (!db.objectStoreNames.contains(this.STORE_PHOTOS)) {
const photoStore = db.createObjectStore(this.STORE_PHOTOS, { keyPath: 'id' });
photoStore.createIndex('timestamp', 'timestamp', { unique: false });
}
// 创建应用数据存储
if (!db.objectStoreNames.contains(this.STORE_DATA)) {
db.createObjectStore(this.STORE_DATA);
}
};
});
}
// 保存照片
static async savePhoto(photo: Photo): Promise<void> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_PHOTOS], 'readwrite');
const store = transaction.objectStore(this.STORE_PHOTOS);
const request = store.put(photo);
request.onsuccess = () => resolve();
request.onerror = () => reject(new Error('保存照片失败'));
});
}
// 获取照片
static async getPhoto(id: string): Promise<Photo | null> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_PHOTOS], 'readonly');
const store = transaction.objectStore(this.STORE_PHOTOS);
const request = store.get(id);
request.onsuccess = () => resolve(request.result || null);
request.onerror = () => reject(new Error('获取照片失败'));
});
}
// 删除照片
static async deletePhoto(id: string): Promise<void> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_PHOTOS], 'readwrite');
const store = transaction.objectStore(this.STORE_PHOTOS);
const request = store.delete(id);
request.onsuccess = () => resolve();
request.onerror = () => reject(new Error('删除照片失败'));
});
}
// 获取所有照片(用于计算存储大小)
static async getAllPhotos(): Promise<Photo[]> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_PHOTOS], 'readonly');
const store = transaction.objectStore(this.STORE_PHOTOS);
const request = store.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(new Error('获取照片列表失败'));
});
}
// 计算存储大小
static async getStorageSize(): Promise<number> {
const photos = await this.getAllPhotos();
return photos.reduce((total, photo) => total + photo.size, 0);
}
// 保存应用数据(带防抖)
private static saveTimeout: NodeJS.Timeout | null = null;
static saveDebouncedData(key: string, data: any, delay: number = 500): Promise<void> {
return new Promise((resolve) => {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(async () => {
await this.saveData(key, data);
resolve();
}, delay);
});
}
// 立即保存应用数据
static async saveData(key: string, data: any): Promise<void> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_DATA], 'readwrite');
const store = transaction.objectStore(this.STORE_DATA);
const request = store.put(data, key);
request.onsuccess = () => resolve();
request.onerror = () => reject(new Error('保存数据失败'));
});
}
// 获取应用数据
static async getData(key: string): Promise<any> {
const db = await this.init();
return new Promise((resolve, reject) => {
const transaction = db.transaction([this.STORE_DATA], 'readonly');
const store = transaction.objectStore(this.STORE_DATA);
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(new Error('获取数据失败'));
});
}
}
/**
* 照片服务
*/
class PhotoService {
// 压缩图片到指定质量
private static async compressImage(dataUrl: string, maxWidth: number = 1920, quality: number = 0.8): Promise<string> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// 按比例缩放
if (width > maxWidth) {
height = (height * maxWidth) / width;
width = maxWidth;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('无法创建Canvas上下文'));
return;
}
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL('image/jpeg', quality));
};
img.onerror = () => reject(new Error('图片加载失败'));
img.src = dataUrl;
});
}
// 生成缩略图
private static async generateThumbnail(dataUrl: string): Promise<string> {
return this.compressImage(dataUrl, 200, 0.6);
}
// 使用相机拍照或从相册选择
static async pickPhoto(): Promise<Photo | null> {
try {
const { Camera, CameraSource, CameraResultType } = await import('@capacitor/camera');
const image = await Camera.getPhoto({
quality: 90,
source: CameraSource.Prompt, // 弹出选择:相机或相册
resultType: CameraResultType.DataUrl,
allowEditing: true,
width: 1920,
});
if (!image.dataUrl) {
return null;
}
// 生成ID
const id = 'photo-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
// 压缩原图
const compressedData = await this.compressImage(image.dataUrl);
// 生成缩略图
const thumbnail = await this.generateThumbnail(image.dataUrl);
// 计算大小
const size = new Blob([compressedData]).size;
const photo: Photo = {
id,
data: compressedData,
thumbnail,
timestamp: new Date().toISOString(),
size
};
// 存储到IndexedDB
await IndexedDBService.savePhoto(photo);
return photo;
} catch (error) {
console.error('选择照片失败:', error);
throw error;
}
}
static async getPhoto(id: string): Promise<Photo | null> {
return await IndexedDBService.getPhoto(id);
}
static async deletePhoto(id: string): Promise<boolean> {
try {
await IndexedDBService.deletePhoto(id);
return true;
} catch (error) {
console.error('删除照片失败:', error);
return false;
}
}
static async getStorageUsage(): Promise<{ used: number; total: number }> {
const used = await IndexedDBService.getStorageSize();
const total = 50 * 1024 * 1024; // 50MB
return { used, total };
}
}
/**
* 配对服务
*/
// --- Helper Functions ---
// 获取记仇/回忆的同步状态
const getSyncStatus = (item: Grudge | Memory, profile: UserProfile): '已同步' | '会被同步' | '不会被同步' => {
// 如果标记为私密,不会被同步
if (item.isPrivate) {
return '不会被同步';
}
// 如果是自己创建的记录,会被同步(当配对时)
if (item.authorDeviceId === profile.deviceId) {
return '会被同步';
}
// 如果是对方的记录(authorDeviceId不同),说明已经同步过来了
return '已同步';
};
// 获取作者标签(用于显示记录的创建者)
const getAuthorLabel = (item: Grudge | Memory, profile: UserProfile): { text: string; isMine: boolean; emoji: string } => {
// 如果没有作者信息(旧数据),默认认为是自己的
if (!item.authorDeviceId) {
return { text: '我的记录', isMine: true, emoji: '✍️' };
}
// 是自己创建的
if (item.authorDeviceId === profile.deviceId) {
return { text: '我的记录', isMine: true, emoji: '✍️' };
}
// 是对方创建的
const partnerName = profile.partner?.name || 'TA';
const partnerCallName = profile.partner?.callsMe || partnerName;
return { text: `${partnerCallName}的记录`, isMine: false, emoji: '💌' };
};
class PairingService {
// 生成配对邀请数据
static generatePairInvite(profile: UserProfile, callName: string): PairInvite {
return {
type: 'pair_invite',
version: '1.0',
timestamp: Date.now(),
inviter: {
id: profile.deviceId,
role: profile.role!,
name: profile.name,
callName: callName // 期望对方怎么叫自己
}
};
}
// 生成配对确认数据
static generatePairConfirm(
profile: UserProfile,
invite: PairInvite,
myCallName: string,
partnerCallsMe: string,
anniversary?: string
): PairConfirm {
return {
type: 'pair_confirm',
version: '1.0',
timestamp: Date.now(),
responder: {
id: profile.deviceId,
role: profile.role!,
name: profile.name,
callName: partnerCallsMe // 我希望对方叫我什么
},
relationship: {
partnerCallsMe: myCallName, // 对方叫我什么 (实际是invite中的inviter的callName)
myCallName: myCallName, // 我叫对方什么
anniversary
},
linkTo: invite.inviter.id
};
}
// 编码二维码数据(压缩)
static encodeQRData(data: QRCodeData): string {
const json = JSON.stringify(data);
return LZString.compressToBase64(json);
}
// 解码二维码数据
static decodeQRData(encoded: string): QRCodeData | null {
try {
const decompressed = LZString.decompressFromBase64(encoded);
if (!decompressed) return null;
return JSON.parse(decompressed) as QRCodeData;
} catch (error) {
console.error('解码二维码失败:', error);
return null;
}
}
// 生成同步数据
static generateSyncData(
deviceId: string,
grudges: Grudge[],
memories: Memory[]
): SyncData {
// 过滤掉私密内容,只同步非私密的数据
const publicGrudges = grudges.filter(g => !g.isPrivate);
const publicMemories = memories.filter(m => !m.isPrivate);
return {
type: 'data_sync',
version: '1.0',
from: deviceId,
timestamp: Date.now(),
syncId: 'sync-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9),
data: {
grudges: publicGrudges,
memories: publicMemories
},
stats: {
totalGrudges: publicGrudges.length,
totalMemories: publicMemories.length
}
};
}
// 扫描二维码(使用摄像头)
static async scanQRCode(): Promise<string | null> {
try {
console.log('开始扫描二维码...');
// 检查是否支持扫描
const isSupported = await BarcodeScanner.isSupported();
console.log('扫描功能支持状态:', isSupported);
if (!isSupported) {
throw new Error('当前设备不支持二维码扫描');
}
// 检查 Google Barcode Scanner 模块是否已安装
console.log('检查 Google Barcode Scanner 模块...');
const { available } = await BarcodeScanner.isGoogleBarcodeScannerModuleAvailable();
if (!available) {
console.log('Google Barcode Scanner 模块未安装,开始安装...');
await BarcodeScanner.installGoogleBarcodeScannerModule();
console.log('Google Barcode Scanner 模块安装完成');
} else {
console.log('Google Barcode Scanner 模块已可用');
}
// 请求相机权限
console.log('请求相机权限...');
const permission = await BarcodeScanner.requestPermissions();
console.log('权限结果:', permission);
if (permission.camera !== 'granted') {
throw new Error('需要相机权限才能扫描二维码');
}
// 开始扫描
console.log('启动扫描界面...');
const result = await BarcodeScanner.scan();
console.log('扫描结果:', result);
if (result.barcodes && result.barcodes.length > 0) {
const qrValue = result.barcodes[0].rawValue || null;
console.log('读取到二维码:', qrValue?.substring(0, 50) + '...');
return qrValue;
}
console.log('未扫描到二维码');
return null;
} catch (error) {
console.error('扫描二维码失败:', error);
const errorMsg = error instanceof Error ? error.message : String(error);
throw new Error('扫描失败: ' + errorMsg);
}
}
// 从相册选择二维码图片
static async pickQRCodeFromGallery(): Promise<string | null> {
try {
console.log('打开相册选择图片...');
const { Camera, CameraSource, CameraResultType } = await import('@capacitor/camera');
const image = await Camera.getPhoto({
quality: 100,
source: CameraSource.Photos, // 从相册选择
resultType: CameraResultType.DataUrl,
allowEditing: false
});
if (!image.dataUrl) {
console.log('未获取到图片数据');
return null;
}
console.log('开始解析图片中的二维码...');
// 创建图片元素加载图片
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
try {
// 创建 canvas 绘制图片
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('无法创建 Canvas 上下文'));
return;
}
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// 使用 jsQR 解析二维码
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'dontInvert'
});
if (code) {
console.log('成功识别二维码:', code.data.substring(0, 50) + '...');
resolve(code.data);
} else {
console.log('图片中未识别到二维码');
resolve(null);
}
} catch (error) {
console.error('解析二维码失败:', error);
reject(error);
}
};
img.onerror = () => {
reject(new Error('图片加载失败'));
};
img.src = image.dataUrl!;
});
} catch (error) {
console.error('从相册选择二维码失败:', error);
throw error;
}
}
}
/**
* 成就系统
*/
// 成就定义列表
const ACHIEVEMENT_DEFINITIONS: Omit<Achievement, 'unlocked' | 'unlockedAt' | 'progress'>[] = [
// 记仇类成就
{ id: 'grudge_first', name: '第一笔账', description: '记录第一条记仇', icon: '📝', target: 1, category: 'grudge' },
{ id: 'grudge_10', name: '记仇达人', description: '记录10条记仇', icon: '📚', target: 10, category: 'grudge' },
{ id: 'grudge_50', name: '账本专家', description: '记录50条记仇', icon: '📖', target: 50, category: 'grudge' },
{ id: 'grudge_100', name: '记仇大师', description: '记录100条记仇', icon: '🏆', target: 100, category: 'grudge' },
{ id: 'high_anger', name: '火山爆发', description: '单条愤怒值达到100', icon: '🌋', target: 1, category: 'grudge' },
{ id: 'daily_5', name: '脾气暴躁', description: '单日记录5条记仇', icon: '😤', target: 5, category: 'grudge' },
{ id: 'grudge_tag_first', name: '贴标签', description: '为记仇添加第一个标签', icon: '🏷️', target: 1, category: 'grudge' },
{ id: 'grudge_photo_10', name: '铁证如山', description: '记仇记录中上传10张照片', icon: '📸', target: 10, category: 'grudge' },
// 回忆类成就
{ id: 'memory_first', name: '第一份甜蜜', description: '记录第一条回忆', icon: '💕', target: 1, category: 'memory' },
{ id: 'memory_10', name: '甜蜜回忆', description: '记录10条回忆', icon: '🎀', target: 10, category: 'memory' },
{ id: 'memory_50', name: '幸福满溢', description: '记录50条回忆', icon: '💖', target: 50, category: 'memory' },
{ id: 'memory_100', name: '爱的见证', description: '记录100条回忆', icon: '💝', target: 100, category: 'memory' },
{ id: 'high_sweet', name: '超级感动', description: '单条甜蜜度达到100', icon: '🌟', target: 1, category: 'memory' },
{ id: 'daily_memory_3', name: '天天甜蜜', description: '单日记录3条回忆', icon: '🥰', target: 3, category: 'memory' },
{ id: 'memory_photo_10', name: '美好瞬间', description: '回忆记录中上传10张照片', icon: '📷', target: 10, category: 'memory' },
// 和解类成就
{ id: 'forgive_first', name: '第一次原谅', description: '原谅第一条记录', icon: '🤝', target: 1, category: 'harmony' },
{ id: 'forgive_10', name: '宽容大度', description: '原谅10条记录', icon: '😊', target: 10, category: 'harmony' },
{ id: 'forgive_50', name: '和平使者', description: '原谅50条记录', icon: '🕊️', target: 50, category: 'harmony' },
{ id: 'forgive_rate_80', name: '天使伴侣', description: '原谅率达到80%', icon: '👼', target: 80, category: 'harmony' },
{ id: 'harmony_80', name: '完美关系', description: '和谐度达到80分', icon: '💯', target: 80, category: 'harmony' },
{ id: 'harmony_perfect', name: '神仙眷侣', description: '和谐度达到95分', icon: '✨', target: 95, category: 'harmony' },
{ id: 'quick_forgive', name: '闪电和解', description: '1小时内原谅一条记仇', icon: '⚡', target: 1, category: 'harmony' },
// 综合类成就
{ id: 'balance', name: '完美平衡', description: '正负记录比例1:1', icon: '⚖️', target: 1, category: 'harmony' },
{ id: 'total_100', name: '百里挑一', description: '总记录数达到100', icon: '💯', target: 100, category: 'harmony' },
{ id: 'total_365', name: '天长地久', description: '总记录数达到365', icon: '🎊', target: 365, category: 'harmony' },
{ id: 'use_30days', name: '忠实用户', description: '使用APP满30天', icon: '📅', target: 30, category: 'harmony' },
{ id: 'continuous_3days', name: '坚持不懈', description: '连续3天记录', icon: '🔥', target: 3, category: 'harmony' },
{ id: 'continuous_7days', name: '一周之约', description: '连续7天记录', icon: '🌈', target: 7, category: 'harmony' },
{ id: 'night_owl', name: '深夜档案', description: '在23:00后记录10次', icon: '🦉', target: 10, category: 'harmony' },
{ id: 'early_bird', name: '清晨记录', description: '在6:00-8:00记录10次', icon: '🌅', target: 10, category: 'harmony' },
{ id: 'delete_master', name: '冷静思考', description: '删除记录达5次', icon: '🗑️', target: 5, category: 'harmony' },
];
class AchievementService {
/**
* 初始化成就列表
*/
static initAchievements(): Achievement[] {
return ACHIEVEMENT_DEFINITIONS.map(def => ({
...def,
unlocked: false,
unlockedAt: null,
progress: 0
}));
}
/**
* 检查并更新所有成就
* 返回新解锁的成就列表
*/
static checkAchievements(
grudges: Grudge[],
memories: Memory[],
currentAchievements: Achievement[],
profile: UserProfile
): { achievements: Achievement[], newlyUnlocked: Achievement[] } {
const updatedAchievements = [...currentAchievements];
const newlyUnlocked: Achievement[] = [];
const stats = this.calculateStats(grudges, memories, profile);
updatedAchievements.forEach(achievement => {
if (achievement.unlocked) return;
let progress = 0;
let shouldUnlock = false;
// 根据成就 ID 计算进度
switch (achievement.id) {
case 'grudge_first':
case 'grudge_10':
case 'grudge_50':
case 'grudge_100':
progress = grudges.length;
shouldUnlock = progress >= achievement.target;
break;
case 'memory_first':
case 'memory_10':
case 'memory_50':
case 'memory_100':
progress = memories.length;
shouldUnlock = progress >= achievement.target;
break;
case 'forgive_first':
case 'forgive_10':
case 'forgive_50':
progress = stats.forgivenCount;
shouldUnlock = progress >= achievement.target;
break;
case 'high_anger':
progress = stats.maxAnger;
shouldUnlock = progress >= achievement.target;
break;
case 'high_sweet':
progress = stats.maxSweetness;
shouldUnlock = progress >= achievement.target;
break;
case 'daily_5':
progress = stats.maxDailyGrudges;
shouldUnlock = progress >= achievement.target;
break;
case 'daily_memory_3':
progress = stats.maxDailyMemories;
shouldUnlock = progress >= achievement.target;
break;
case 'forgive_rate_80':
progress = stats.forgivenessRate;
shouldUnlock = progress >= achievement.target && grudges.length >= 10;
break;
case 'harmony_80':
case 'harmony_perfect':
progress = stats.harmonyScore;
shouldUnlock = progress >= achievement.target;
break;
case 'balance':
progress = stats.balanceRatio;
shouldUnlock = stats.balanceRatio >= 0.8 && stats.balanceRatio <= 1.2 && grudges.length >= 10 && memories.length >= 10;
break;
case 'total_100':
case 'total_365':
progress = grudges.length + memories.length;
shouldUnlock = progress >= achievement.target;
break;
case 'use_30days':
progress = stats.usageDays;
shouldUnlock = progress >= achievement.target;
break;
case 'grudge_tag_first':
progress = stats.grudgeTagCount;
shouldUnlock = progress >= achievement.target;
break;
case 'grudge_photo_10':
progress = stats.grudgePhotoCount;
shouldUnlock = progress >= achievement.target;
break;
case 'memory_photo_10':
progress = stats.memoryPhotoCount;
shouldUnlock = progress >= achievement.target;
break;
case 'quick_forgive':
progress = stats.quickForgivCount;
shouldUnlock = progress >= achievement.target;
break;
case 'continuous_3days':
case 'continuous_7days':
progress = stats.continuousDays;
shouldUnlock = progress >= achievement.target;
break;
case 'night_owl':
progress = stats.nightRecordCount;
shouldUnlock = progress >= achievement.target;
break;
case 'early_bird':
progress = stats.earlyRecordCount;
shouldUnlock = progress >= achievement.target;
break;
case 'delete_master':
progress = stats.deleteCount;
shouldUnlock = progress >= achievement.target;
break;
}
achievement.progress = Math.min(progress, achievement.target);
if (shouldUnlock) {
achievement.unlocked = true;
achievement.unlockedAt = new Date().toISOString();
newlyUnlocked.push(achievement);
}
});
return { achievements: updatedAchievements, newlyUnlocked };
}
/**
* 计算统计数据用于成就检测
*/
private static calculateStats(grudges: Grudge[], memories: Memory[], profile: UserProfile) {
const forgivenCount = grudges.filter(g => g.status === 'forgiven').length;
const forgivenessRate = grudges.length > 0 ? (forgivenCount / grudges.length) * 100 : 0;
const maxAnger = grudges.length > 0 ? Math.max(...grudges.map(g => g.severity)) : 0;
const maxSweetness = memories.length > 0 ? Math.max(...memories.map(m => m.sweetness)) : 0;
// 计算单日最大记录数
const grudgeDates: { [key: string]: number } = {};
grudges.forEach(g => {
const date = new Date(g.date).toDateString();
grudgeDates[date] = (grudgeDates[date] || 0) + 1;
});
const maxDailyGrudges = Object.values(grudgeDates).length > 0 ? Math.max(...Object.values(grudgeDates)) : 0;
const memoryDates: { [key: string]: number } = {};
memories.forEach(m => {
const date = new Date(m.date).toDateString();
memoryDates[date] = (memoryDates[date] || 0) + 1;
});
const maxDailyMemories = Object.values(memoryDates).length > 0 ? Math.max(...Object.values(memoryDates)) : 0;
// 计算和谐度(简化版)
const activeAnger = grudges.filter(g => g.status === 'active').reduce((sum, g) => sum + g.severity, 0);
const totalSweetness = memories.reduce((sum, m) => sum + m.sweetness, 0);
const harmonyScore = Math.max(0, Math.min(100, 50 + (totalSweetness / 10 - activeAnger / 5)));
// 正负记录比例
const balanceRatio = memories.length > 0 ? grudges.length / memories.length : 0;
// 使用天数(从第一条记录开始)
const allDates = [...grudges.map(g => new Date(g.date)), ...memories.map(m => new Date(m.date))];
const firstDate = allDates.length > 0 ? Math.min(...allDates.map(d => d.getTime())) : Date.now();
const usageDays = Math.floor((Date.now() - firstDate) / (1000 * 60 * 60 * 24));
// 标签统计
const grudgeTagCount = grudges.filter(g => g.tags && g.tags.length > 0).length;
// 照片统计