File size: 34,571 Bytes
b7560a4
 
 
790de78
b7560a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d58052f
08a6186
d58052f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08a6186
d58052f
 
 
 
08a6186
 
 
 
 
 
 
d58052f
08a6186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d58052f
 
 
08a6186
d58052f
 
 
08a6186
d58052f
 
 
08a6186
d58052f
 
 
08a6186
d58052f
 
 
08a6186
d58052f
 
08a6186
 
 
 
 
 
b7560a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d58052f
b7560a4
 
d58052f
b7560a4
08a6186
 
 
d58052f
 
b7560a4
a2a8341
d58052f
08a6186
d58052f
 
 
 
 
 
08a6186
d58052f
 
 
 
 
 
 
 
a2a8341
 
d58052f
08a6186
d58052f
 
 
 
 
 
08a6186
 
d58052f
 
 
 
 
 
 
 
70ebf00
 
d58052f
70ebf00
08a6186
 
d58052f
 
 
 
08a6186
d58052f
 
 
08a6186
d58052f
 
 
 
 
 
 
b7560a4
a2a8341
d58052f
b7560a4
 
 
d58052f
 
 
 
 
 
 
 
 
 
b7560a4
 
08a6186
d58052f
 
 
 
 
 
 
08a6186
 
d58052f
 
 
08a6186
 
d58052f
 
 
 
 
 
 
 
 
 
 
08a6186
 
d58052f
 
 
 
 
08a6186
b7560a4
08a6186
d58052f
08a6186
 
 
 
 
d58052f
 
 
 
 
 
 
 
 
 
08a6186
b7560a4
d58052f
08a6186
 
b7560a4
70ebf00
 
d58052f
 
08a6186
d58052f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08a6186
 
d58052f
 
 
 
 
 
 
08a6186
 
d58052f
 
 
 
 
08a6186
 
d58052f
 
08a6186
 
70ebf00
d58052f
 
 
 
 
 
70ebf00
d58052f
 
 
 
 
 
70ebf00
d58052f
 
 
 
 
 
 
 
 
70ebf00
d58052f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70ebf00
b7560a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d621ef
b7560a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08a9a1b
 
b7560a4
 
 
 
08a9a1b
 
 
b7560a4
 
 
08a9a1b
 
b7560a4
 
08a9a1b
b7560a4
 
 
08a9a1b
 
b7560a4
 
 
08a9a1b
b7560a4
 
 
 
 
08a9a1b
 
 
 
 
 
 
 
 
 
b7560a4
 
 
 
08a9a1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7560a4
 
 
 
 
 
 
 
 
 
 
08a9a1b
790de78
 
08a9a1b
 
 
 
 
 
b7560a4
 
08a9a1b
b7560a4
 
08a9a1b
b7560a4
 
 
 
790de78
 
 
e1a892e
 
790de78
 
 
 
 
e1a892e
 
790de78
 
 
 
e1a892e
790de78
 
 
 
 
e1a892e
790de78
 
 
 
 
 
 
e1a892e
790de78
 
 
e1a892e
790de78
 
 
 
 
e1a892e
790de78
 
 
 
e1a892e
790de78
 
e1a892e
790de78
 
 
 
e1a892e
790de78
 
 
 
e1a892e
790de78
 
 
e1a892e
790de78
 
 
e1a892e
790de78
 
 
e1a892e
 
790de78
 
e1a892e
790de78
 
 
e1a892e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790de78
 
 
b7560a4
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
import express from 'express';
import githubService from '../services/githubService.js';
import memoryStorageService from '../services/memoryStorageService.js';
import screenshotService from '../services/screenshotService.js';

const router = express.Router();

// 选择存储服务
const getStorageService = () => {
  // 如果GitHub Token未配置,使用内存存储
  if (!process.env.GITHUB_TOKEN) {
    return memoryStorageService;
  }
  return githubService;
};

// 生成HTML页面来显示PPT幻灯片
const generateSlideHTML = (pptData, slideIndex, title) => {
  const slide = pptData.slides[slideIndex];
  const theme = pptData.theme || {};
  
  // 精确计算PPT内容的真实尺寸 - 优先使用预设尺寸,然后基于元素计算
  const calculatePptDimensions = (slide) => {
    // 1. 优先使用PPT数据中的预设尺寸
    if (pptData.slideSize && pptData.slideSize.width && pptData.slideSize.height) {
      const result = {
        width: Math.ceil(pptData.slideSize.width),
        height: Math.ceil(pptData.slideSize.height)
      };
      console.log(`使用PPT预设尺寸: ${result.width}x${result.height}`);
      return result;
    }
    
    // 2. 使用slide级别的尺寸设置
    if (slide.width && slide.height) {
      const result = {
        width: Math.ceil(slide.width),
        height: Math.ceil(slide.height)
      };
      console.log(`使用slide尺寸: ${result.width}x${result.height}`);
      return result;
    }
    
    // 3. 根据元素分布计算合适的尺寸
    if (!slide.elements || slide.elements.length === 0) {
      // 如果没有元素,使用标准PPT尺寸
      const result = { width: 960, height: 720 }; // 4:3标准比例
      console.log(`使用默认尺寸: ${result.width}x${result.height}`);
      return result;
    }
    
    let maxRight = 0;
    let maxBottom = 0;
    let minLeft = Infinity;
    let minTop = Infinity;
    
    // 计算所有元素的实际边界
    slide.elements.forEach(element => {
      const left = element.left || 0;
      const top = element.top || 0;
      const width = element.width || 0;
      const height = element.height || 0;
      
      const elementRight = left + width;
      const elementBottom = top + height;
      
      maxRight = Math.max(maxRight, elementRight);
      maxBottom = Math.max(maxBottom, elementBottom);
      minLeft = Math.min(minLeft, left);
      minTop = Math.min(minTop, top);
    });
    
    // 重置无限值
    if (minLeft === Infinity) minLeft = 0;
    if (minTop === Infinity) minTop = 0;
    
    // 计算内容区域的实际尺寸
    const contentWidth = maxRight - minLeft;
    const contentHeight = maxBottom - minTop;
    
    // 添加适当的边距,确保内容不被裁切
    const paddingX = Math.max(40, Math.abs(minLeft));
    const paddingY = Math.max(40, Math.abs(minTop));
    
    // 计算最终的PPT尺寸
    let finalWidth = Math.max(contentWidth + paddingX * 2, 800);
    let finalHeight = Math.max(contentHeight + paddingY * 2, 600);
    
    // 确保尺寸为偶数(避免半像素问题)
    finalWidth = Math.ceil(finalWidth / 2) * 2;
    finalHeight = Math.ceil(finalHeight / 2) * 2;
    
    const result = { width: finalWidth, height: finalHeight };
    console.log(`根据元素计算尺寸: ${result.width}x${result.height}`);
    
    return result;
  };
  
  const pptDimensions = calculatePptDimensions(slide);
  
  // 渲染幻灯片元素
  const renderElements = (elements) => {
    if (!elements || elements.length === 0) return '';
    
    return elements.map(element => {
      const style = `

        position: absolute;

        left: ${element.left}px;

        top: ${element.top}px;

        width: ${element.width}px;

        height: ${element.height}px;

        transform: rotate(${element.rotate || 0}deg);

        z-index: ${element.zIndex || 1};

      `;
      
      switch (element.type) {
        case 'text':
          return `

            <div style="${style} 

              font-size: ${element.fontSize || 14}px;

              font-family: ${element.fontName || 'Arial'};

              color: ${element.defaultColor || '#000'};

              font-weight: ${element.bold ? 'bold' : 'normal'};

              font-style: ${element.italic ? 'italic' : 'normal'};

              text-decoration: ${element.underline ? 'underline' : 'none'};

              text-align: ${element.align || 'left'};

              line-height: ${element.lineHeight || 1.2};

              padding: 10px;

              word-wrap: break-word;

              overflow: hidden;

            ">

              ${element.content || ''}

            </div>

          `;
        case 'image':
          return `

            <div style="${style}">

              <img src="${element.src}" alt="" style="width: 100%; height: 100%; object-fit: ${element.objectFit || 'contain'};" />

            </div>

          `;
        case 'shape':
          const shapeStyle = element.fill ? `background-color: ${element.fill};` : '';
          const borderStyle = element.outline ? `border: ${element.outline.width || 1}px ${element.outline.style || 'solid'} ${element.outline.color || '#000'};` : '';
          return `

            <div style="${style} ${shapeStyle} ${borderStyle}"></div>

          `;
        default:
          return `<div style="${style}"></div>`;
      }
    }).join('');
  };

  return `

    <!DOCTYPE html>

    <html lang="zh-CN">

    <head>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=${pptDimensions.width}, height=${pptDimensions.height}, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover">

        <title>${title} - 第${slideIndex + 1}页</title>

        <style>

            /* 全局重置 - 完全消除所有边距和填充 */

            * {

                margin: 0 !important;

                padding: 0 !important;

                box-sizing: border-box !important;

                border: none !important;

                outline: none !important;

            }

            

            /* HTML根元素 - 严格设置为PPT精确尺寸 */

            html {

                width: ${pptDimensions.width}px !important;

                height: ${pptDimensions.height}px !important;

                min-width: ${pptDimensions.width}px !important;

                min-height: ${pptDimensions.height}px !important;

                max-width: ${pptDimensions.width}px !important;

                max-height: ${pptDimensions.height}px !important;

                overflow: hidden !important;

                background: ${slide.background?.color || theme.backgroundColor || '#ffffff'} !important;

                position: fixed !important;

                top: 0 !important;

                left: 0 !important;

                margin: 0 !important;

                padding: 0 !important;

                border: none !important;

                outline: none !important;

            }

            

            /* Body元素 - 严格设置为PPT精确尺寸 */

            body {

                width: ${pptDimensions.width}px !important;

                height: ${pptDimensions.height}px !important;

                min-width: ${pptDimensions.width}px !important;

                min-height: ${pptDimensions.height}px !important;

                max-width: ${pptDimensions.width}px !important;

                max-height: ${pptDimensions.height}px !important;

                overflow: hidden !important;

                font-family: 'Microsoft YaHei', Arial, sans-serif !important;

                background: ${slide.background?.color || theme.backgroundColor || '#ffffff'} !important;

                position: fixed !important;

                top: 0 !important;

                left: 0 !important;

                margin: 0 !important;

                padding: 0 !important;

                border: none !important;

                outline: none !important;

            }

            

            /* PPT容器 - 严格设置为PPT精确尺寸,完全填充 */

            .slide-container {

                width: ${pptDimensions.width}px !important;

                height: ${pptDimensions.height}px !important;

                min-width: ${pptDimensions.width}px !important;

                min-height: ${pptDimensions.height}px !important;

                max-width: ${pptDimensions.width}px !important;

                max-height: ${pptDimensions.height}px !important;

                background-color: ${slide.background?.color || theme.backgroundColor || '#ffffff'} !important;

                position: fixed !important;

                top: 0 !important;

                left: 0 !important;

                overflow: hidden !important;

                transform: none !important;

                transform-origin: top left !important;

                margin: 0 !important;

                padding: 0 !important;

                border: none !important;

                outline: none !important;

                z-index: 1 !important;

            }

            

            /* 背景图片处理 */

            ${slide.background?.type === 'image' ? `

            .slide-container::before {

                content: '';

                position: absolute !important;

                top: 0 !important;

                left: 0 !important;

                width: ${pptDimensions.width}px !important;

                height: ${pptDimensions.height}px !important;

                background-image: url('${slide.background.image}') !important;

                background-size: ${slide.background.imageSize || 'cover'} !important;

                background-position: center !important;

                background-repeat: no-repeat !important;

                z-index: 0 !important;

            }

            ` : ''}

            

            /* 隐藏所有滚动条 */

            html::-webkit-scrollbar,

            body::-webkit-scrollbar,

            *::-webkit-scrollbar {

                display: none !important;

                width: 0 !important;

                height: 0 !important;

            }

            

            /* Firefox滚动条隐藏 */

            html {

                scrollbar-width: none !important;

            }

            

            /* 禁用文本选择和拖拽 */

            * {

                -webkit-user-select: none !important;

                -moz-user-select: none !important;

                -ms-user-select: none !important;

                user-select: none !important;

                -webkit-user-drag: none !important;

                -khtml-user-drag: none !important;

                -moz-user-drag: none !important;

                -o-user-drag: none !important;

                user-drag: none !important;

            }

            

            /* 禁用所有可能的缩放和调整 */

            body {

                zoom: 1 !important;

                -webkit-text-size-adjust: 100% !important;

                -ms-text-size-adjust: 100% !important;

            }

        </style>

        <script>

            // PPT尺寸信息 - 用于截图服务和JavaScript处理

            window.PPT_DIMENSIONS = {

                width: ${pptDimensions.width},

                height: ${pptDimensions.height}

            };

            

            // 强制设置viewport尺寸

            const viewportMeta = document.querySelector('meta[name="viewport"]');

            if (viewportMeta) {

                viewportMeta.setAttribute('content', \`width=\${window.PPT_DIMENSIONS.width}, height=\${window.PPT_DIMENSIONS.height}, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover\`);

            }

            

            console.log('PPT页面初始化 - 固定尺寸模式:', {

                dimensions: window.PPT_DIMENSIONS,

                userAgent: navigator.userAgent

            });

        </script>

    </head>

    <body>

        <div class="slide-container" id="slideContainer">

            ${renderElements(slide.elements)}

        </div>

        

        <script>

            // 页面加载完成后的初始化 - 确保完全精确的尺寸

            window.addEventListener('load', function() {

                const container = document.getElementById('slideContainer');

                const html = document.documentElement;

                const body = document.body;

                

                // 强制设置精确尺寸

                const exactWidth = ${pptDimensions.width};

                const exactHeight = ${pptDimensions.height};

                const backgroundColor = '${slide.background?.color || theme.backgroundColor || '#ffffff'}';

                

                console.log('强制设置页面精确尺寸:', exactWidth + 'x' + exactHeight);

                

                // 应用固定尺寸样式 - 完全消除白边

                const applyExactSize = (element, width, height) => {

                    if (!element) return;

                    

                    element.style.cssText = \`

                        width: \${width}px !important;

                        height: \${height}px !important;

                        min-width: \${width}px !important;

                        min-height: \${height}px !important;

                        max-width: \${width}px !important;

                        max-height: \${height}px !important;

                        overflow: hidden !important;

                        margin: 0 !important;

                        padding: 0 !important;

                        border: none !important;

                        outline: none !important;

                        position: fixed !important;

                        top: 0 !important;

                        left: 0 !important;

                        transform: none !important;

                        transform-origin: top left !important;

                        background: \${backgroundColor} !important;

                        box-sizing: border-box !important;

                    \`;

                };

                

                // 设置HTML和Body元素

                applyExactSize(html, exactWidth, exactHeight);

                applyExactSize(body, exactWidth, exactHeight);

                

                // 设置容器元素

                if (container) {

                    container.style.cssText = \`

                        width: \${exactWidth}px !important;

                        height: \${exactHeight}px !important;

                        min-width: \${exactWidth}px !important;

                        min-height: \${exactHeight}px !important;

                        max-width: \${exactWidth}px !important;

                        max-height: \${exactHeight}px !important;

                        position: fixed !important;

                        top: 0 !important;

                        left: 0 !important;

                        overflow: hidden !important;

                        margin: 0 !important;

                        padding: 0 !important;

                        border: none !important;

                        outline: none !important;

                        transform: none !important;

                        box-shadow: none !important;

                        z-index: 1 !important;

                        background-color: \${backgroundColor} !important;

                    \`;

                }

                

                // 禁用所有可能的缩放和调整

                document.addEventListener('wheel', function(e) {

                    if (e.ctrlKey) {

                        e.preventDefault();

                    }

                }, { passive: false });

                

                // 禁用触摸缩放

                document.addEventListener('touchstart', function(e) {

                    if (e.touches.length > 1) {

                        e.preventDefault();

                    }

                }, { passive: false });

                

                // 禁用双击缩放

                let lastTouchEnd = 0;

                document.addEventListener('touchend', function(e) {

                    const now = new Date().getTime();

                    if (now - lastTouchEnd <= 300) {

                        e.preventDefault();

                    }

                    lastTouchEnd = now;

                }, false);

                

                // 禁用右键菜单

                document.addEventListener('contextmenu', function(e) {

                    e.preventDefault();

                }, false);

                

                // 禁用F11全屏

                document.addEventListener('keydown', function(e) {

                    if (e.key === 'F11') {

                        e.preventDefault();

                    }

                }, false);

                

                console.log('固定尺寸模式样式应用完成,精确尺寸:', exactWidth + 'x' + exactHeight);

                

                // 最终验证尺寸 - 确保网页分辨率与PPT分辨率完全一致

                setTimeout(() => {

                    const actualDimensions = {

                        html: {

                            width: html.offsetWidth,

                            height: html.offsetHeight,

                            clientWidth: html.clientWidth,

                            clientHeight: html.clientHeight

                        },

                        body: {

                            width: body.offsetWidth,

                            height: body.offsetHeight,

                            clientWidth: body.clientWidth,

                            clientHeight: body.clientHeight

                        },

                        container: {

                            width: container ? container.offsetWidth : 0,

                            height: container ? container.offsetHeight : 0,

                            clientWidth: container ? container.clientWidth : 0,

                            clientHeight: container ? container.clientHeight : 0

                        },

                        viewport: {

                            width: window.innerWidth,

                            height: window.innerHeight

                        }

                    };

                    

                    console.log('最终页面尺寸验证:', actualDimensions);

                    console.log('PPT目标尺寸:', window.PPT_DIMENSIONS);

                    

                    // 检查是否存在尺寸不一致的情况

                    const htmlSizeMatch = actualDimensions.html.width === window.PPT_DIMENSIONS.width && 

                                         actualDimensions.html.height === window.PPT_DIMENSIONS.height;

                    const bodySizeMatch = actualDimensions.body.width === window.PPT_DIMENSIONS.width && 

                                         actualDimensions.body.height === window.PPT_DIMENSIONS.height;

                    const containerSizeMatch = container ? 

                        (actualDimensions.container.width === window.PPT_DIMENSIONS.width && 

                         actualDimensions.container.height === window.PPT_DIMENSIONS.height) : true;

                    

                    if (!htmlSizeMatch || !bodySizeMatch || !containerSizeMatch) {

                        console.warn('检测到尺寸不一致,可能出现白边问题');

                        console.warn('HTML尺寸匹配:', htmlSizeMatch);

                        console.warn('Body尺寸匹配:', bodySizeMatch);

                        console.warn('容器尺寸匹配:', containerSizeMatch);

                        

                        // 尝试强制修正

                        if (!htmlSizeMatch) {

                            html.style.width = window.PPT_DIMENSIONS.width + 'px';

                            html.style.height = window.PPT_DIMENSIONS.height + 'px';

                        }

                        if (!bodySizeMatch) {

                            body.style.width = window.PPT_DIMENSIONS.width + 'px';

                            body.style.height = window.PPT_DIMENSIONS.height + 'px';

                        }

                        if (container && !containerSizeMatch) {

                            container.style.width = window.PPT_DIMENSIONS.width + 'px';

                            container.style.height = window.PPT_DIMENSIONS.height + 'px';

                        }

                        

                        console.log('已尝试强制修正尺寸不一致问题');

                    } else {

                        console.log('✅ 页面尺寸验证通过,网页分辨率与PPT分辨率完全一致,无白边');

                    }

                }, 100);

            });

        </script>

    </body>

    </html>

  `;
};

// 公开访问PPT页面 - 返回HTML页面
router.get('/view/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const querySlideIndex = req.query.slide ? parseInt(req.query.slide) : parseInt(slideIndex);
    const fileName = `${pptId}.json`;
    const storageService = getStorageService();

    let pptData = null;
    
    // 如果是GitHub服务,尝试所有仓库
    if (storageService === githubService && storageService.repositories) {
      for (let i = 0; i < storageService.repositories.length; i++) {
        try {
          const result = await storageService.getFile(userId, fileName, i);
          if (result) {
            pptData = result.content;
            break;
          }
        } catch (error) {
          continue;
        }
      }
    } else {
      // 内存存储服务
      const result = await storageService.getFile(userId, fileName);
      if (result) {
        pptData = result.content;
      }
    }

    if (!pptData) {
      return res.status(404).send(`

        <!DOCTYPE html>

        <html lang="zh-CN">

        <head>

            <meta charset="UTF-8">

            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <title>PPT未找到</title>

            <style>

                body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }

                .error { color: #e74c3c; font-size: 18px; }

            </style>

        </head>

        <body>

            <div class="error">

                <h2>PPT未找到</h2>

                <p>请检查链接是否正确</p>

            </div>

        </body>

        </html>

      `);
    }

    const slideIdx = querySlideIndex;
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).send(`

        <!DOCTYPE html>

        <html lang="zh-CN">

        <head>

            <meta charset="UTF-8">

            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <title>幻灯片未找到</title>

            <style>

                body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }

                .error { color: #e74c3c; font-size: 18px; }

            </style>

        </head>

        <body>

            <div class="error">

                <h2>幻灯片未找到</h2>

                <p>请检查幻灯片索引是否正确</p>

            </div>

        </body>

        </html>

      `);
    }

    // 返回HTML页面
    const htmlContent = generateSlideHTML(pptData, slideIdx, pptData.title);
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.send(htmlContent);
  } catch (error) {
    next(error);
  }
});

// API接口:获取PPT数据和指定幻灯片(JSON格式)
router.get('/api-view/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const fileName = `${pptId}.json`;
    const storageService = getStorageService();

    let pptData = null;
    
    // 如果是GitHub服务,尝试所有仓库
    if (storageService === githubService && storageService.repositories) {
      for (let i = 0; i < storageService.repositories.length; i++) {
        try {
          const result = await storageService.getFile(userId, fileName, i);
          if (result) {
            pptData = result.content;
            break;
          }
        } catch (error) {
          continue;
        }
      }
    } else {
      // 内存存储服务
      const result = await storageService.getFile(userId, fileName);
      if (result) {
        pptData = result.content;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    const slideIdx = parseInt(slideIndex);
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).json({ error: 'Slide not found' });
    }

    // 返回PPT数据和指定幻灯片
    res.json({
      id: pptData.id,
      title: pptData.title,
      theme: pptData.theme,
      currentSlide: pptData.slides[slideIdx],
      slideIndex: slideIdx,
      totalSlides: pptData.slides.length,
      isPublicView: true
    });
  } catch (error) {
    next(error);
  }
});

// 获取完整PPT数据(只读模式)
router.get('/ppt/:userId/:pptId', async (req, res, next) => {
  try {
    const { userId, pptId } = req.params;
    const fileName = `${pptId}.json`;
    const storageService = getStorageService();

    let pptData = null;
    
    // 如果是GitHub服务,尝试所有仓库
    if (storageService === githubService && storageService.repositories) {
      for (let i = 0; i < storageService.repositories.length; i++) {
        try {
          const result = await storageService.getFile(userId, fileName, i);
          if (result) {
            pptData = result.content;
            break;
          }
        } catch (error) {
          continue;
        }
      }
    } else {
      // 内存存储服务
      const result = await storageService.getFile(userId, fileName);
      if (result) {
        pptData = result.content;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // 返回只读版本的PPT数据
    res.json({
      ...pptData,
      isPublicView: true,
      readOnly: true
    });
  } catch (error) {
    next(error);
  }
});

// 生成PPT分享链接
router.post('/generate-share-link', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.body;

    if (!userId || !pptId) {
      return res.status(400).json({ error: 'User ID and PPT ID are required' });
    }

    console.log(`Generating share link for PPT: ${pptId}, User: ${userId}`);

    // 验证PPT是否存在
    const fileName = `${pptId}.json`;
    const storageService = getStorageService();
    let pptExists = false;
    let pptData = null;
    
    console.log(`Using storage service: ${storageService === githubService ? 'GitHub' : 'Memory'}`);
    
    // 如果是GitHub服务,尝试所有仓库
    if (storageService === githubService && storageService.repositories) {
      console.log(`Checking ${storageService.repositories.length} GitHub repositories...`);
      
      for (let i = 0; i < storageService.repositories.length; i++) {
        try {
          console.log(`Checking repository ${i}: ${storageService.repositories[i]}`);
          const result = await storageService.getFile(userId, fileName, i);
          if (result) {
            pptExists = true;
            pptData = result.content;
            console.log(`PPT found in repository ${i}`);
            break;
          }
        } catch (error) {
          console.log(`PPT not found in repository ${i}: ${error.message}`);
          continue;
        }
      }
    } else {
      // 内存存储服务
      console.log('Checking memory storage...');
      try {
        const result = await storageService.getFile(userId, fileName);
        if (result) {
          pptExists = true;
          pptData = result.content;
          console.log('PPT found in memory storage');
        }
      } catch (error) {
        console.log(`PPT not found in memory storage: ${error.message}`);
      }
    }

    if (!pptExists) {
      console.log('PPT not found in any storage location');
      
      // 额外尝试:如果GitHub失败,检查memory storage作为fallback
      if (storageService === githubService) {
        console.log('GitHub lookup failed, trying memory storage fallback...');
        try {
          const memoryResult = await memoryStorageService.getFile(userId, fileName);
          if (memoryResult) {
            pptExists = true;
            pptData = memoryResult.content;
            console.log('PPT found in memory storage fallback');
          }
        } catch (memoryError) {
          console.log(`Memory storage fallback also failed: ${memoryError.message}`);
        }
      }
    }

    if (!pptExists) {
      return res.status(404).json({ 
        error: 'PPT not found',
        details: `PPT ${pptId} not found for user ${userId}`,
        searchedLocations: storageService === githubService ? 'GitHub repositories and memory storage' : 'Memory storage only'
      });
    }

    const baseUrl = process.env.PUBLIC_URL || req.get('host');
    const protocol = process.env.NODE_ENV === 'production' ? 'https' : req.protocol;
    
    const shareLinks = {
      // 单页分享链接
      slideUrl: `${protocol}://${baseUrl}/api/public/view/${userId}/${pptId}/${slideIndex}`,
      // 完整PPT分享链接
      pptUrl: `${protocol}://${baseUrl}/api/public/ppt/${userId}/${pptId}`,
      // 前端查看链接
      viewUrl: `${protocol}://${baseUrl}/public/${userId}/${pptId}/${slideIndex}`,
      // 新增:截图链接
      screenshotUrl: `${protocol}://${baseUrl}/api/public/screenshot/${userId}/${pptId}/${slideIndex}`,
      // 添加PPT信息
      pptInfo: {
        id: pptId,
        title: pptData?.title || 'Unknown Title',
        slideCount: pptData?.slides?.length || 0
      }
    };

    console.log('Share links generated successfully:', shareLinks);
    res.json(shareLinks);
  } catch (error) {
    console.error('Share link generation error:', error);
    next(error);
  }
});

// 截图功能 - 返回JPEG图片
router.get('/screenshot/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    console.log('Screenshot request received:', req.params);
    
    const { userId, pptId, slideIndex = 0 } = req.params;
    const slideIdx = parseInt(slideIndex);
    const fileName = `${pptId}.json`;
    const storageService = getStorageService();

    console.log(`Generating screenshot for: ${userId}/${pptId}/${slideIdx}`);

    let pptData = null;
    
    // 获取PPT数据(复用现有逻辑)
    if (storageService === githubService && storageService.repositories) {
      console.log('Checking GitHub repositories...');
      for (let i = 0; i < storageService.repositories.length; i++) {
        try {
          const result = await storageService.getFile(userId, fileName, i);
          if (result) {
            pptData = result.content;
            console.log(`PPT data found in repository ${i}`);
            break;
          }
        } catch (error) {
          continue;
        }
      }
    } else {
      console.log('Checking memory storage...');
      const result = await storageService.getFile(userId, fileName);
      if (result) {
        pptData = result.content;
        console.log('PPT data found in memory storage');
      }
    }

    // 如果GitHub失败,尝试内存存储fallback
    if (!pptData && storageService === githubService) {
      console.log('Trying memory storage fallback...');
      try {
        const memoryResult = await memoryStorageService.getFile(userId, fileName);
        if (memoryResult) {
          pptData = memoryResult.content;
          console.log('PPT data found in memory storage fallback');
        }
      } catch (memoryError) {
        console.log('Memory storage fallback failed:', memoryError.message);
      }
    }

    if (!pptData) {
      console.log('PPT not found');
      return res.status(404).json({ error: 'PPT not found' });
    }

    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      console.log('Slide index out of bounds');
      return res.status(404).json({ error: 'Slide not found' });
    }

    console.log('Generating HTML content...');
    // 生成HTML内容(复用现有函数)
    const htmlContent = generateSlideHTML(pptData, slideIdx, pptData.title);
    
    console.log('Calling screenshot service...');
    // 生成截图
    const screenshot = await screenshotService.generateScreenshot(htmlContent);
    
    console.log('Screenshot generated, sending response...');
    
    // 返回图片
    res.setHeader('Content-Type', 'image/jpeg');
    res.setHeader('Cache-Control', 'public, max-age=60'); // 1分钟缓存,减少服务器压力
    res.setHeader('Content-Disposition', `inline; filename="${pptData.title}-${slideIdx + 1}.jpg"`);
    res.send(screenshot);
  } catch (error) {
    console.error('Screenshot route error:', error);
    console.error('Stack trace:', error.stack);
    
    // 返回一个简单的错误响应而不是抛出异常
    try {
      res.status(500).setHeader('Content-Type', 'application/json');
      res.json({ 
        error: 'Screenshot generation failed', 
        message: error.message,
        details: process.env.NODE_ENV === 'development' ? error.stack : undefined
      });
    } catch (responseError) {
      console.error('Error sending error response:', responseError);
      // 如果连错误响应都发送失败,调用next
      next(error);
    }
  }
});

export default router;