// 通用工具函数

/**
 * 显示模态框
 * @param {string} modalId - 模态框的ID
 */
function showModal(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        // 使用className替代classList以提高兼容性
        if (modal.classList) {
            modal.classList.remove('hidden');
        } else {
            modal.className = modal.className.replace('hidden', '');
        }
    }
}

/**
 * 关闭模态框
 * @param {string} modalId - 模态框的ID
 */
function closeModal(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        // 使用className替代classList以提高兼容性
        if (modal.classList) {
            modal.classList.add('hidden');
        } else {
            modal.className += ' hidden';
        }
    }
}

/**
 * 绑定模态框点击外部关闭事件
 * @param {string} modalId - 模态框的ID
 */
function bindModalOutsideClick(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal(modalId);
            }
        });
    }
}

/**
 * 显示消息提示
 * @param {string} message - 消息内容
 * @param {boolean} isSuccess - 是否为成功消息
 * @param {number} duration - 消息显示时长(毫秒)
 */
function showMessage(message, isSuccess, duration) {
    // 为参数设置默认值，不使用ES6默认参数
    isSuccess = (isSuccess === undefined) ? true : isSuccess;
    duration = (duration === undefined) ? 5000 : duration;
    
    var messageContainer = document.getElementById('messageContainer');
    var successMessage = document.getElementById('successMessage');
    var errorMessage = document.getElementById('errorMessage');
    
    if (!messageContainer || !successMessage || !errorMessage) return;
    
    if (isSuccess) {
        successMessage.querySelector('span').textContent = message;
        if (successMessage.classList) {
            successMessage.classList.remove('hidden');
        } else {
            successMessage.className = successMessage.className.replace('hidden', '');
        }
        if (errorMessage.classList) {
            errorMessage.classList.add('hidden');
        } else {
            errorMessage.className += ' hidden';
        }
    } else {
        errorMessage.querySelector('span').textContent = message;
        if (errorMessage.classList) {
            errorMessage.classList.remove('hidden');
        } else {
            errorMessage.className = errorMessage.className.replace('hidden', '');
        }
        if (successMessage.classList) {
            successMessage.classList.add('hidden');
        } else {
            successMessage.className += ' hidden';
        }
    }
    
    if (messageContainer.classList) {
        messageContainer.classList.remove('hidden');
    } else {
        messageContainer.className = messageContainer.className.replace('hidden', '');
    }
    
    // 自动隐藏
    setTimeout(function() {
        if (isSuccess) {
            if (successMessage.classList) {
                successMessage.classList.add('hidden');
            } else {
                successMessage.className += ' hidden';
            }
        } else {
            if (errorMessage.classList) {
                errorMessage.classList.add('hidden');
            } else {
                errorMessage.className += ' hidden';
            }
        }
        if (messageContainer.classList) {
            messageContainer.classList.add('hidden');
        } else {
            messageContainer.className += ' hidden';
        }
    }, duration);
}

/**
 * 显示表单错误消息
 * @param {string} errorId - 错误容器的ID
 * @param {string} messageId - 错误消息的ID
 * @param {string} message - 错误消息内容
 * @param {string} successId - 成功消息容器的ID
 */
function showFormError(errorId, messageId, message, successId) {
    successId = successId || '';
    
    var errorContainer = document.getElementById(errorId);
    var errorMessage = document.getElementById(messageId);
    var successContainer = successId ? document.getElementById(successId) : null;
    
    if (!errorContainer || !errorMessage) return;
    
    errorMessage.textContent = message;
    if (errorContainer.classList) {
        errorContainer.classList.remove('hidden');
    } else {
        errorContainer.className = errorContainer.className.replace('hidden', '');
    }
    
    if (successContainer) {
        if (successContainer.classList) {
            successContainer.classList.add('hidden');
        } else {
            successContainer.className += ' hidden';
        }
    }
    
    // 滚动到错误信息，使用简单滚动方式替代smooth behavior
    errorContainer.scrollIntoView(false);
}

/**
 * 显示表单成功消息
 * @param {string} successId - 成功容器的ID
 * @param {string} messageId - 成功消息的ID
 * @param {string} message - 成功消息内容
 * @param {string} errorId - 错误消息容器的ID
 */
function showFormSuccess(successId, messageId, message, errorId) {
    errorId = errorId || '';
    
    var successContainer = document.getElementById(successId);
    var successMessage = document.getElementById(messageId);
    var errorContainer = errorId ? document.getElementById(errorId) : null;
    
    if (!successContainer || !successMessage) return;
    
    successMessage.textContent = message;
    if (successContainer.classList) {
        successContainer.classList.remove('hidden');
    } else {
        successContainer.className = successContainer.className.replace('hidden', '');
    }
    
    if (errorContainer) {
        if (errorContainer.classList) {
            errorContainer.classList.add('hidden');
        } else {
            errorContainer.className += ' hidden';
        }
    }
    
    // 滚动到成功信息，使用简单滚动方式替代smooth behavior
    successContainer.scrollIntoView(false);
}

/**
 * 发起API请求的通用函数 - 使用Promise替代async/await以提高兼容性
 * @param {string} url - 请求URL
 * @param {string} method - 请求方法
 * @param {object} data - 请求数据
 * @param {object} options - 附加选项
 * @returns {Promise} - 返回Promise对象
 */
function apiRequest(url, method, data, options) {
    // 为参数设置默认值，不使用ES6默认参数
    method = method || 'GET';
    data = data || null;
    options = options || {};
    
    // 手动合并选项，不使用扩展运算符
    var defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        },
        method: method
    };
    
    // 手动合并options
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            if (key === 'headers' && options.headers) {
                for (var headerKey in options.headers) {
                    if (options.headers.hasOwnProperty(headerKey)) {
                        defaultOptions.headers[headerKey] = options.headers[headerKey];
                    }
                }
            } else {
                defaultOptions[key] = options[key];
            }
        }
    }
    
    if (data) {
        // 根据Content-Type处理数据
        if (defaultOptions.headers['Content-Type'] === 'application/json') {
            defaultOptions.body = JSON.stringify(data);
        } else if (defaultOptions.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
            defaultOptions.body = new URLSearchParams(data);
        }
    }
    
    // 使用Promise替代async/await
    return new Promise(function(resolve, reject) {
        fetch(url, defaultOptions)
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('网络错误');
                }
                return response.json();
            })
            .then(function(data) {
                resolve(data);
            })
            .catch(function(error) {
                console.error('API请求错误 [' + url + ']:', error);
                reject(error);
            });
    });
}

/**
 * 重置表单
 * @param {string} formId - 表单ID
 */
function resetForm(formId) {
    var form = document.getElementById(formId);
    if (form) {
        form.reset();
    }
}

/**
 * 填充表单数据
 * @param {string} formId - 表单ID
 * @param {object} data - 表单数据对象
 */
function fillForm(formId, data) {
    var form = document.getElementById(formId);
    if (!form || !data) return;
    
    // 使用传统的for-in循环替代forEach
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            var element = form.elements[key] || document.getElementById(key);
            if (element) {
                element.value = data[key] || '';
            }
        }
    }
}

/**
 * 防抖函数 - 使用传统函数替代箭头函数
 * @param {Function} func - 要防抖的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} - 返回防抖后的函数
 */
function debounce(func, delay) {
    var timeoutId;
    var that = this;
    
    return function() {
        var context = this;
        var args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            func.apply(context || that, args);
        }, delay);
    };
}

/**
 * 节流函数 - 使用传统函数替代箭头函数
 * @param {Function} func - 要节流的函数
 * @param {number} limit - 时间限制(毫秒)
 * @returns {Function} - 返回节流后的函数
 */
function throttle(func, limit) {
    var inThrottle;
    var that = this;
    
    return function() {
        var context = this;
        var args = arguments;
        
        if (!inThrottle) {
            func.apply(context || that, args);
            inThrottle = true;
            setTimeout(function() {
                inThrottle = false;
            }, limit);
        }
    };
}