// settings.js - 处理用户设置页面的功能
// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
// 检查用户登录状态
checkAuthStatus();
// 初始化表单事件监听器
initFormListeners();
// 初始化模态框事件监听器
initModalListeners();
// 初始化界面设置
initInterfaceSettings();
});
/**
* 检查用户的登录状态
*/
async function checkAuthStatus() {
try {
// 确保Supabase客户端已初始化
if (window.supabaseClient) {
const { data: { user }, error } = await window.supabaseClient.auth.getUser();
if (error || !user) {
// 用户未登录,重定向到首页
showAlert('请先登录以访问设置页面', 'warning');
setTimeout(() => {
window.location.href = 'index.html';
}, 2000);
return;
}
// 用户已登录,加载设置数据
loadSettingsData(user);
// 显示用户信息
document.getElementById('username').textContent = user.email.split('@')[0];
document.getElementById('profile-username').textContent = user.email.split('@')[0];
document.getElementById('profile-email').textContent = user.email;
// 显示用户界面元素
document.getElementById('auth-buttons').classList.add('d-none');
document.getElementById('user-profile').classList.remove('d-none');
} else {
console.error('Supabase client not initialized');
}
} catch (error) {
console.error('Error checking auth status:', error);
}
}
/**
* 加载用户设置数据
* @param {Object} user - 当前登录的用户对象
*/
async function loadSettingsData(user) {
try {
if (window.supabaseClient) {
// 从Supabase获取用户设置数据
const { data, error } = await window.supabaseClient
.from('user_settings')
.select('*')
.eq('user_id', user.id)
.single();
if (error && error.code !== 'PGRST116') { // PGRST116 是 "未找到记录" 的错误代码
console.error('Error loading settings data:', error);
return;
}
if (data) {
// 界面设置
if (data.theme) {
document.querySelector(`input[name="theme"][id="theme-${data.theme}"]`).checked = true;
}
if (data.language) {
document.getElementById('language-select').value = data.language;
}
if (data.font_size) {
document.getElementById('font-size-range').value = data.font_size;
document.getElementById('font-size-value').textContent = `${data.font_size}%`;
}
// 通知设置
document.getElementById('email-notifications').checked = data.email_notifications !== false;
document.getElementById('keyword-alerts').checked = data.keyword_alerts !== false;
document.getElementById('marketing-emails').checked = data.marketing_emails === true;
// 数据设置
document.getElementById('search-history').checked = data.save_search_history !== false;
document.getElementById('usage-analytics').checked = data.usage_analytics !== false;
// 高级设置
if (data.default_view) {
document.getElementById('default-view').value = data.default_view;
}
if (data.results_per_page) {
document.getElementById('results-per-page').value = data.results_per_page;
}
}
}
} catch (error) {
console.error('Error loading settings data:', error);
}
}
/**
* 初始化表单事件监听器
*/
function initFormListeners() {
// 界面设置表单
const saveInterfaceBtn = document.getElementById('save-interface-settings');
if (saveInterfaceBtn) {
saveInterfaceBtn.addEventListener('click', async function(e) {
e.preventDefault();
await saveInterfaceSettings();
});
}
// 字体大小滑块
const fontSizeRange = document.getElementById('font-size-range');
const fontSizeValue = document.getElementById('font-size-value');
if (fontSizeRange && fontSizeValue) {
fontSizeRange.addEventListener('input', function() {
fontSizeValue.textContent = `${this.value}%`;
document.documentElement.style.fontSize = `${this.value / 100}rem`;
});
}
// 通知设置表单
const saveNotificationBtn = document.getElementById('save-notification-settings');
if (saveNotificationBtn) {
saveNotificationBtn.addEventListener('click', async function(e) {
e.preventDefault();
await saveNotificationSettings();
});
}
// 高级设置表单
const saveAdvancedBtn = document.getElementById('save-advanced-settings');
if (saveAdvancedBtn) {
saveAdvancedBtn.addEventListener('click', async function(e) {
e.preventDefault();
await saveAdvancedSettings();
});
}
// 数据导出按钮
const exportDataBtn = document.getElementById('export-data-btn');
if (exportDataBtn) {
exportDataBtn.addEventListener('click', function(e) {
e.preventDefault();
// 此功能需要实现数据导出,暂时显示提示
showAlert('数据导出功能即将推出', 'info');
});
}
// 清除数据按钮
const clearDataBtn = document.getElementById('clear-data-btn');
if (clearDataBtn) {
clearDataBtn.addEventListener('click', function(e) {
e.preventDefault();
// 此功能需要实现数据清除,暂时显示提示
showAlert('数据清除功能即将推出', 'info');
});
}
// API密钥相关按钮
const showApiKeyBtn = document.getElementById('show-api-key-btn');
if (showApiKeyBtn) {
showApiKeyBtn.addEventListener('click', function() {
const apiKeyInput = document.getElementById('api-key');
if (apiKeyInput.type === 'password') {
apiKeyInput.type = 'text';
this.innerHTML = '';
} else {
apiKeyInput.type = 'password';
this.innerHTML = '';
}
});
}
const copyApiKeyBtn = document.getElementById('copy-api-key-btn');
if (copyApiKeyBtn) {
copyApiKeyBtn.addEventListener('click', function() {
const apiKeyInput = document.getElementById('api-key');
apiKeyInput.select();
document.execCommand('copy');
showAlert('API密钥已复制到剪贴板', 'success');
});
}
const regenerateApiKeyBtn = document.getElementById('regenerate-api-key-btn');
if (regenerateApiKeyBtn) {
regenerateApiKeyBtn.addEventListener('click', function() {
// 此功能需要实现API密钥重新生成,暂时显示提示
showAlert('API密钥重新生成功能即将推出', 'info');
});
}
// 侧边栏退出登录
const sidebarLogout = document.getElementById('sidebar-logout');
if (sidebarLogout) {
sidebarLogout.addEventListener('click', function(e) {
e.preventDefault();
logout();
});
}
// 导航栏退出登录
const logoutButton = document.getElementById('logout-button');
if (logoutButton) {
logoutButton.addEventListener('click', function(e) {
e.preventDefault();
logout();
});
}
}
/**
* 初始化模态框事件监听器
*/
function initModalListeners() {
// 删除账户按钮
const deleteAccountBtn = document.getElementById('delete-account-btn');
if (deleteAccountBtn) {
deleteAccountBtn.addEventListener('click', function() {
const deleteAccountModal = new bootstrap.Modal(document.getElementById('deleteAccountModal'));
deleteAccountModal.show();
});
}
// 确认删除账户复选框
const confirmDeletion = document.getElementById('confirm-deletion');
const confirmDeleteAccountBtn = document.getElementById('confirm-delete-account-btn');
if (confirmDeletion && confirmDeleteAccountBtn) {
confirmDeletion.addEventListener('change', function() {
confirmDeleteAccountBtn.disabled = !this.checked;
});
}
// 确认删除账户按钮
if (confirmDeleteAccountBtn) {
confirmDeleteAccountBtn.addEventListener('click', async function() {
const password = document.getElementById('confirm-password').value;
if (!password) {
showAlert('请输入密码以确认删除', 'warning');
return;
}
// 此功能需要实现账户删除,暂时显示提示
showAlert('账户删除功能即将推出', 'info');
// 关闭模态框
const deleteAccountModal = bootstrap.Modal.getInstance(document.getElementById('deleteAccountModal'));
deleteAccountModal.hide();
});
}
}
/**
* 初始化界面设置
*/
function initInterfaceSettings() {
// 主题切换
const themeRadios = document.querySelectorAll('input[name="theme"]');
themeRadios.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
applyTheme(this.id.replace('theme-', ''));
}
});
});
// 初始化API密钥输入框为密码类型
const apiKeyInput = document.getElementById('api-key');
if (apiKeyInput) {
apiKeyInput.type = 'password';
}
}
/**
* 应用主题
* @param {string} theme - 主题名称 (light, dark, system)
*/
function applyTheme(theme) {
const body = document.body;
// 移除现有主题类
body.classList.remove('theme-light', 'theme-dark');
if (theme === 'system') {
// 使用系统主题
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
body.classList.add(prefersDark ? 'theme-dark' : 'theme-light');
} else {
// 使用指定主题
body.classList.add(`theme-${theme}`);
}
}
/**
* 保存界面设置
*/
async function saveInterfaceSettings() {
try {
if (window.supabaseClient) {
const { data: { user }, error: userError } = await window.supabaseClient.auth.getUser();
if (userError || !user) {
showAlert('获取用户信息失败,请重新登录', 'error');
return;
}
// 获取主题设置
let theme = 'light';
document.querySelectorAll('input[name="theme"]').forEach(radio => {
if (radio.checked) {
theme = radio.id.replace('theme-', '');
}
});
// 获取语言设置
const language = document.getElementById('language-select').value;
// 获取字体大小设置
const fontSize = document.getElementById('font-size-range').value;
// 更新设置
const { error } = await window.supabaseClient
.from('user_settings')
.upsert({
user_id: user.id,
theme: theme,
language: language,
font_size: fontSize,
updated_at: new Date()
});
if (error) {
console.error('Error saving interface settings:', error);
showAlert('保存界面设置失败', 'error');
return;
}
showAlert('界面设置已保存', 'success');
}
} catch (error) {
console.error('Error saving interface settings:', error);
showAlert('保存界面设置时出错', 'error');
}
}
/**
* 保存通知设置
*/
async function saveNotificationSettings() {
try {
if (window.supabaseClient) {
const { data: { user }, error: userError } = await window.supabaseClient.auth.getUser();
if (userError || !user) {
showAlert('获取用户信息失败,请重新登录', 'error');
return;
}
// 获取通知设置
const emailNotifications = document.getElementById('email-notifications').checked;
const keywordAlerts = document.getElementById('keyword-alerts').checked;
const marketingEmails = document.getElementById('marketing-emails').checked;
// 更新设置
const { error } = await window.supabaseClient
.from('user_settings')
.upsert({
user_id: user.id,
email_notifications: emailNotifications,
keyword_alerts: keywordAlerts,
marketing_emails: marketingEmails,
updated_at: new Date()
});
if (error) {
console.error('Error saving notification settings:', error);
showAlert('保存通知设置失败', 'error');
return;
}
showAlert('通知设置已保存', 'success');
}
} catch (error) {
console.error('Error saving notification settings:', error);
showAlert('保存通知设置时出错', 'error');
}
}
/**
* 保存高级设置
*/
async function saveAdvancedSettings() {
try {
if (window.supabaseClient) {
const { data: { user }, error: userError } = await window.supabaseClient.auth.getUser();
if (userError || !user) {
showAlert('获取用户信息失败,请重新登录', 'error');
return;
}
// 获取高级设置
const defaultView = document.getElementById('default-view').value;
const resultsPerPage = document.getElementById('results-per-page').value;
const searchHistory = document.getElementById('search-history').checked;
const usageAnalytics = document.getElementById('usage-analytics').checked;
// 更新设置
const { error } = await window.supabaseClient
.from('user_settings')
.upsert({
user_id: user.id,
default_view: defaultView,
results_per_page: resultsPerPage,
save_search_history: searchHistory,
usage_analytics: usageAnalytics,
updated_at: new Date()
});
if (error) {
console.error('Error saving advanced settings:', error);
showAlert('保存高级设置失败', 'error');
return;
}
showAlert('高级设置已保存', 'success');
}
} catch (error) {
console.error('Error saving advanced settings:', error);
showAlert('保存高级设置时出错', 'error');
}
}
/**
* 退出登录
*/
async function logout() {
try {
if (window.supabaseClient) {
const { error } = await window.supabaseClient.auth.signOut();
if (error) {
console.error('Error signing out:', error);
showAlert('退出登录失败', 'error');
return;
}
// 重定向到首页
window.location.href = 'index.html';
}
} catch (error) {
console.error('Error signing out:', error);
showAlert('退出登录时出错', 'error');
}
}
/**
* 显示提示信息
* @param {string} message - 提示消息
* @param {string} type - 提示类型 (success, info, warning, error)
*/
function showAlert(message, type = 'info') {
// 创建提示元素
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3`;
alertDiv.style.zIndex = '9999';
alertDiv.style.maxWidth = '90%';
alertDiv.style.width = '400px';
// 添加提示内容
alertDiv.innerHTML = `
${message}
`;
// 添加到页面
document.body.appendChild(alertDiv);
// 自动关闭
setTimeout(() => {
const bsAlert = new bootstrap.Alert(alertDiv);
bsAlert.close();
}, 5000);
}