index.html
69.6 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>lemonPCRM — 人脉管理</title>
<!-- vis-network -->
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<!-- Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<style>
/* ─── Reset & Base ─── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f0f12;
--card: #1a1a22;
--card2: #22222e;
--border: #2a2a38;
--text: #e8e8f0;
--muted: #8888a8;
--accent: #6366f1;
--accent-hover: #7c7ff5;
--success: #22c55e;
--warning: #f59e0b;
--danger: #ef4444;
--radius: 8px;
--sidebar-width: 280px;
--header-height: 52px;
}
html, body { height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; }
/* ─── Scrollbars ─── */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
/* ─── Layout ─── */
#app { display: flex; flex-direction: column; height: 100vh; min-width: 1024px; }
/* Header */
header {
height: var(--header-height);
background: var(--card);
border-bottom: 1px solid var(--border);
display: flex; align-items: center; padding: 0 20px; gap: 12px;
flex-shrink: 0; z-index: 100;
}
.logo { font-size: 18px; font-weight: 700; color: var(--text); display: flex; align-items: center; gap: 6px; }
.logo-icon { font-size: 20px; }
header .spacer { flex: 1; }
.btn {
display: inline-flex; align-items: center; gap: 6px;
padding: 6px 14px; border-radius: var(--radius);
border: 1px solid var(--border); background: var(--card2);
color: var(--text); cursor: pointer; font-size: 13px;
transition: background 0.15s, border-color 0.15s;
}
.btn:hover { background: #2d2d3d; border-color: var(--accent); }
.btn-primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn-sm { padding: 4px 10px; font-size: 12px; }
/* Body (sidebar + main) */
.body { display: flex; flex: 1; overflow: hidden; }
/* Sidebar */
#sidebar {
width: var(--sidebar-width); flex-shrink: 0;
background: var(--card); border-right: 1px solid var(--border);
display: flex; flex-direction: column;
}
.sidebar-search {
padding: 12px;
border-bottom: 1px solid var(--border);
}
.search-wrap { position: relative; }
.search-wrap input {
width: 100%; padding: 8px 32px 8px 10px;
background: var(--card2); border: 1px solid var(--border);
border-radius: var(--radius); color: var(--text); font-size: 13px;
outline: none; transition: border-color 0.15s;
}
.search-wrap input:focus { border-color: var(--accent); }
.search-wrap input::placeholder { color: var(--muted); }
.search-icon { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: var(--muted); font-size: 14px; pointer-events: none; }
#contact-list { flex: 1; overflow-y: auto; }
.contact-item {
display: flex; align-items: center; gap: 10px;
padding: 10px 14px; cursor: pointer;
border-bottom: 1px solid transparent;
transition: background 0.12s;
}
.contact-item:hover { background: var(--card2); }
.contact-item.active { background: rgba(99,102,241,0.12); border-left: 2px solid var(--accent); padding-left: 12px; }
.status-dot {
width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0;
}
.status-dot.complete { background: var(--success); box-shadow: 0 0 4px rgba(34,197,94,0.5); }
.status-dot.partial { background: #3b82f6; box-shadow: 0 0 4px rgba(59,130,246,0.5); }
.status-dot.none { background: var(--muted); }
.contact-info { flex: 1; min-width: 0; }
.contact-name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.contact-company { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sidebar-footer {
padding: 10px 14px; border-top: 1px solid var(--border);
font-size: 12px; color: var(--muted);
}
/* Main panel */
#main { flex: 1; display: flex; flex-direction: column; overflow: hidden; position: relative; }
/* Tab bar */
.tab-bar {
display: flex; gap: 2px; padding: 0 16px;
background: var(--card); border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.tab {
padding: 12px 16px; cursor: pointer; font-size: 13px;
color: var(--muted); border-bottom: 2px solid transparent;
transition: color 0.15s, border-color 0.15s; white-space: nowrap;
}
.tab:hover { color: var(--text); }
.tab.active { color: var(--accent); border-bottom-color: var(--accent); }
/* Canvas area */
#canvas-area { flex: 1; overflow-y: auto; padding: 20px; position: relative; }
/* Tab panels */
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* Empty state */
.empty-state {
display: flex; flex-direction: column; align-items: center; justify-content: center;
height: 60vh; gap: 16px; color: var(--muted);
}
.empty-state .icon { font-size: 48px; }
.empty-state h3 { font-size: 18px; color: var(--text); }
.empty-state p { font-size: 14px; text-align: center; max-width: 360px; line-height: 1.6; }
/* Profile view */
.profile-header {
display: flex; align-items: flex-start; gap: 16px; margin-bottom: 24px;
}
.avatar-circle {
width: 56px; height: 56px; border-radius: 50%;
background: linear-gradient(135deg, var(--accent), #8b5cf6);
display: flex; align-items: center; justify-content: center;
font-size: 22px; font-weight: 700; color: #fff; flex-shrink: 0;
}
.profile-meta { flex: 1; }
.profile-name { font-size: 22px; font-weight: 700; }
.profile-sub { color: var(--muted); margin-top: 4px; }
.profile-actions { display: flex; gap: 8px; align-items: flex-start; }
.info-grid {
display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;
margin-bottom: 24px;
}
.info-card {
background: var(--card); border: 1px solid var(--border);
border-radius: var(--radius); padding: 14px;
}
.info-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin-bottom: 6px; }
.info-value { font-size: 14px; word-break: break-all; }
.info-value a { color: var(--accent); text-decoration: none; }
.info-value a:hover { text-decoration: underline; }
.info-value.empty { color: var(--muted); font-style: italic; }
.section-title { font-size: 13px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 12px; }
.edges-list { display: flex; flex-direction: column; gap: 8px; }
.edge-item {
display: flex; align-items: center; gap: 10px;
background: var(--card); border: 1px solid var(--border);
border-radius: var(--radius); padding: 10px 14px; cursor: pointer;
transition: border-color 0.15s;
}
.edge-item:hover { border-color: var(--accent); }
.edge-relation { font-size: 11px; background: rgba(99,102,241,0.15); color: var(--accent); border-radius: 4px; padding: 2px 7px; }
.edge-name { font-weight: 500; }
.edge-type { font-size: 12px; color: var(--muted); }
/* Graph view */
#graph-container { width: 100%; height: 500px; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
.graph-placeholder { display: flex; align-items: center; justify-content: center; height: 500px; color: var(--muted); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
/* Timeline view */
.timeline-filters { display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; }
.filter-chip {
padding: 4px 12px; border-radius: 20px; font-size: 12px;
border: 1px solid var(--border); background: var(--card2);
color: var(--muted); cursor: pointer; transition: all 0.15s;
}
.filter-chip.active { background: var(--accent); border-color: var(--accent); color: #fff; }
.timeline { display: flex; flex-direction: column; gap: 0; margin-bottom: 24px; }
.timeline-item {
display: flex; gap: 14px; padding: 14px 0;
border-bottom: 1px solid var(--border);
}
.tl-icon {
width: 32px; height: 32px; border-radius: 50%; flex-shrink: 0;
display: flex; align-items: center; justify-content: center; font-size: 14px;
background: var(--card2);
}
.tl-content { flex: 1; }
.tl-date { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
.tl-summary { line-height: 1.5; }
.tl-tags { margin-top: 6px; display: flex; gap: 6px; flex-wrap: wrap; }
.tag { font-size: 11px; padding: 2px 8px; border-radius: 12px; background: var(--card2); color: var(--muted); }
#map-container { height: 240px; border-radius: var(--radius); overflow: hidden; border: 1px solid var(--border); margin-top: 16px; }
/* Insights view */
.stats-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 24px; }
.stat-card {
background: var(--card); border: 1px solid var(--border);
border-radius: var(--radius); padding: 16px; text-align: center;
}
.stat-num { font-size: 28px; font-weight: 700; color: var(--accent); }
.stat-label { font-size: 12px; color: var(--muted); margin-top: 4px; }
.bar-chart { display: flex; flex-direction: column; gap: 10px; margin-bottom: 24px; }
.bar-row { display: flex; align-items: center; gap: 12px; }
.bar-label { width: 100px; font-size: 12px; color: var(--muted); text-align: right; flex-shrink: 0; }
.bar-track { flex: 1; height: 8px; background: var(--card2); border-radius: 4px; overflow: hidden; }
.bar-fill { height: 100%; background: var(--accent); border-radius: 4px; transition: width 0.5s ease; }
.bar-count { width: 30px; font-size: 12px; color: var(--muted); text-align: right; flex-shrink: 0; }
.followup-list { display: flex; flex-direction: column; gap: 8px; }
.followup-item {
display: flex; gap: 10px; align-items: flex-start;
background: var(--card); border: 1px solid var(--border);
border-radius: var(--radius); padding: 10px 14px;
}
.followup-check { color: var(--warning); font-size: 16px; flex-shrink: 0; margin-top: 1px; }
/* AI Report view */
.report-toolbar { display: flex; gap: 8px; margin-bottom: 16px; }
#report-output {
background: var(--card); border: 1px solid var(--border);
border-radius: var(--radius); padding: 20px; min-height: 420px;
font-family: 'SF Mono', 'Fira Code', monospace; font-size: 13px;
line-height: 1.7; white-space: pre-wrap; overflow-y: auto;
color: var(--text);
}
#report-output .placeholder { color: var(--muted); font-style: italic; font-family: inherit; }
.streaming-cursor::after { content: '▋'; animation: blink 1s step-end infinite; }
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
/* AI Chat widget */
#chat-widget {
position: fixed; bottom: 24px; right: 24px;
width: 360px; z-index: 200;
}
.chat-header {
background: var(--accent); color: #fff;
padding: 10px 14px; border-radius: var(--radius) var(--radius) 0 0;
display: flex; align-items: center; justify-content: space-between;
cursor: pointer; user-select: none;
}
.chat-header-left { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 13px; }
.chat-toggle-btn { background: rgba(255,255,255,0.2); border: none; color: #fff; width: 22px; height: 22px; border-radius: 4px; cursor: pointer; font-size: 14px; display: flex; align-items: center; justify-content: center; }
.chat-body {
background: var(--card); border: 1px solid var(--border); border-top: none;
border-radius: 0 0 var(--radius) var(--radius);
display: flex; flex-direction: column;
transition: height 0.2s ease;
overflow: hidden;
}
.chat-body.collapsed { height: 0; }
#chat-messages {
flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px;
height: 260px;
}
.chat-msg {
max-width: 85%; padding: 8px 12px; border-radius: 10px; font-size: 13px; line-height: 1.5;
}
.chat-msg.user { background: var(--accent); color: #fff; align-self: flex-end; border-bottom-right-radius: 2px; }
.chat-msg.assistant { background: var(--card2); color: var(--text); align-self: flex-start; border-bottom-left-radius: 2px; }
.chat-msg.assistant.streaming { border-bottom-left-radius: 2px; }
.chat-input-row {
display: flex; gap: 6px; padding: 8px 10px;
border-top: 1px solid var(--border);
}
#chat-input {
flex: 1; padding: 8px 10px; background: var(--card2);
border: 1px solid var(--border); border-radius: 6px;
color: var(--text); font-size: 13px; outline: none; resize: none;
transition: border-color 0.15s; max-height: 80px;
}
#chat-input:focus { border-color: var(--accent); }
#chat-input::placeholder { color: var(--muted); }
#chat-send { background: var(--accent); border: none; border-radius: 6px; color: #fff; padding: 8px 12px; cursor: pointer; font-size: 14px; transition: background 0.15s; flex-shrink: 0; }
#chat-send:hover { background: var(--accent-hover); }
/* Modal */
.modal-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,0.6);
display: flex; align-items: center; justify-content: center;
z-index: 300; opacity: 0; pointer-events: none; transition: opacity 0.2s;
}
.modal-overlay.show { opacity: 1; pointer-events: auto; }
.modal {
background: var(--card); border: 1px solid var(--border);
border-radius: 12px; padding: 28px; width: 380px; max-width: 90vw;
}
.modal h3 { font-size: 16px; font-weight: 600; margin-bottom: 12px; }
.modal p { color: var(--muted); font-size: 13px; line-height: 1.6; margin-bottom: 16px; }
.progress-bar { height: 6px; background: var(--card2); border-radius: 3px; overflow: hidden; }
.progress-fill { height: 100%; background: var(--accent); border-radius: 3px; transition: width 0.3s ease; }
.modal-status { font-size: 13px; color: var(--muted); margin-top: 10px; }
/* Toast */
#toast-container {
position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; gap: 8px; z-index: 400;
pointer-events: none;
}
.toast {
padding: 10px 18px; border-radius: 8px; font-size: 13px;
color: #fff; opacity: 0; transform: translateY(10px);
transition: all 0.25s; white-space: nowrap;
}
.toast.show { opacity: 1; transform: translateY(0); }
.toast.success { background: #166534; border: 1px solid var(--success); }
.toast.error { background: #7f1d1d; border: 1px solid var(--danger); }
.toast.info { background: #1e3a5f; border: 1px solid #3b82f6; }
/* Sort bar */
.sort-bar {
display: flex; align-items: center; gap: 6px;
padding: 6px 12px 8px; border-bottom: 1px solid var(--border);
}
.sort-select {
flex: 1; padding: 5px 8px; font-size: 12px;
background: var(--card2); border: 1px solid var(--border);
border-radius: var(--radius); color: var(--text);
cursor: pointer; outline: none;
}
.sort-select:focus { border-color: var(--accent); }
.sort-order-btn {
padding: 5px 9px; font-size: 12px;
background: var(--card2); border: 1px solid var(--border);
border-radius: var(--radius); color: var(--text);
cursor: pointer; transition: background 0.15s; white-space: nowrap;
}
.sort-order-btn:hover { background: #2d2d3d; border-color: var(--accent); }
/* ─── Chat viewer ─── */
.chat-toolbar {
display: flex; align-items: center; gap: 8px; margin-bottom: 10px;
}
.chat-search-input {
flex: 1; padding: 6px 10px; font-size: 12px;
background: var(--card2); border: 1px solid var(--border);
border-radius: var(--radius); color: var(--text); outline: none;
}
.chat-search-input:focus { border-color: var(--accent); }
.chat-search-input::placeholder { color: var(--muted); }
.chat-info { font-size: 11px; color: var(--muted); white-space: nowrap; }
.msg-list { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; }
.msg-item { display: flex; padding: 2px 0; width: 100%; }
.msg-item.other { justify-content: flex-start; }
.msg-item.self { justify-content: flex-end; }
.msg-col {
max-width: 65%; display: flex; flex-direction: column;
}
.msg-item.other .msg-col { align-items: flex-start; }
.msg-item.self .msg-col { align-items: flex-end; }
.msg-bubble {
padding: 8px 12px; border-radius: 12px;
font-size: 13px; line-height: 1.55; word-break: break-word;
display: inline-block;
}
.msg-item.other .msg-bubble { background: var(--card2); border-bottom-left-radius: 3px; }
.msg-item.self .msg-bubble { background: rgba(99,102,241,0.25); border-bottom-right-radius: 3px; }
.msg-meta { font-size: 10px; color: var(--muted); margin-top: 2px; padding: 0 2px; }
.msg-sender { font-size: 11px; color: var(--accent); margin-bottom: 2px; }
.msg-highlight { background: rgba(245,158,11,0.35); border-radius: 2px; }
.chat-pagination {
display: flex; align-items: center; justify-content: center;
gap: 8px; padding: 8px 0 4px; border-top: 1px solid var(--border);
}
.page-btn {
padding: 4px 12px; font-size: 12px;
background: var(--card2); border: 1px solid var(--border);
border-radius: var(--radius); color: var(--text);
cursor: pointer; transition: background 0.15s;
}
.page-btn:hover:not(:disabled) { background: #2d2d3d; border-color: var(--accent); }
.page-btn:disabled { opacity: 0.35; cursor: default; }
.page-label { font-size: 12px; color: var(--muted); }
/* Misc */
.loading-spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.7s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.divider { height: 1px; background: var(--border); margin: 20px 0; }
</style>
</head>
<body>
<div id="app">
<!-- Header -->
<header>
<div class="logo">
<span class="logo-icon">🍋</span>
lemonPCRM
</div>
<div class="spacer"></div>
<button class="btn btn-primary" id="btn-import-wechat">
<span>📱</span> 导入微信联系人
</button>
<button class="btn" id="btn-settings">
<span>⚙️</span> 设置
</button>
</header>
<!-- Body -->
<div class="body">
<!-- Sidebar -->
<aside id="sidebar">
<div class="sidebar-search">
<div class="search-wrap">
<input type="text" id="search-input" placeholder="搜索联系人..." />
<span class="search-icon">🔍</span>
</div>
</div>
<div class="sort-bar">
<select id="sort-select" class="sort-select">
<option value="name">按名字排序</option>
<option value="count">按对话次数</option>
<option value="lastChat">按最后对话</option>
</select>
<button id="sort-order-btn" class="sort-order-btn">↑ 升序</button>
</div>
<div id="contact-list"></div>
<div class="sidebar-footer">
<span id="contact-count">0</span> 位联系人
</div>
</aside>
<!-- Main -->
<main id="main">
<nav class="tab-bar">
<div class="tab active" data-tab="profile">📋 档案</div>
<div class="tab" data-tab="chat">💬 聊天</div>
<div class="tab" data-tab="graph">🕸️ 图谱</div>
<div class="tab" data-tab="timeline">📅 时间轴</div>
<div class="tab" data-tab="insights">💡 对话洞察</div>
<div class="tab" data-tab="report">🤖 AI 报告</div>
</nav>
<div id="canvas-area">
<!-- Profile panel -->
<div class="tab-panel active" id="panel-profile">
<div class="empty-state" id="empty-profile">
<div class="icon">👤</div>
<h3>选择一位联系人</h3>
<p>从左侧列表选择联系人查看详细档案,或点击「导入微信联系人」开始构建你的人脉图谱。</p>
</div>
<div id="profile-content" style="display:none;"></div>
</div>
<!-- Chat panel -->
<div class="tab-panel" id="panel-chat" style="display:flex;flex-direction:column;height:100%;">
<div class="empty-state" id="empty-chat">
<div class="icon">💬</div>
<h3>选择联系人查看聊天记录</h3>
<p>从左侧选择有微信 ID 的联系人,在此查看完整聊天记录。</p>
</div>
<div id="chat-tab-content" style="display:none;flex:1;display:none;flex-direction:column;">
<div id="chat-contact-header" style="padding:0 0 12px;border-bottom:1px solid var(--border);margin-bottom:12px;"></div>
<div id="chat-viewer"></div>
</div>
</div>
<!-- Graph panel -->
<div class="tab-panel" id="panel-graph">
<div class="empty-state" id="empty-graph">
<div class="icon">🕸️</div>
<h3>选择联系人查看关系图谱</h3>
<p>关系图谱展示选中联系人及其直接关系网络。</p>
</div>
<div id="graph-content" style="display:none;">
<div id="graph-container"></div>
</div>
</div>
<!-- Timeline panel -->
<div class="tab-panel" id="panel-timeline">
<div class="empty-state" id="empty-timeline">
<div class="icon">📅</div>
<h3>选择联系人查看时间轴</h3>
<p>时间轴记录与该联系人的所有互动事件。</p>
</div>
<div id="timeline-content" style="display:none;"></div>
</div>
<!-- Insights panel -->
<div class="tab-panel" id="panel-insights">
<div class="empty-state" id="empty-insights">
<div class="icon">💡</div>
<h3>选择联系人查看对话洞察</h3>
<p>对话洞察展示与该联系人的互动统计和话题分布。</p>
</div>
<div id="insights-content" style="display:none;"></div>
</div>
<!-- Report panel -->
<div class="tab-panel" id="panel-report">
<div class="empty-state" id="empty-report">
<div class="icon">🤖</div>
<h3>选择联系人生成 AI 报告</h3>
<p>AI 报告基于所有已有信息为该联系人生成全面分析。</p>
</div>
<div id="report-content" style="display:none;">
<div class="report-toolbar">
<button class="btn btn-primary" id="btn-gen-report">🤖 生成 AI 报告</button>
<button class="btn" id="btn-export-md">📥 导出 Markdown</button>
</div>
<div id="report-output"><span class="placeholder">点击「生成 AI 报告」开始生成…</span></div>
</div>
</div>
</div>
</main>
</div>
</div>
<!-- AI Chat Widget -->
<div id="chat-widget">
<div class="chat-header" id="chat-header">
<div class="chat-header-left">
<span>🤖</span> AI 助手
</div>
<button class="chat-toggle-btn" id="chat-toggle">▼</button>
</div>
<div class="chat-body" id="chat-body">
<div id="chat-messages"></div>
<div class="chat-input-row">
<textarea id="chat-input" rows="1" placeholder="输入问题…(回车发送)"></textarea>
<button id="chat-send">➤</button>
</div>
</div>
</div>
<!-- Import Modal -->
<div class="modal-overlay" id="import-modal">
<div class="modal">
<h3>📱 导入微信联系人</h3>
<p id="import-modal-msg">正在从微信通讯录导入联系人,请稍候…</p>
<div class="progress-bar">
<div class="progress-fill" id="import-progress" style="width:0%"></div>
</div>
<div class="modal-status" id="import-status">准备中…</div>
<div style="margin-top:20px; text-align:right;">
<button class="btn" id="import-close" style="display:none;">关闭</button>
</div>
</div>
</div>
<!-- Toast container -->
<div id="toast-container"></div>
<script>
// ═══════════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════════
const API = 'http://localhost:3010';
let allContacts = [];
let filteredContacts = [];
let currentContact = null;
let currentEdges = [];
let activeTab = 'profile';
let chatSessionId = null;
let chatCollapsed = false;
let reportSseSource = null;
let activationSseSource = null;
let mapInstance = null;
let networkInstance = null;
// ═══════════════════════════════════════════════════════════════
// UTILS
// ═══════════════════════════════════════════════════════════════
function showToast(msg, type = 'info') {
const tc = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = `toast ${type}`;
el.textContent = msg;
tc.appendChild(el);
requestAnimationFrame(() => el.classList.add('show'));
setTimeout(() => {
el.classList.remove('show');
setTimeout(() => el.remove(), 300);
}, 3500);
}
async function apiFetch(url, opts = {}) {
try {
const res = await fetch(API + url, opts);
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(err.error || res.statusText);
}
return res.json();
} catch (e) {
showToast('API 错误: ' + e.message, 'error');
throw e;
}
}
function getStatusClass(status) {
if (status === 'complete') return 'complete';
if (status === 'partial') return 'partial';
return 'none';
}
function formatDate(ts) {
if (!ts) return '—';
const d = typeof ts === 'number' ? new Date(ts < 1e12 ? ts * 1000 : ts) : new Date(ts);
return d.toLocaleDateString('zh-CN', { year: 'numeric', month: 'short', day: 'numeric' });
}
function escapeHtml(s) {
if (!s) return '';
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
}
// ─── URL / Hash routing ───────────────────────────────────────
// 格式:#<tab>/<contactId> 例:#chat/per-e145855e
function setUrl(tab, contactId) {
const hash = contactId ? `#${tab}/${encodeURIComponent(contactId)}` : `#${tab}`;
history.replaceState(null, '', hash);
}
function parseUrl() {
const raw = location.hash.slice(1); // 去掉 #
if (!raw) return { tab: 'profile', contactId: null };
const slash = raw.indexOf('/');
if (slash === -1) return { tab: raw, contactId: null };
return {
tab: raw.slice(0, slash),
contactId: decodeURIComponent(raw.slice(slash + 1)),
};
}
function switchTab(name) {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
const tabEl = document.querySelector(`.tab[data-tab="${name}"]`);
if (tabEl) tabEl.classList.add('active');
const panelEl = document.getElementById('panel-' + name);
if (panelEl) panelEl.classList.add('active');
activeTab = name;
}
function getInitial(name) {
if (!name) return '?';
return name.charAt(0).toUpperCase();
}
function nodeData(node) {
// node.data may be a JSON string or an object
if (node._data) return node._data;
try { node._data = typeof node.data === 'string' ? JSON.parse(node.data) : (node.data || {}); }
catch(e) { node._data = {}; }
return node._data;
}
// ═══════════════════════════════════════════════════════════════
// CONTACT LIST — 瀑布流分页加载
// ═══════════════════════════════════════════════════════════════
const PAGE_SIZE = 100;
let contactTotal = 0; // 后端总数
let contactOffset = 0; // 当前已加载数
let contactLoading = false;
let searchMode = false; // 搜索模式时不瀑布流
let currentSort = 'name'; // 当前排序字段
let currentOrder = 'asc'; // 当前排序方向
// ─── Sort controls ───
document.getElementById('sort-select').addEventListener('change', (e) => {
currentSort = e.target.value;
loadContacts();
});
document.getElementById('sort-order-btn').addEventListener('click', () => {
currentOrder = currentOrder === 'asc' ? 'desc' : 'asc';
document.getElementById('sort-order-btn').textContent = currentOrder === 'asc' ? '↑ 升序' : '↓ 降序';
loadContacts();
});
async function loadContacts() {
contactOffset = 0;
allContacts = [];
searchMode = false;
document.getElementById('contact-list').innerHTML = '';
await loadMoreContacts();
}
async function loadMoreContacts() {
if (contactLoading) return;
contactLoading = true;
try {
const url = `/api/graph/nodes?type=Person&limit=${PAGE_SIZE}&offset=${contactOffset}&sort=${currentSort}&order=${currentOrder}`;
const res = await apiFetch(url);
const nodes = res.nodes || [];
contactTotal = res.total || 0;
contactOffset += nodes.length;
allContacts = allContacts.concat(nodes);
appendContactItems(nodes);
updateContactCount();
} catch(e) {
if (allContacts.length === 0) renderEmptyContacts('无法加载联系人列表');
} finally {
contactLoading = false;
}
}
/* 将联系人节点渲染成 HTML 字符串 */
function contactItemHTML(c) {
const name = c.name || '未命名';
const nickName = c.nickName || '';
const remark = c.remark || '';
const wechatId = c.wechatId || '';
const company = c.company || c.organization || '';
const role = c.role || '';
const alias = c.alias || '';
const status = c._analysisStatus || c.analysis_status || 'none';
const isActive = currentContact && currentContact.id === c.id;
// 副标题:优先显示 nickName(微信昵称),再 alias,再 wechatId
const subtitle = [nickName !== name ? nickName : '', company, role]
.filter(Boolean).join(' · ') || wechatId || alias || '';
return `<div class="contact-item ${isActive ? 'active' : ''}" data-id="${escapeHtml(c.id)}">
<span class="status-dot ${getStatusClass(status)}"></span>
<div class="contact-info">
<div class="contact-name">${escapeHtml(name)}</div>
<div class="contact-company">${escapeHtml(subtitle || '—')}</div>
</div>
</div>`;
}
function appendContactItems(nodes) {
const list = document.getElementById('contact-list');
// 移除已有的"加载更多"sentinel
const sentinel = list.querySelector('.load-sentinel');
if (sentinel) sentinel.remove();
if (nodes.length === 0 && allContacts.length === 0) {
renderEmptyContacts('暂无联系人,请先导入微信联系人');
return;
}
list.insertAdjacentHTML('beforeend', nodes.map(contactItemHTML).join(''));
list.querySelectorAll('.contact-item:not([data-bound])').forEach(el => {
el.dataset.bound = '1';
el.addEventListener('click', () => selectContact(el.dataset.id));
});
// 如还有更多,追加 sentinel 供 IntersectionObserver 触发
if (allContacts.length < contactTotal) {
list.insertAdjacentHTML('beforeend', `<div class="load-sentinel" style="height:1px;"></div>`);
observeSentinel();
}
}
function updateContactCount() {
const el = document.getElementById('contact-count');
el.textContent = searchMode
? `${filteredContacts.length} / ${contactTotal}`
: `${allContacts.length} / ${contactTotal}`;
}
function renderEmptyContacts(msg) {
document.getElementById('contact-list').innerHTML =
`<div style="padding:24px 14px;text-align:center;color:var(--muted);font-size:13px;">${msg}</div>`;
}
/* 重新渲染整个列表(搜索模式 / 切换联系人高亮用) */
function renderContactList() {
const list = document.getElementById('contact-list');
const contacts = searchMode ? filteredContacts : allContacts;
if (contacts.length === 0) {
list.innerHTML = `<div style="padding:24px 14px;text-align:center;color:var(--muted);font-size:13px;">没有匹配的联系人</div>`;
return;
}
list.innerHTML = contacts.map(contactItemHTML).join('');
list.querySelectorAll('.contact-item').forEach(el => {
el.addEventListener('click', () => selectContact(el.dataset.id));
});
if (!searchMode && allContacts.length < contactTotal) {
list.insertAdjacentHTML('beforeend', `<div class="load-sentinel" style="height:1px;"></div>`);
observeSentinel();
}
updateContactCount();
}
/* IntersectionObserver 触底加载 */
let _observer = null;
function observeSentinel() {
if (_observer) _observer.disconnect();
const sentinel = document.querySelector('#contact-list .load-sentinel');
if (!sentinel) return;
_observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && !searchMode) loadMoreContacts();
}, { root: document.getElementById('contact-list'), threshold: 0.1 });
_observer.observe(sentinel);
}
// ─── Search ───
let searchTimer = null;
document.getElementById('search-input').addEventListener('input', (e) => {
clearTimeout(searchTimer);
const q = e.target.value.trim();
if (!q) {
searchMode = false;
filteredContacts = [];
renderContactList();
return;
}
searchMode = true;
// 先本地过滤已加载的
const ql = q.toLowerCase();
filteredContacts = allContacts.filter(c => {
const fields = [c.name, c.nickName, c.remark, c.wechatId, c.company, c.role, c.alias, c.notes]
.filter(Boolean).join(' ').toLowerCase();
return fields.includes(ql);
});
renderContactList();
// 再后端搜索(覆盖全量)
searchTimer = setTimeout(async () => {
try {
const res = await apiFetch(`/api/graph/search?q=${encodeURIComponent(q)}&type=Person&limit=200`);
contactTotal = res.total || 0;
filteredContacts = res.results || [];
renderContactList();
} catch(e) { /* 保持本地搜索结果 */ }
}, 350);
});
// ═══════════════════════════════════════════════════════════════
// SELECT CONTACT
// ═══════════════════════════════════════════════════════════════
async function selectContact(id) {
try {
const res = await apiFetch(`/api/graph/nodes/${encodeURIComponent(id)}`);
currentContact = res.node;
const raw = res.edges || {};
currentEdges = Array.isArray(raw)
? raw
: [...(raw.outgoing || []), ...(raw.incoming || [])];
if (_chatState.username !== (currentContact.wechatId || '')) {
_chatState = { username: null, page: 1, query: '', total: 0, pages: 0, messages: null };
}
setUrl(activeTab, id);
renderContactList();
renderCurrentTab();
} catch(e) { /* toast shown by apiFetch */ }
}
// ═══════════════════════════════════════════════════════════════
// TABS
// ═══════════════════════════════════════════════════════════════
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
const name = tab.dataset.tab;
switchTab(name);
setUrl(name, currentContact?.id || null);
renderCurrentTab();
});
});
function renderCurrentTab() {
if (!currentContact) return;
switch (activeTab) {
case 'profile': renderProfile(); break;
case 'chat': renderChatTab(); break;
case 'graph': renderGraph(); break;
case 'timeline': renderTimeline(); break;
case 'insights': renderInsights(); break;
case 'report': renderReportPanel(); break;
}
}
// ═══════════════════════════════════════════════════════════════
// PROFILE VIEW
// ═══════════════════════════════════════════════════════════════
function renderProfile() {
const emptyEl = document.getElementById('empty-profile');
const content = document.getElementById('profile-content');
emptyEl.style.display = 'none';
content.style.display = 'block';
const c = currentContact;
const name = c.name || '未命名';
const nickName = c.nickName || '';
const remark = c.remark || '';
const wechatId = c.wechatId || '';
const alias = c.alias || '';
const notes = c.notes || '';
const company = c.company || c.organization || '';
const jobTitle = c.title || c.jobTitle || c.position || '';
const email = c.email || '';
const phone = c.phone || c.mobile || '';
const linkedin = c.linkedin || c.linkedinUrl || '';
const twitter = c.twitter || c.twitterUrl || c.x || '';
const status = c._analysisStatus || 'none';
const STATUS_LABEL = { complete: '已分析', partial: '分析中', none: '未激活' };
const STATUS_COLOR = { complete: 'var(--success)', partial: '#3b82f6', none: 'var(--muted)' };
// Only render a card when the value is non-empty
function card(label, value, opts = {}) {
if (!value) return '';
let disp = escapeHtml(value);
if (opts.email) disp = `<a href="mailto:${escapeHtml(value)}">${escapeHtml(value)}</a>`;
if (opts.url) disp = `<a href="${escapeHtml(value)}" target="_blank" rel="noopener">${escapeHtml(value)}</a>`;
const fw = opts.fullWidth ? 'grid-column:1/-1;' : '';
return `<div class="info-card" style="${fw}">
<div class="info-label">${label}</div>
<div class="info-value">${disp}</div>
</div>`;
}
// WeChat block — only fields that differ from the display name, plus IDs
const wechatCards = [
card('昵称', nickName !== name ? nickName : ''),
card('备注名', remark !== name ? remark : ''),
card('微信号', alias),
card('wxid', wechatId),
].filter(Boolean).join('');
// Professional block — only rendered when at least one field has data
const profCards = [
card('公司', company),
card('职位', jobTitle),
card('邮箱', email, { email: true }),
card('电话', phone),
card('LinkedIn', linkedin, { url: true }),
card('Twitter / X',twitter, { url: true }),
].filter(Boolean).join('');
// Non-chat edges for relationship section
const otherEdges = currentEdges.filter(e => e.relation !== 'PARTICIPATED');
// Avatar: use pinyin initial when available for a nicer letter
const initial = c.pinYinInitial ? c.pinYinInitial.charAt(0).toUpperCase() : getInitial(name);
// Subtitle under the name: prefer job+company, else nickName/alias
const subtitle = [jobTitle, company].filter(Boolean).join(' · ')
|| (nickName && nickName !== name ? nickName : '')
|| alias;
content.innerHTML = `
<div class="profile-header">
<div class="avatar-circle">${escapeHtml(initial)}</div>
<div class="profile-meta">
<div class="profile-name">${escapeHtml(name)}</div>
<div class="profile-sub">${escapeHtml(subtitle)}</div>
<div style="margin-top:8px;display:flex;align-items:center;gap:8px;">
<span class="status-dot ${getStatusClass(status)}" style="width:10px;height:10px;"></span>
<span style="font-size:12px;color:${STATUS_COLOR[status]||'var(--muted)'};">${STATUS_LABEL[status]||status}</span>
</div>
</div>
<div class="profile-actions">
<button class="btn btn-primary btn-sm" id="btn-activate">⚡ 激活档案</button>
</div>
</div>
${wechatCards ? `
<div class="section-title" style="margin-top:4px;">微信信息</div>
<div class="info-grid" style="margin-bottom:20px;">${wechatCards}</div>
` : ''}
${profCards ? `
<div class="section-title">职业信息</div>
<div class="info-grid" style="margin-bottom:20px;">${profCards}</div>
` : ''}
${notes ? `
<div class="info-card" style="margin-bottom:20px;">
<div class="info-label">备注</div>
<div class="info-value" style="white-space:pre-wrap;">${escapeHtml(notes)}</div>
</div>
` : ''}
${otherEdges.length > 0 ? `
<div class="divider"></div>
<div class="section-title">关联关系 (${otherEdges.length})</div>
<div class="edges-list">
${otherEdges.map(e => {
const otherId = e.from_id === c.id ? e.to_id : e.from_id;
const otherName = e.neighbor_name || otherId;
const dir = e.from_id === c.id ? '→' : '←';
return `<div class="edge-item" data-id="${escapeHtml(otherId)}">
<span class="edge-relation">${escapeHtml(e.relation)}</span>
<span style="color:var(--muted);">${dir}</span>
<span class="edge-name">${escapeHtml(otherName)}</span>
</div>`;
}).join('')}
</div>
` : ''}
`;
document.getElementById('btn-activate')?.addEventListener('click', () => activateContact(c));
content.querySelectorAll('.edge-item[data-id]').forEach(el => {
el.addEventListener('click', () => selectContact(el.dataset.id));
});
}
// ═══════════════════════════════════════════════════════════════
// CHAT TAB
// ═══════════════════════════════════════════════════════════════
let _chatState = { username: null, page: 1, query: '', total: 0, pages: 0, messages: null };
let _chatSearchTimer = null;
function renderChatTab() {
const emptyEl = document.getElementById('empty-chat');
const content = document.getElementById('chat-tab-content');
const c = currentContact;
const wechatId = c?.wechatId || '';
if (!c || !wechatId) {
emptyEl.style.display = 'flex';
content.style.display = 'none';
return;
}
emptyEl.style.display = 'none';
content.style.display = 'flex';
// Contact header
document.getElementById('chat-contact-header').innerHTML = `
<div style="display:flex;align-items:center;gap:10px;">
<div class="avatar-circle" style="width:36px;height:36px;font-size:14px;flex-shrink:0;">
${escapeHtml(c.pinYinInitial ? c.pinYinInitial.charAt(0).toUpperCase() : getInitial(c.name||'?'))}
</div>
<div>
<div style="font-weight:600;">${escapeHtml(c.name||'未命名')}</div>
<div style="font-size:12px;color:var(--muted);">${escapeHtml(c.alias||wechatId)}</div>
</div>
</div>
`;
// Auto-load or restore
if (_chatState.username === wechatId && _chatState.messages) {
renderChatPanel(_chatState);
} else {
loadChat(wechatId, 1, '');
}
}
async function loadChat(username, page, query) {
const viewer = document.getElementById('chat-viewer');
if (!viewer) return;
viewer.innerHTML = `<div style="padding:32px;text-align:center;color:var(--muted);font-size:13px;">
<div class="loading-spinner" style="width:24px;height:24px;margin:0 auto 10px;"></div>加载中…
</div>`;
try {
const params = new URLSearchParams({ page, pageSize: 200 });
if (query) params.set('q', query);
const res = await apiFetch(`/api/wechat/messages/${encodeURIComponent(username)}?${params}`);
_chatState = { username, page: res.page, query, total: res.total, pages: res.pages, messages: res.messages };
renderChatPanel(_chatState);
} catch(e) {
if (viewer) viewer.innerHTML = `<div style="padding:20px;color:var(--danger);font-size:13px;">加载失败</div>`;
}
}
function renderChatPanel(state) {
const viewer = document.getElementById('chat-viewer');
if (!viewer) return;
const { username, page, query, total, pages, messages } = state;
const start = (page - 1) * 200 + 1;
const end = Math.min(page * 200, total);
function highlight(text) {
if (!query) return escapeHtml(text);
const re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
return escapeHtml(text).replace(re, m => `<mark class="msg-highlight">${m}</mark>`);
}
// 页内消息从新到旧显示(reverse)
const displayed = [...messages].reverse();
const msgsHtml = displayed.length === 0
? `<div style="padding:40px 0;text-align:center;color:var(--muted);font-size:13px;">${query ? '未找到匹配消息' : '暂无文本消息'}</div>`
: displayed.map(m => {
const isSelf = m.isSelf;
const timeStr = m.createTime
? new Date(m.createTime * 1000).toLocaleString('zh-CN', { month:'numeric', day:'numeric', hour:'2-digit', minute:'2-digit' })
: '';
return `<div class="msg-item ${isSelf ? 'self' : 'other'}">
<div class="msg-col">
${(!isSelf && m.sender) ? `<div class="msg-sender">${escapeHtml(m.sender)}</div>` : ''}
<div class="msg-bubble">${highlight(m.content)}</div>
<div class="msg-meta">${timeStr}</div>
</div>
</div>`;
}).join('');
viewer.innerHTML = `
<div class="chat-toolbar">
<input class="chat-search-input" id="chat-search-input" placeholder="搜索消息…" value="${escapeHtml(query)}" />
<span class="chat-info">${total > 0 ? `第 ${start}–${end} 条 / 共 ${total} 条` : '0 条'}</span>
</div>
<div class="msg-list">${msgsHtml}</div>
<div class="chat-pagination">
<button class="page-btn" id="chat-prev" ${page <= 1 ? 'disabled' : ''}>‹ 上一页(更旧)</button>
<span class="page-label">第 ${page} / ${pages} 页</span>
<button class="page-btn" id="chat-next" ${page >= pages ? 'disabled' : ''}>下一页(更旧)›</button>
</div>
`;
document.getElementById('chat-search-input').addEventListener('input', function() {
clearTimeout(_chatSearchTimer);
_chatSearchTimer = setTimeout(() => loadChat(username, 1, this.value.trim()), 400);
});
document.getElementById('chat-prev')?.addEventListener('click', () => loadChat(username, page - 1, query));
document.getElementById('chat-next')?.addEventListener('click', () => loadChat(username, page + 1, query));
}
function activateContact(contact) {
const name = contact.name || nodeData(contact).name || '该联系人';
showToast(`正在激活 ${name} 的档案分析…`, 'info');
if (activationSseSource) { activationSseSource.close(); activationSseSource = null; }
const sessionId = 'activate-' + Date.now();
const message = encodeURIComponent(`请分析联系人 ${name} 的档案,整理其公司、职位、人脉关系,并给出关系维护建议。`);
activationSseSource = new EventSource(`${API}/api/master/chat?message=${message}&sessionId=${sessionId}`);
// Switch to report tab to show output
document.querySelector('.tab[data-tab="report"]').click();
const output = document.getElementById('report-output');
output.innerHTML = '';
output.classList.add('streaming-cursor');
activationSseSource.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === 'text' || data.type === 'content_block_delta') {
const text = data.text || data.delta?.text || '';
output.textContent += text;
output.scrollTop = output.scrollHeight;
} else if (data.type === 'done' || data.type === 'end') {
output.classList.remove('streaming-cursor');
activationSseSource.close(); activationSseSource = null;
showToast('档案激活完成', 'success');
} else if (data.type === 'error') {
output.classList.remove('streaming-cursor');
showToast('激活失败: ' + (data.error || '未知错误'), 'error');
activationSseSource.close(); activationSseSource = null;
}
} catch(err) {}
};
activationSseSource.onerror = () => {
output.classList.remove('streaming-cursor');
activationSseSource.close(); activationSseSource = null;
};
}
// ═══════════════════════════════════════════════════════════════
// GRAPH VIEW
// ═══════════════════════════════════════════════════════════════
function renderGraph() {
const emptyEl = document.getElementById('empty-graph');
const contentEl = document.getElementById('graph-content');
emptyEl.style.display = 'none';
contentEl.style.display = 'block';
if (networkInstance) { networkInstance.destroy(); networkInstance = null; }
const c = currentContact;
const d = nodeData(c);
const centerName = c.name || d.name || c.id;
const nodes = [{ id: c.id, label: centerName, color: { background: '#6366f1', border: '#4f46e5' }, font: { color: '#fff' }, size: 28 }];
const edges = [];
const addedIds = new Set([c.id]);
currentEdges.forEach(e => {
const otherId = e.from_id === c.id ? e.to_id : e.from_id;
if (!addedIds.has(otherId)) {
addedIds.add(otherId);
nodes.push({ id: otherId, label: otherId.length > 16 ? otherId.slice(0, 14) + '…' : otherId, color: { background: '#22222e', border: '#2a2a38' }, font: { color: '#e8e8f0' }, size: 18 });
}
edges.push({ from: e.from_id, to: e.to_id, label: e.relation, color: { color: '#6366f1' }, font: { color: '#8888a8', size: 10 } });
});
const container = document.getElementById('graph-container');
const data = { nodes: new vis.DataSet(nodes), edges: new vis.DataSet(edges) };
const options = {
layout: { improvedLayout: true },
physics: { stabilization: { iterations: 100 }, barnesHut: { gravitationalConstant: -8000 } },
interaction: { hover: true },
nodes: { shape: 'dot', borderWidth: 2, chosen: true },
edges: { arrows: { to: { enabled: true, scaleFactor: 0.6 } }, smooth: { type: 'dynamic' } },
background: { fill: 'transparent' }
};
networkInstance = new vis.Network(container, data, options);
networkInstance.on('click', (params) => {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
if (nodeId !== c.id) { selectContact(nodeId); }
}
});
}
// ═══════════════════════════════════════════════════════════════
// TIMELINE VIEW
// ═══════════════════════════════════════════════════════════════
let timelineFilter = 'all';
function renderTimeline() {
const emptyEl = document.getElementById('empty-timeline');
const contentEl = document.getElementById('timeline-content');
emptyEl.style.display = 'none';
contentEl.style.display = 'block';
// Gather event nodes from edges
const eventEdges = currentEdges.filter(e => {
const otherId = e.from_id === currentContact.id ? e.to_id : e.from_id;
return otherId.startsWith('eve-') || e.relation === 'PARTICIPATED' || e.relation === 'MENTIONED_IN';
});
const typeIcons = { chat: '💬', meeting: '📅', post: '📝', call: '📞', email: '✉️', default: '📌' };
const typeLabels = { chat: '微信消息', meeting: '会议', post: '动态', call: '电话', email: '邮件' };
// Build event list from edges (we may not have full data for related events)
const events = eventEdges.map(e => {
const otherId = e.from_id === currentContact.id ? e.to_id : e.from_id;
const edgeData = typeof e.data === 'string' ? JSON.parse(e.data || '{}') : (e.data || {});
return {
id: otherId,
type: edgeData.eventType || edgeData.type || 'default',
date: edgeData.date || edgeData.time || e.created_at,
summary: edgeData.summary || edgeData.content || otherId,
tags: edgeData.tags || [],
followUps: edgeData.followUps || [],
lat: edgeData.lat, lng: edgeData.lng,
};
}).sort((a, b) => (b.date || 0) - (a.date || 0));
const filterTypes = ['all', 'chat', 'meeting', 'post'];
const filtered = timelineFilter === 'all' ? events : events.filter(ev => ev.type === timelineFilter);
const mapPoints = events.filter(ev => ev.lat && ev.lng);
contentEl.innerHTML = `
<div class="timeline-filters">
${filterTypes.map(t => `<div class="filter-chip ${timelineFilter === t ? 'active' : ''}" data-type="${t}">${t === 'all' ? '全部' : (typeLabels[t] || t)}</div>`).join('')}
</div>
<div class="timeline">
${filtered.length === 0
? `<div style="color:var(--muted); font-size:13px; padding: 20px 0;">暂无互动记录</div>`
: filtered.map(ev => `
<div class="timeline-item">
<div class="tl-icon">${typeIcons[ev.type] || typeIcons.default}</div>
<div class="tl-content">
<div class="tl-date">${formatDate(ev.date)}</div>
<div class="tl-summary">${escapeHtml(ev.summary)}</div>
${ev.tags.length > 0 ? `<div class="tl-tags">${ev.tags.map(t => `<span class="tag">${escapeHtml(t)}</span>`).join('')}</div>` : ''}
</div>
</div>
`).join('')}
</div>
${mapPoints.length > 0 ? `<div class="section-title">地图轨迹</div><div id="map-container"></div>` : ''}
`;
// Filter chips
contentEl.querySelectorAll('.filter-chip').forEach(el => {
el.addEventListener('click', () => {
timelineFilter = el.dataset.type;
renderTimeline();
});
});
// Leaflet map
if (mapPoints.length > 0) {
if (mapInstance) { mapInstance.remove(); mapInstance = null; }
mapInstance = L.map('map-container').setView([mapPoints[0].lat, mapPoints[0].lng], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap' }).addTo(mapInstance);
mapPoints.forEach(ev => L.marker([ev.lat, ev.lng]).addTo(mapInstance).bindPopup(escapeHtml(ev.summary)));
}
}
// ═══════════════════════════════════════════════════════════════
// INSIGHTS VIEW
// ═══════════════════════════════════════════════════════════════
function renderInsights() {
const emptyEl = document.getElementById('empty-insights');
const contentEl = document.getElementById('insights-content');
emptyEl.style.display = 'none';
contentEl.style.display = 'block';
const c = currentContact;
const d = nodeData(c);
// Gather stats from edges
const eventEdges = currentEdges.filter(e => e.relation === 'PARTICIPATED' || e.relation === 'MENTIONED_IN');
const chatEvents = eventEdges.filter(e => {
const ed = typeof e.data === 'string' ? JSON.parse(e.data || '{}') : (e.data || {});
return ed.type === 'chat' || ed.eventType === 'chat';
});
const lastInteraction = currentEdges.reduce((max, e) => Math.max(max, e.created_at || 0), 0);
const msgCount = d.messageCount || chatEvents.length || 0;
const warmth = d.relationWarmth || d.warmth || (msgCount > 20 ? '热' : msgCount > 5 ? '温' : '冷');
const warmthColor = { '热': 'var(--success)', '温': 'var(--warning)', '冷': '#3b82f6' };
// Topic distribution from event tags
const topicMap = {};
currentEdges.forEach(e => {
const ed = typeof e.data === 'string' ? JSON.parse(e.data || '{}') : (e.data || {});
(ed.tags || []).forEach(t => { topicMap[t] = (topicMap[t] || 0) + 1; });
});
const topics = Object.entries(topicMap).sort((a,b) => b[1]-a[1]).slice(0, 6);
const maxTopic = topics.length > 0 ? topics[0][1] : 1;
// Follow-ups
const followUps = [];
currentEdges.forEach(e => {
const ed = typeof e.data === 'string' ? JSON.parse(e.data || '{}') : (e.data || {});
(ed.followUps || []).forEach(f => followUps.push(f));
});
contentEl.innerHTML = `
<div class="stats-row">
<div class="stat-card">
<div class="stat-num">${msgCount}</div>
<div class="stat-label">消息数</div>
</div>
<div class="stat-card">
<div class="stat-num" style="font-size:18px;">${lastInteraction ? formatDate(lastInteraction) : '—'}</div>
<div class="stat-label">最后互动</div>
</div>
<div class="stat-card">
<div class="stat-num" style="color:${warmthColor[warmth] || 'var(--accent)'};">${warmth}</div>
<div class="stat-label">关系温度</div>
</div>
</div>
<div class="section-title">话题分布</div>
<div class="bar-chart">
${topics.length === 0
? `<div style="color:var(--muted); font-size:13px;">暂无话题数据</div>`
: topics.map(([topic, count]) => `
<div class="bar-row">
<div class="bar-label">${escapeHtml(topic)}</div>
<div class="bar-track"><div class="bar-fill" style="width:${Math.round(count/maxTopic*100)}%"></div></div>
<div class="bar-count">${count}</div>
</div>
`).join('')}
</div>
<div class="divider"></div>
<div class="section-title">待跟进事项 (${followUps.length})</div>
<div class="followup-list">
${followUps.length === 0
? `<div style="color:var(--muted); font-size:13px;">暂无待跟进事项</div>`
: followUps.map(f => `
<div class="followup-item">
<span class="followup-check">⏰</span>
<span>${escapeHtml(typeof f === 'string' ? f : (f.text || JSON.stringify(f)))}</span>
</div>
`).join('')}
</div>
`;
}
// ═══════════════════════════════════════════════════════════════
// AI REPORT VIEW
// ═══════════════════════════════════════════════════════════════
function renderReportPanel() {
const emptyEl = document.getElementById('empty-report');
const contentEl = document.getElementById('report-content');
emptyEl.style.display = 'none';
contentEl.style.display = 'block';
}
document.getElementById('btn-gen-report').addEventListener('click', () => {
if (!currentContact) { showToast('请先选择联系人', 'info'); return; }
generateReport();
});
document.getElementById('btn-export-md').addEventListener('click', () => {
const text = document.getElementById('report-output').textContent;
if (!text || text.includes('点击「生成')) { showToast('请先生成报告', 'info'); return; }
const name = currentContact ? (currentContact.name || nodeData(currentContact).name || 'contact') : 'contact';
const blob = new Blob([text], { type: 'text/markdown' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${name}-report.md`;
a.click();
URL.revokeObjectURL(a.href);
});
function generateReport() {
const c = currentContact;
const name = c.name || nodeData(c).name || '该联系人';
const output = document.getElementById('report-output');
if (reportSseSource) { reportSseSource.close(); reportSseSource = null; }
output.textContent = '';
output.classList.add('streaming-cursor');
const sessionId = 'report-' + Date.now();
const message = `请为联系人 ${name} 生成一份完整的人脉分析报告,包括:基本信息、关系网络、互动历史、关系维护建议。`;
// Use SSE via POST
startChatSSE(message, sessionId, (text) => {
output.textContent += text;
output.scrollTop = output.scrollHeight;
}, () => {
output.classList.remove('streaming-cursor');
showToast('AI 报告生成完成', 'success');
}, (err) => {
output.classList.remove('streaming-cursor');
showToast('报告生成失败: ' + err, 'error');
});
}
// ═══════════════════════════════════════════════════════════════
// SSE CHAT HELPER
// ═══════════════════════════════════════════════════════════════
function startChatSSE(message, sessionId, onText, onDone, onError) {
// POST to /api/master/chat with SSE response
const ctrl = new AbortController();
fetch(`${API}/api/master/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
body: JSON.stringify({ message, sessionId, stream: true }),
signal: ctrl.signal,
}).then(async res => {
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
onError(err.error || res.statusText);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) { onDone(); break; }
buf += decoder.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop(); // keep incomplete line
for (const line of lines) {
if (line.startsWith('data: ')) {
const raw = line.slice(6).trim();
if (raw === '[DONE]') { onDone(); reader.cancel(); return; }
try {
const data = JSON.parse(raw);
const text = data.text || data.content || data.delta?.text || data.message || '';
if (text) onText(text);
if (data.type === 'done' || data.done) { onDone(); reader.cancel(); return; }
if (data.type === 'error') { onError(data.error || 'Stream error'); reader.cancel(); return; }
} catch(e) {
// plain text chunk
if (raw) onText(raw);
}
}
}
}
}).catch(e => {
if (e.name !== 'AbortError') onError(e.message);
});
return ctrl;
}
// ═══════════════════════════════════════════════════════════════
// AI CHAT WIDGET
// ═══════════════════════════════════════════════════════════════
document.getElementById('chat-header').addEventListener('click', () => {
chatCollapsed = !chatCollapsed;
document.getElementById('chat-body').classList.toggle('collapsed', chatCollapsed);
document.getElementById('chat-toggle').textContent = chatCollapsed ? '▲' : '▼';
});
document.getElementById('chat-send').addEventListener('click', sendChatMessage);
document.getElementById('chat-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChatMessage(); }
});
let chatSseCtrl = null;
function sendChatMessage() {
const input = document.getElementById('chat-input');
let text = input.value.trim();
if (!text) return;
// Prepend contact context if available
if (currentContact) {
const name = currentContact.name || nodeData(currentContact).name;
if (name && !text.includes(name)) {
text = `当前查看联系人:${name},${text}`;
}
}
input.value = '';
input.style.height = 'auto';
appendChatMsg('user', text);
if (!chatSessionId) chatSessionId = 'chat-' + Date.now();
const assistantEl = appendChatMsg('assistant', '', true);
assistantEl.classList.add('streaming');
if (chatSseCtrl) { chatSseCtrl.abort(); chatSseCtrl = null; }
chatSseCtrl = startChatSSE(text, chatSessionId, (chunk) => {
assistantEl.textContent += chunk;
document.getElementById('chat-messages').scrollTop = 9999;
}, () => {
assistantEl.classList.remove('streaming');
chatSseCtrl = null;
}, (err) => {
assistantEl.textContent = '错误:' + err;
assistantEl.classList.remove('streaming');
chatSseCtrl = null;
});
}
function appendChatMsg(role, text, streaming = false) {
const msgs = document.getElementById('chat-messages');
const el = document.createElement('div');
el.className = `chat-msg ${role}${streaming ? ' streaming-cursor' : ''}`;
el.textContent = text;
msgs.appendChild(el);
msgs.scrollTop = msgs.scrollHeight;
return el;
}
// Auto-resize textarea
document.getElementById('chat-input').addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 80) + 'px';
});
// ═══════════════════════════════════════════════════════════════
// IMPORT WECHAT
// ═══════════════════════════════════════════════════════════════
document.getElementById('btn-import-wechat').addEventListener('click', () => {
showImportModal();
});
async function showImportModal() {
const modal = document.getElementById('import-modal');
const progress = document.getElementById('import-progress');
const status = document.getElementById('import-status');
const closeBtn = document.getElementById('import-close');
const msgEl = document.getElementById('import-modal-msg');
modal.classList.add('show');
progress.style.width = '0%';
status.textContent = '准备中…';
closeBtn.style.display = 'none';
msgEl.textContent = '正在从微信通讯录导入联系人,请稍候…';
// Animate progress
let pct = 0;
const prog = setInterval(() => {
pct = Math.min(pct + Math.random() * 8, 85);
progress.style.width = pct + '%';
}, 300);
try {
status.textContent = '正在连接微信数据源…';
const res = await fetch(`${API}/api/wechat/import-contacts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ limit: 10000 }),
});
clearInterval(prog);
if (res.ok) {
const data = await res.json();
progress.style.width = '100%';
const count = data.imported || data.count || 0;
status.textContent = `导入完成!已导入 ${count} 位联系人。`;
msgEl.textContent = '微信联系人导入成功';
showToast(`成功导入 ${count} 位联系人`, 'success');
await loadContacts();
} else {
const err = await res.json().catch(() => ({ error: res.statusText }));
progress.style.width = '0%';
status.textContent = '导入失败:' + (err.error || '未知错误');
msgEl.textContent = '导入过程中出现错误';
showToast('导入失败: ' + (err.error || '未知错误'), 'error');
}
} catch(e) {
clearInterval(prog);
progress.style.width = '0%';
status.textContent = '连接失败:' + e.message;
msgEl.textContent = '无法连接到微信服务';
showToast('导入失败: ' + e.message, 'error');
}
closeBtn.style.display = 'inline-flex';
}
document.getElementById('import-close').addEventListener('click', () => {
document.getElementById('import-modal').classList.remove('show');
});
document.getElementById('import-modal').addEventListener('click', (e) => {
if (e.target === e.currentTarget) e.currentTarget.classList.remove('show');
});
// ═══════════════════════════════════════════════════════════════
// SETTINGS (stub)
// ═══════════════════════════════════════════════════════════════
document.getElementById('btn-settings').addEventListener('click', () => {
showToast('设置功能即将上线', 'info');
});
// ═══════════════════════════════════════════════════════════════
// INIT
// ═══════════════════════════════════════════════════════════════
// 浏览器前进/后退时响应 hash 变化
window.addEventListener('hashchange', () => {
const { tab, contactId } = parseUrl();
if (tab && tab !== activeTab) switchTab(tab);
if (contactId && contactId !== currentContact?.id) {
selectContact(contactId);
} else {
renderCurrentTab();
}
});
async function init() {
await loadContacts(); // 先加载联系人列表
const { tab, contactId } = parseUrl();
// 恢复 tab
if (tab && tab !== 'profile') switchTab(tab);
// 恢复联系人
if (contactId) {
await selectContact(contactId);
}
}
init();
</script>
</body>
</html>