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
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
/**
 * 简化的 Viser 管理器
 * 使用全局覆盖策略:iframe在全局容器中,通过absolute定位匹配目标容器
 */

class ViserManagerSimple {
    constructor() {
        this.viserPort = null;
        this.sharedIframe = null;
        this.currentPlugin = null;
        this.isLoaded = false;
        this.plugins = new Map();
        this.globalContainer = null;
        this.currentViewport = null;
        this.resizeObserver = null;
        this.currentResizeTarget = null;
        
        console.log('🔧 ViserManager 初始化完成 - 全局覆盖策略 (absolute定位)');
    }

    detectBackendPort() {
        if (this.viserPort) {
            return this.viserPort;
        }

        // 从 URL 参数获取
        const urlParams = new URLSearchParams(window.location.search);
        const backendParam = urlParams.get('backend');
        if (backendParam) {
            this.viserPort = parseInt(backendParam);
            console.log(`🔍 从URL参数获取后端端口: ${this.viserPort}`);
            return this.viserPort;
        }
        
        // 从当前前端端口推断
        const currentPort = parseInt(window.location.port) || 8080;
        this.viserPort = currentPort === 8084 ? 8082 : (currentPort === 8080 ? 8081 : currentPort + 1);
        
        console.log(`🔍 推断后端端口: ${this.viserPort}`);
        return this.viserPort;
    }

    async testPort(port) {
        // 快速端口测试 - 使用更轻量的方法
        try {
            return new Promise((resolve) => {
                // 使用img标签测试,更快更轻量
                const testImg = new Image();
                let resolved = false;
                
                testImg.onload = () => {
                    if (!resolved) {
                        resolved = true;
                        resolve(true);
                    }
                };
                
                testImg.onerror = () => {
                    if (!resolved) {
                        resolved = true;
                        // 即使图片加载失败,只要有响应就说明端口可用
                        resolve(true);
                    }
                };
                
                // 快速超时 - 500ms
                setTimeout(() => {
                    if (!resolved) {
                        resolved = true;
                        resolve(false);
                    }
                }, 500);
                
                // 尝试加载一个小资源
                testImg.src = `http://localhost:${port}/favicon.ico?t=${Date.now()}`;
            });
        } catch (error) {
            return false;
        }
    }

    async findWorkingBackendPort() {
        // 自动查找可用的后端端口
        // 首先尝试从URL参数或推断的端口
        const initialPort = this.detectBackendPort();
        console.log(`🔍 测试初始端口: ${initialPort}`);
        
        if (await this.testPort(initialPort)) {
            console.log(`✅ 端口 ${initialPort} 可用`);
            return initialPort;
        }
        
        // 如果初始端口不可用,尝试常用端口
        const commonPorts = [8081, 8082, 8083, 8084];
        console.log(`⚠️ 初始端口 ${initialPort} 不可用,尝试常用端口: ${commonPorts.join(', ')}`);
        
        for (const port of commonPorts) {
            // 注意:也要测试初始端口,因为iframe测试可能比直接检测更准确
            if (await this.testPort(port)) {
                console.log(`✅ 找到可用端口: ${port}`);
                this.viserPort = port;
                return port;
            }
        }
        
        console.error(`❌ 无法找到可用的后端端口`);
        throw new Error('无法连接到Viser后端');
    }

    async initializeSharedIframe() {
        if (this.sharedIframe && this.isLoaded) {
            return;
        }

        if (this.sharedIframe && !this.isLoaded) {
            // 等待加载完成
            return new Promise((resolve) => {
                const checkLoaded = () => {
                    if (this.isLoaded) {
                        resolve();
                    } else {
                        setTimeout(checkLoaded, 100);
                    }
                };
                checkLoaded();
            });
        }

        // 优先使用URL参数中的端口,这是最可靠的
        let port = this.detectBackendPort();
        console.log(`🎯 使用后端端口: ${port} (来源: URL参数或推断)`);
        
        // 跳过端口检测,直接使用配置的端口,加快启动速度
        
        console.log(`🔄 初始化共享Viser iframe (端口: ${port})`);
        
        return new Promise((resolve, reject) => {
            this.sharedIframe = document.createElement('iframe');
            this.sharedIframe.id = 'shared-viser-iframe';
            this.sharedIframe.title = 'Viser 3D Visualization';
            this.sharedIframe.style.cssText = `
                width: 100%;
                height: 100%;
                border: none;
                background: #001122;
                display: block;
            `;

            // 尝试不同的加载检测策略
            let isResolved = false;
            
            // 策略1: 传统的load事件
            this.sharedIframe.addEventListener('load', () => {
                if (!isResolved) {
                    this.isLoaded = true;
                    isResolved = true;
                    console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - load事件`);
                    resolve();
                }
            });

            this.sharedIframe.addEventListener('error', (event) => {
                if (!isResolved) {
                    isResolved = true;
                    console.error(`❌ 共享Viser iframe加载失败 (端口: ${port})`, event);
                    reject(new Error(`Viser连接失败,端口 ${port}`));
                }
            });
            
            // 策略2: 轮询检测iframe是否可访问
            const pollForLoad = () => {
                try {
                    // 检查iframe是否有内容
                    if (this.sharedIframe.contentDocument || this.sharedIframe.contentWindow) {
                        if (!isResolved) {
                            this.isLoaded = true;
                            isResolved = true;
                            console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - 轮询检测`);
                            resolve();
                            return;
                        }
                    }
                } catch (e) {
                    // CORS会导致访问异常,但这可能意味着iframe已经加载了外部内容
                    if (e.name === 'SecurityError' && !isResolved) {
                        this.isLoaded = true;
                        isResolved = true;
                        console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - CORS检测`);
                        resolve();
                        return;
                    }
                }
                
                // 继续轮询
                if (!isResolved) {
                    setTimeout(pollForLoad, 200);
                }
            };
            
            // 减少超时时间到2秒,加快响应
            const timeoutId = setTimeout(() => {
                if (!isResolved) {
                    isResolved = true;
                    console.warn(`⏰ Viser iframe加载超时 (端口: ${port}),但继续使用`);
                    // 超时后仍然继续,因为Viser可能仍在启动
                    this.isLoaded = true;
                    resolve();
                }
            }, 2000);
            
            // 设置src,这会触发加载
            console.log(`🔗 设置iframe src: http://localhost:${port}`);
            this.sharedIframe.src = `http://localhost:${port}`;
            
            // 立即开始轮询,减少延迟
            setTimeout(pollForLoad, 100);
        });
    }

    registerPlugin(pluginId, pluginInstance) {
        this.plugins.set(pluginId, pluginInstance);
        console.log(`📝 插件 ${pluginId} 已注册到 ViserManager`);
    }

    unregisterPlugin(pluginId) {
        this.plugins.delete(pluginId);
        console.log(`🗑️ 插件 ${pluginId} 已从 ViserManager 注销`);
    }

    async attachToPlugin(pluginId, targetContainer, loadingElement) {
        try {
            console.log(`🔍 附加共享iframe到插件 ${pluginId}`);
            
            // 确保共享iframe已初始化
            await this.initializeSharedIframe();
            
            // 隐藏加载指示器
            if (loadingElement) {
                loadingElement.style.display = 'none';
            }

            if (!targetContainer) {
                console.error('⚠️ 目标容器不存在');
                return false;
            }

            // 回到原来的全局覆盖策略,但使用absolute定位而不是fixed
            if (!this.globalContainer) {
                // 创建全局容器,但使用absolute定位
                this.globalContainer = document.createElement('div');
                this.globalContainer.id = 'viser-global-container';
                this.globalContainer.style.cssText = `
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    pointer-events: none;
                    z-index: -1;
                    top: 0;
                    left: 0;
                `;
                this.globalContainer.appendChild(this.sharedIframe);
                
                // 将全局容器添加到main-container
                const mainContainer = document.querySelector('.main-container') || document.body;
                // 确保主容器有relative定位(CSS中已设置,这里是保险)
                const computedStyle = window.getComputedStyle(mainContainer);
                if (computedStyle.position === 'static') {
                    mainContainer.style.position = 'relative';
                }
                mainContainer.appendChild(this.globalContainer);
                console.log(`🌍 创建了全局iframe容器,使用absolute定位`);
            }
            
            // 清空目标容器
            Array.from(targetContainer.children).forEach(child => {
                if (child !== loadingElement) {
                    child.remove();
                }
            });
            
            // 创建视口窗口
            const viewportWindow = document.createElement('div');
            viewportWindow.className = 'viser-viewport-window';
            viewportWindow.style.cssText = `
                width: 100%;
                height: 100%;
                position: relative;
                overflow: hidden;
            `;
            targetContainer.appendChild(viewportWindow);
            
            // 保存当前视口
            this.currentViewport = viewportWindow;
            
            // 更新iframe位置
            this.updateIframePosition();
            
            // 监听窗口大小变化
            if (!this.resizeObserver) {
                this.resizeObserver = new ResizeObserver(() => {
                    this.updateIframePosition();
                });
            }
            if (this.currentResizeTarget) {
                this.resizeObserver.unobserve(this.currentResizeTarget);
            }
            this.resizeObserver.observe(viewportWindow);
            this.currentResizeTarget = viewportWindow;
            
            // 更新当前插件
            const oldPlugin = this.currentPlugin;
            this.currentPlugin = pluginId;
            
            console.log(`✅ 插件 ${pluginId} 已激活 (从 ${oldPlugin || 'none'})`);
            console.log(`📊 使用全局覆盖策略,iframe跟随容器,状态完全保持`);
            
            return true;
            
        } catch (error) {
            console.error(`❌ 无法附加iframe到插件 ${pluginId}:`, error);
            
            // 显示错误信息
            if (loadingElement) {
                loadingElement.innerHTML = `
                    <div class="status-indicator" style="background: #f8d7da; color: #721c24; border-color: #f5c6cb;">
                        ❌ Viser 服务器连接失败,请确保后端正在运行在端口 ${this.detectBackendPort()}
                    </div>
                `;
            }
            
            return false;
        }
    }

    sendMessage(message) {
        if (this.sharedIframe && this.sharedIframe.contentWindow && this.isLoaded) {
            this.sharedIframe.contentWindow.postMessage(message, '*');
            console.log(`📤 消息已发送到Viser:`, message.type);
            return true;
        }
        console.warn('⚠️ 无法发送消息,iframe未就绪');
        return false;
    }

    // 广播消息给所有插件
    broadcastToPlugins(message) {
        this.plugins.forEach((plugin, id) => {
            if (plugin.onViserMessage && typeof plugin.onViserMessage === 'function') {
                try {
                    plugin.onViserMessage(message);
                } catch (error) {
                    console.error(`插件 ${id} 处理消息时出错:`, error);
                }
            }
        });
    }

    // 更新iframe位置以匹配当前视口
    updateIframePosition() {
        if (!this.globalContainer || !this.currentViewport) return;
        
        const rect = this.currentViewport.getBoundingClientRect();
        const mainContainer = document.querySelector('.main-container') || document.body;
        const mainRect = mainContainer.getBoundingClientRect();
        
        // 计算相对于主容器的位置(考虑滚动)
        const scrollTop = mainContainer.scrollTop || 0;
        const scrollLeft = mainContainer.scrollLeft || 0;
        const relativeTop = rect.top - mainRect.top + scrollTop;
        const relativeLeft = rect.left - mainRect.left + scrollLeft;
        
        // 更新全局容器的位置和大小
        this.globalContainer.style.cssText = `
            position: absolute;
            width: ${rect.width}px;
            height: ${rect.height}px;
            top: ${relativeTop}px;
            left: ${relativeLeft}px;
            pointer-events: auto;
            z-index: 1;
            visibility: visible;
        `;
        
        // 确保iframe填满容器
        if (this.sharedIframe) {
            this.sharedIframe.style.cssText = `
                width: 100%;
                height: 100%;
                border: none;
                display: block;
            `;
        }
        
        console.log(`📐 更新iframe位置: ${relativeLeft}, ${relativeTop}, ${rect.width}x${rect.height}`);
    }

    // 隐藏iframe(当切换到非可视化选项卡时)
    hideIframe() {
        if (this.globalContainer) {
            this.globalContainer.style.visibility = 'hidden';
            this.globalContainer.style.pointerEvents = 'none';
            console.log('🙈 隐藏iframe');
        }
        this.currentViewport = null;
    }
    
    // 显示iframe(通常由attachToPlugin调用)
    showIframe() {
        if (this.globalContainer && this.currentViewport) {
            this.updateIframePosition();
            console.log('👁️ 显示iframe');
        }
    }

    // 获取当前状态
    getCurrentState() {
        return {
            currentPlugin: this.currentPlugin,
            viserPort: this.viserPort,
            isLoaded: this.isLoaded,
            registeredPlugins: Array.from(this.plugins.keys()),
            hasGlobalContainer: !!this.globalContainer,
            currentViewport: this.currentViewport?.className || 'none'
        };
    }
    
    // 诊断方法
    diagnose() {
        console.log('🔍 ViserManager 诊断信息 (全局覆盖策略):');
        console.log('  - 当前插件:', this.currentPlugin);
        console.log('  - Viser端口:', this.viserPort);
        console.log('  - iframe已加载:', this.isLoaded);
        console.log('  - 注册插件数量:', this.plugins.size);
        console.log('  - 注册插件列表:', Array.from(this.plugins.keys()));
        console.log('  - 全局容器:', this.globalContainer?.id || 'none');
        console.log('  - 当前视口:', this.currentViewport?.className || 'none');
        
        if (this.sharedIframe) {
            console.log('  - iframe父容器:', this.sharedIframe.parentNode?.id || 'none');
            console.log('  - iframe src:', this.sharedIframe.src);
            console.log('  - iframe尺寸:', {
                width: this.sharedIframe.offsetWidth,
                height: this.sharedIframe.offsetHeight
            });
        }
        
        if (this.globalContainer) {
            console.log('  - 全局容器位置:', {
                position: this.globalContainer.style.position,
                top: this.globalContainer.style.top,
                left: this.globalContainer.style.left,
                width: this.globalContainer.style.width,
                height: this.globalContainer.style.height
            });
        }
    }

    // 销毁管理器
    destroy() {
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
        
        if (this.globalContainer) {
            this.globalContainer.remove();
            this.globalContainer = null;
        }
        
        if (this.sharedIframe) {
            this.sharedIframe.remove();
            this.sharedIframe = null;
        }
        
        this.plugins.clear();
        this.isLoaded = false;
        this.currentPlugin = null;
        this.currentViewport = null;
        
        console.log('🗑️ ViserManager 已销毁');
    }
}

// 创建全局单例
window.viserManager = window.viserManager || new ViserManagerSimple();

// 暴露诊断函数到全局作用域,方便调试
window.viserDiagnose = () => window.viserManager.diagnose();

// 导出给插件使用
export default window.viserManager;