// 全局变量
let currentConnectorType = null;
let allSettings = {};

// 连接件分类和类型映射
const connectorCategories = {
    '三合一': 'A',
    '二合一': 'C',
    '活动层板销': 'D',
   //  '四合一': 'A2',// 已注释，不显示
    // '螺钉': 'A3',  // 已注释，不显示
   // '隐藏式层板托': 'C2',// 已注释，不显示
   // '塞力斯快装二合一': 'E3',// 已注释，不显示
     //'铰链': 'HINGE'//
   
};

// 连接件参数定义
const paramDefinitions = {
    'A': {
        '偏心件孔尺寸参数': ['pxjd', 'pxja', 'd_yl'],
        '连接杆侧孔': ['ljgd', 'ljga'],
        '胶粒预埋孔': ['ymjd', 'ymjc']
    },
    'A2': {
        '偏心件孔尺寸参数': ['pxjd', 'pxja', 'd_yl'],
        '连接杆侧孔': ['ljgd', 'ljga'],
        '胶粒预埋孔': ['ymjd', 'ymjc']
    },
    'A3': {
        '偏心孔设置': ['pxjd', 'pxja', 'pxjh'],
        '连接杆设置': ['ljgd', 'ljgb', 'ljga'],
        '侧板孔设置': ['ljgwidth']
    },
    'C': {
        '偏心件孔尺寸参数': ['pxjd', 'pxja', 'pxjs'],
        '连接杆孔尺寸参数': ['ljgd', 'ljgc']
    },
    'D': {
        '活动层板销': ['hdcbd', 'mbd']
    },
    'E3': {
        '侧板开孔': ['cbd', 'cbc'],
        '面板开孔': ['mbd', 'mbc']
    },
    'HINGE': {
        '铰链孔设置': ['d', 's', 'a', 'c', 'display_hinge_hole', 'ymk_d', 'ymk_k', 'ymk_l', 'cb_l', 'cb_a']
    }
};

// 参数标签
const paramLabels = {
    'pxjd': '直径(pxjd)',
    'pxja': '边距(pxja)',
    'pxjh': '偏心件高度',
    'pxjs': '偏心件深度(pxjs)',
    'd_yl': '偏心件孔深度余量(d_yl)',
    'ljgd': '直径(ljgd)',
    'ljgb': '连接杆长度B',
    'ljga': '深度(ljga)',
    'ljgc': '深度(ljgc)',
    'ljgwidth': '侧板孔深度(ljgwidth)',
    'ymjd': '直径(ymjd)',
    'ymjc': '深度(ymjc)',
    'hdcbd': '开孔直径(hdcbd)',
    'mbd': '开孔深度(mbd)',
    'width': '伸出长度(width)',
    'cbd': '侧板开孔直径(cbd)',
    'cbc': '侧板开孔深度(cbc)',
    'mbc': '面板开孔深度(mbc)',
    'd': '绞杯孔直径(d)',
    's': '绞杯孔深度(s)',
    'a': '预埋孔偏距(a)',
    'c': '绞杯孔边距(c)',
    'display_hinge_hole': '添加铰链螺丝预埋孔',
    'ymk_d': '螺丝预埋孔直径(ymk_d)',
    'ymk_k': '螺丝预埋孔深度(ymk_k)',
    'ymk_l': '螺丝预埋孔间距(ymk_l)',
    'cb_l': '侧板孔引间距(cb_l)',
    'cb_a': '侧板孔引偏距(cb_a)'
};

// 渲染连接件列表
function renderConnectorList() {
    const list = document.getElementById('connectorList');
    if (!list) return;
    
    list.innerHTML = '';
    
    Object.keys(connectorCategories).forEach(category => {
        const type = connectorCategories[category];
        const item = document.createElement('li');
        item.className = 'connector-item';
        item.textContent = category;
        item.dataset.type = type;
        item.onclick = function() {
            selectConnector(type);
        };
        if (currentConnectorType === type) {
            item.classList.add('active');
        }
        list.appendChild(item);
    });
}

// 选择连接件
function selectConnector(type) {
    currentConnectorType = type;
    
    // 更新列表选中状态
    document.querySelectorAll('.connector-item').forEach(item => {
        item.classList.remove('active');
        if (item.dataset.type === type) {
            item.classList.add('active');
        }
    });
    
    // 更新标题
    const title = document.getElementById('connectorTitle');
    if (title) {
        const category = Object.keys(connectorCategories).find(cat => connectorCategories[cat] === type);
        title.textContent = (category || type) + ' 参数设置';
    }
    
    // 渲染表单
    renderParamsForm(type);
    
    // 显示保存按钮
    const footer = document.getElementById('contentFooter');
    if (footer) {
        footer.style.display = 'flex';
    }
}

// 渲染参数表单
function renderParamsForm(type) {
    const body = document.getElementById('contentBody');
    if (!body) return;
    
    console.log('=== renderParamsForm 被调用 ===');
    console.log('连接件类型:', type);
    console.log('allSettings:', allSettings);
    console.log('allSettings.connector_size_setting:', allSettings.connector_size_setting);
    
    let params = {};
    if (type === 'HINGE') {
        if (allSettings.general_settings && allSettings.general_settings.hinge) {
            params = {...allSettings.general_settings.hinge};
            if (params.jl_setting) {
                Object.assign(params, params.jl_setting);
                params.jl_distance = allSettings.general_settings.hinge.jl_distance;
            }
        }
    } else {
        // 尝试多种方式访问数据
        if (allSettings.connector_size_setting) {
            // 先尝试使用点号访问
            if (allSettings.connector_size_setting[type]) {
                params = allSettings.connector_size_setting[type];
                console.log(`✓ 从 allSettings.connector_size_setting[${type}] 读取参数:`, params);
            } else if (allSettings.connector_size_setting[String(type)]) {
                params = allSettings.connector_size_setting[String(type)];
                console.log(`✓ 从 allSettings.connector_size_setting["${type}"] 读取参数:`, params);
            } else {
                console.warn(`✗ 警告: allSettings.connector_size_setting[${type}] 不存在或为空`);
                console.warn(`可用的键:`, Object.keys(allSettings.connector_size_setting || {}));
                params = {};
            }
        } else {
            console.error(`✗ 错误: allSettings.connector_size_setting 不存在`);
            params = {};
        }
    }
    
    console.log('最终使用的 params:', params);
    console.log('params keys:', Object.keys(params));
    
    const definition = paramDefinitions[type];
    if (!definition) {
        body.innerHTML = '<div class="empty-state"><p>该连接件类型暂无参数定义</p></div>';
        return;
    }
    
    let html = '<div class="params-form">';
    
    Object.keys(definition).forEach(sectionName => {
        html += `<div class="section-title">${sectionName}</div>`;
        html += '<div class="form-row">';
        
        definition[sectionName].forEach(paramKey => {
            const label = paramLabels[paramKey] || paramKey;
            let value = params[paramKey] !== undefined ? params[paramKey] : '';
            
            // 格式化数值，避免显示 7.999999 这样的浮点误差
            if (typeof value === 'number') {
                // 保留1位小数，避免浮点误差
                value = Math.round(value * 10) / 10;
            }
            
            if (paramKey === 'display_hinge_hole') {
                html += `
                    <div class="form-group">
                        <label style="display: flex; align-items: center; gap: 10px;">
                            <input type="checkbox" id="${paramKey}" ${value ? 'checked' : ''}>
                            <span>${label}</span>
                        </label>
                    </div>
                `;
            } else {
                html += `
                    <div class="form-group">
                        <label for="${paramKey}">${label}</label>
                        <input type="number" id="${paramKey}" value="${value}" step="0.1" placeholder="请输入${label}">
                    </div>
                `;
            }
        });
        
        html += '</div>';
    });
    
    html += '</div>';
    body.innerHTML = html;
}

// 保存参数
function saveParams() {
    if (!currentConnectorType) {
        showMessage('请先选择连接件类型', 'error');
        return;
    }
    
    console.log('开始保存参数，连接件类型:', currentConnectorType);
    
    const params = {};
    const definition = paramDefinitions[currentConnectorType];
    
    if (!definition) {
        showMessage('该连接件类型无参数定义', 'error');
        return;
    }
    
    // 收集所有参数
    Object.values(definition).forEach(paramKeys => {
        paramKeys.forEach(paramKey => {
            const input = document.getElementById(paramKey);
            if (input) {
                if (input.type === 'checkbox') {
                    params[paramKey] = input.checked;
                } else {
                    const value = input.value.trim();
                    if (value !== '') {
                        const numValue = parseFloat(value);
                        if (!isNaN(numValue)) {
                            params[paramKey] = numValue;
                        }
                    }
                }
            }
        });
    });
    
    console.log('收集到的参数:', params);
    console.log('参数数量:', Object.keys(params).length);
    
    if (Object.keys(params).length === 0) {
        showMessage('没有可保存的参数', 'error');
        return;
    }
    
    if (currentConnectorType === 'HINGE') {
        const data = { hinge: params };
        console.log('发送铰链参数:', data);
        
        // 检查 sketchup 对象（优先使用 window.sketchup）
        let postMessageFunc = null;
        
        if (typeof window.sketchup !== 'undefined' && typeof window.sketchup.post_message === 'function') {
            postMessageFunc = window.sketchup.post_message;
            console.log('✓ 使用 window.sketchup.post_message');
        } else if (typeof sketchup !== 'undefined' && typeof sketchup.post_message === 'function') {
            postMessageFunc = sketchup.post_message;
            console.log('✓ 使用 sketchup.post_message');
        } else {
            console.error('✗ 无法找到 sketchup.post_message');
            console.log('window.sketchup:', typeof window.sketchup);
            console.log('window.sketchup.post_message:', typeof (window.sketchup && window.sketchup.post_message));
            console.log('sketchup:', typeof sketchup);
            console.log('sketchup.post_message:', typeof (sketchup && sketchup.post_message));
            
            // 尝试等待桥接代码注入（最多等待2秒）
            let waitCount = 0;
            const waitInterval = setInterval(function() {
                waitCount++;
                if (typeof window.sketchup !== 'undefined' && typeof window.sketchup.post_message === 'function') {
                    console.log('✓ 等待后找到 window.sketchup.post_message');
                    clearInterval(waitInterval);
                    window.sketchup.post_message('set_general_params', JSON.stringify(data));
                    showMessage('参数已保存', 'success');
                } else if (waitCount >= 4) {
                    console.error('✗ 等待超时，sketchup.post_message 仍未定义');
                    clearInterval(waitInterval);
                    showMessage('无法连接到后端: sketchup.post_message 未定义', 'error');
                }
            }, 500);
            return;
        }
        
        // 调用 post_message
        if (postMessageFunc) {
            try {
                postMessageFunc('set_general_params', JSON.stringify(data));
                showMessage('参数已保存', 'success');
            } catch(e) {
                console.error('调用 post_message 失败:', e);
                showMessage('保存失败: ' + e.message, 'error');
            }
        }
    } else {
        const data = {
            type: currentConnectorType,
            params: params
        };
        console.log('发送连接件参数:', data);
        
        // 检查 sketchup 对象（优先使用 window.sketchup）
        let postMessageFunc = null;
        
        if (typeof window.sketchup !== 'undefined' && typeof window.sketchup.post_message === 'function') {
            postMessageFunc = window.sketchup.post_message;
            console.log('✓ 使用 window.sketchup.post_message');
        } else if (typeof sketchup !== 'undefined' && typeof sketchup.post_message === 'function') {
            postMessageFunc = sketchup.post_message;
            console.log('✓ 使用 sketchup.post_message');
        } else {
            console.error('✗ 无法找到 sketchup.post_message');
            console.log('window.sketchup:', typeof window.sketchup);
            console.log('window.sketchup.post_message:', typeof (window.sketchup && window.sketchup.post_message));
            console.log('sketchup:', typeof sketchup);
            console.log('sketchup.post_message:', typeof (sketchup && sketchup.post_message));
            
            // 尝试等待桥接代码注入（最多等待2秒）
            let waitCount = 0;
            const waitInterval = setInterval(function() {
                waitCount++;
                if (typeof window.sketchup !== 'undefined' && typeof window.sketchup.post_message === 'function') {
                    console.log('✓ 等待后找到 window.sketchup.post_message');
                    clearInterval(waitInterval);
                    window.sketchup.post_message('set_connector_params', JSON.stringify(data));
                    showMessage('参数已保存', 'success');
                } else if (waitCount >= 4) {
                    console.error('✗ 等待超时，sketchup.post_message 仍未定义');
                    clearInterval(waitInterval);
                    showMessage('无法连接到后端: sketchup.post_message 未定义', 'error');
                }
            }, 500);
            return;
        }
        
        // 调用 post_message
        if (postMessageFunc) {
            try {
                postMessageFunc('set_connector_params', JSON.stringify(data));
                showMessage('参数已保存', 'success');
            } catch(e) {
                console.error('调用 post_message 失败:', e);
                showMessage('保存失败: ' + e.message, 'error');
            }
        }
    }
}

// 重置参数
function resetParams() {
    if (!currentConnectorType) return;
    selectConnector(currentConnectorType);
}

// 显示消息
function showMessage(message, type) {
    const container = document.getElementById('messageContainer');
    if (!container) return;
    
    const msgDiv = document.createElement('div');
    msgDiv.className = `message ${type}`;
    msgDiv.textContent = message;
    container.appendChild(msgDiv);
    
    setTimeout(() => {
        msgDiv.remove();
    }, 3000);
}

// 接收设置数据（添加防重复调用机制）
let lastSettingsHash = null;
function receiveSettings(settings) {
    if (!settings) {
        console.error('✗ 错误: settings 为空或 undefined');
        return;
    }
    
    // 检查是否是重复调用（通过比较关键数据）
    const currentHash = JSON.stringify(settings.connector_size_setting);
    if (currentHash === lastSettingsHash) {
        console.log('receiveSettings: 数据未变化，跳过重复处理');
        return;
    }
    lastSettingsHash = currentHash;
    
    console.log('=== receiveSettings 被调用 ===');
    console.log('接收到的 settings keys:', Object.keys(settings));
    
    if (settings.connector_size_setting) {
        console.log('✓ connector_size_setting 存在，包含', Object.keys(settings.connector_size_setting).length, '个连接件');
    } else {
        console.error('✗ 错误: settings.connector_size_setting 不存在');
        return;
    }
    
    // 深拷贝设置，确保数据不会丢失
    allSettings = JSON.parse(JSON.stringify(settings || {}));
    
    // 验证数据
    if (allSettings.connector_size_setting) {
        console.log('✓ allSettings.connector_size_setting 已设置，包含', Object.keys(allSettings.connector_size_setting).length, '个连接件');
    } else {
        console.error('✗ 错误: allSettings.connector_size_setting 不存在');
        return;
    }
    
    renderConnectorList();
    
    // 如果没有选中连接件，自动选中第一个
    if (!currentConnectorType && Object.keys(connectorCategories).length > 0) {
        const firstType = connectorCategories[Object.keys(connectorCategories)[0]];
        selectConnector(firstType);
    } else if (currentConnectorType) {
        selectConnector(currentConnectorType);
    }
}

// 调试函数
function toggleDebugPanel() {
    const panel = document.getElementById('debugPanel');
    if (panel) {
        panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
    }
}

function clearDebugLog() {
    const content = document.getElementById('debugContent');
    if (content) {
        content.innerHTML = '';
    }
}

function logDebug(message) {
    const content = document.getElementById('debugContent');
    if (content) {
        const time = new Date().toLocaleTimeString();
        const logEntry = document.createElement('div');
        logEntry.textContent = `[${time}] ${message}`;
        content.appendChild(logEntry);
        content.scrollTop = content.scrollHeight;
    }
    console.log(message);
}

// 分割线拖动功能
function initResizer() {
    const resizer = document.getElementById('resizer');
    const sidebar = document.getElementById('sidebar');
    
    if (!resizer || !sidebar) return;
    
    let isResizing = false;
    let startX = 0;
    let startWidth = 0;
    
    resizer.addEventListener('mousedown', function(e) {
        isResizing = true;
        startX = e.clientX;
        startWidth = sidebar.offsetWidth;
        document.body.style.cursor = 'col-resize';
        document.body.style.userSelect = 'none';
        e.preventDefault();
    });
    
    document.addEventListener('mousemove', function(e) {
        if (!isResizing) return;
        
        const diff = e.clientX - startX;
        const newWidth = startWidth + diff;
        const minWidth = 150;
        const maxWidth = 400;
        
        if (newWidth >= minWidth && newWidth <= maxWidth) {
            sidebar.style.width = newWidth + 'px';
        }
    });
    
    document.addEventListener('mouseup', function() {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
        }
    });
}

// 暴露到全局
window.selectConnector = selectConnector;
window.saveParams = saveParams;
window.resetParams = resetParams;
window.receiveSettings = receiveSettings;
window.toggleDebugPanel = toggleDebugPanel;
window.clearDebugLog = clearDebugLog;
window.logDebug = logDebug;

// 立即初始化
(function() {
    function init() {
        const list = document.getElementById('connectorList');
        if (!list) {
            setTimeout(init, 50);
            return;
        }
        
        console.log('=== 前端初始化开始 ===');
        console.log('window.initialSettings:', window.initialSettings);
        
        // 初始化分割线拖动功能
        initResizer();
        
        // 先渲染列表（即使没有数据也要渲染）
        renderConnectorList();
        
        // 检查并接收数据
        if (window.initialSettings) {
            console.log('✓ 发现 window.initialSettings，调用 receiveSettings');
            receiveSettings(window.initialSettings);
        } else {
            console.log('等待后端发送数据...');
        }
        
        // 监听 settingsLoaded 事件（只监听一次，避免重复处理）
        if (!window.settingsLoadedListenerAdded) {
            window.addEventListener('settingsLoaded', function(event) {
                console.log('收到 settingsLoaded 事件，调用 receiveSettings');
                receiveSettings(event.detail);
            });
            window.settingsLoadedListenerAdded = true;
        }
        
        // 延迟检查，确保数据已加载（最多检查5次，2.5秒）
        let checkCount = 0;
        const checkInterval = setInterval(function() {
            checkCount++;
            if (window.initialSettings && (!allSettings.connector_size_setting || Object.keys(allSettings.connector_size_setting).length === 0)) {
                console.log(`延迟检查 ${checkCount}，发现 window.initialSettings，调用 receiveSettings`);
                receiveSettings(window.initialSettings);
            }
            if (checkCount >= 5 || (allSettings.connector_size_setting && Object.keys(allSettings.connector_size_setting).length > 0)) {
                clearInterval(checkInterval);
                if (allSettings.connector_size_setting && Object.keys(allSettings.connector_size_setting).length > 0) {
                    console.log('✓ 数据已成功加载');
                } else {
                    console.warn('延迟检查超时，数据仍未加载');
                }
            }
        }, 500);
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
