// Toast 提示函数
function showToast(message, type = 'info', duration = 3000) {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;

    const icons = {
        success: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        error: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        info: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/><path d="M12 16V12M12 8H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
    };

    toast.innerHTML = `
        <span class="toast-icon">${icons[type]}</span>
        <span>${message}</span>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('hiding');
        setTimeout(() => {
            container.removeChild(toast);
        }, 300);
    }, duration);
}

// 自定义确认对话框
let modalCallback = null;

function showConfirm(title, message, confirmText = '确定', confirmClass = '', iconType = '', callback) {
    const modal = document.getElementById('confirm-modal');
    const iconEl = document.getElementById('modal-icon');
    const titleEl = document.getElementById('modal-title');
    const messageEl = document.getElementById('modal-message');
    const confirmBtn = document.getElementById('modal-confirm');
    const cancelBtn = document.getElementById('modal-cancel');

    // 图标定义
    const icons = {
        warning: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#faad14" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        info: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="#1890ff" stroke-width="2"/><path d="M12 16V12M12 8H12.01" stroke="#1890ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        delete: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 7L18.1327 19.1425C18.0579 20.1891 17.187 21 16.1378 21H7.86218C6.81299 21 5.94208 20.1891 5.86732 19.1425L5 7M10 11V17M14 11V17M15 7V4C15 3.44772 14.5523 3 14 3H10C9.44772 3 9 3.44772 9 4V7M4 7H20" stroke="#ff4d4f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        logout: `<svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M14 8V7C14 5.34315 12.6569 4 11 4H6C4.34315 4 3 5.34315 3 7V17C3 18.6569 4.34315 20 6 20H11C12.6569 20 14 18.6569 14 17V16M17 12H10M17 12L14 9M17 12L14 15" stroke="#2468ad" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
    };

    if (iconType && icons[iconType]) {
        iconEl.innerHTML = icons[iconType];
        iconEl.style.display = 'block';
        iconEl.className = 'modal-icon ' + iconType;
    } else {
        iconEl.style.display = 'none';
    }

    titleEl.textContent = title;
    messageEl.textContent = message;
    confirmBtn.textContent = confirmText;
    confirmBtn.className = 'modal-btn confirm ' + confirmClass;

    modalCallback = callback;

    modal.classList.add('active');
}

// 绑定对话框按钮事件
document.getElementById('modal-confirm').addEventListener('click', function() {
    const modal = document.getElementById('confirm-modal');
    modal.classList.remove('active');
    if (modalCallback) {
        modalCallback(true);
        modalCallback = null;
    }
});

document.getElementById('modal-cancel').addEventListener('click', function() {
    const modal = document.getElementById('confirm-modal');
    modal.classList.remove('active');
    if (modalCallback) {
        modalCallback(false);
        modalCallback = null;
    }
});

// 点击遮罩层关闭对话框
document.getElementById('confirm-modal').addEventListener('click', function(e) {
    if (e.target === this) {
        this.classList.remove('active');
        if (modalCallback) {
            modalCallback(false);
            modalCallback = null;
        }
    }
});

// 检查登录状态
function checkLogin() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return false;
    }
    return true;
}

// 退出登录
function logout() {
    showConfirm('退出登录', '确定要退出登录吗？', '退出', 'logout', 'logout', function(confirmed) {
        if (confirmed) {
            // 清除本地存储的 token 和用户信息
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            // 跳转到登录页面
            window.location.href = 'login.html';
        }
    });
}

// 绑定退出登录按钮事件
document.getElementById('logout-btn').addEventListener('click', logout);

// 初始化页面
function initPage() {
    if (!checkLogin()) return;
    
    // 设置默认日期为今天
    document.getElementById('date').valueAsDate = new Date();
    
    // 加载数据
    loadRecords();
    loadStats();
    
    // 标签切换
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有标签的active类
            document.querySelectorAll('.nav-item').forEach(nav => nav.classList.remove('active'));
            // 添加当前标签的active类
            this.classList.add('active');
            
            // 隐藏所有内容
            document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');
            // 显示当前标签对应的内容
            const tab = this.getAttribute('data-tab');
            document.getElementById(tab + '-tab').style.display = 'block';
            
            // 切换到历史标签时加载记录
            if (tab === 'history') {
                loadRecords();
                // 清除记账表单状态，防止编辑状态干扰新增
                clearAddForm();
            }
            // 切换到统计标签时加载统计数据
            if (tab === 'stats') {
                loadStats();
                // 清除记账表单状态，防止编辑状态干扰新增
                clearAddForm();
            }
            // 切换到账户标签时加载账户列表
            if (tab === 'accounts') {
                loadAccounts();
                // 清除记账表单状态，防止编辑状态干扰新增
                clearAddForm();
            }
        });
    });
    
    // 查询按钮点击事件
    document.getElementById('search-btn').addEventListener('click', function() {
        loadRecords();
    });
    
    // 保存所有分类选项
    const allCategories = [];
    const categorySelect = document.getElementById('category');
    const originalOptions = categorySelect.querySelectorAll('option');
    originalOptions.forEach(option => {
        allCategories.push({
            value: option.value,
            text: option.textContent,
            type: option.getAttribute('data-type')
        });
    });
    
    // 类型选择
    document.querySelectorAll('.type-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有按钮的active类
            document.querySelectorAll('.type-btn').forEach(b => b.classList.remove('active'));
            // 添加当前按钮的active类
            this.classList.add('active');
            
            // 过滤分类选项
            const selectedType = this.getAttribute('data-type');
            
            // 清空选择框
            categorySelect.innerHTML = '';
            
            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择分类';
            categorySelect.appendChild(defaultOption);
            
            // 添加对应类型的分类选项
            allCategories.forEach(category => {
                if (category.type === selectedType) {
                    const option = document.createElement('option');
                    option.value = category.value;
                    option.textContent = category.text;
                    option.setAttribute('data-type', category.type);
                    categorySelect.appendChild(option);
                }
            });
            
            // 检查本地缓存中是否有对应类型的分类
            const savedCategory = localStorage.getItem('lastRecordCategory');
            const savedAccount = localStorage.getItem('lastRecordAccount');
            
            // 设置分类：优先使用缓存，否则使用默认值
            let categorySet = false;
            if (savedCategory) {
                for (let i = 0; i < categorySelect.options.length; i++) {
                    if (categorySelect.options[i].value === savedCategory) {
                        categorySelect.selectedIndex = i;
                        categorySet = true;
                        break;
                    }
                }
            }
            
            // 如果没有缓存或缓存的分类不存在，使用默认分类
            if (!categorySet) {
                for (let i = 0; i < categorySelect.options.length; i++) {
                    if ((selectedType === 'expense' && categorySelect.options[i].value === '餐饮') ||
                        (selectedType === 'income' && categorySelect.options[i].value === '工资')) {
                        categorySelect.selectedIndex = i;
                        break;
                    }
                }
            }
            
            // 设置账户：优先使用缓存，否则使用默认值
            const accountSelect = document.getElementById('account');
            let accountSet = false;
            if (savedAccount) {
                for (let i = 0; i < accountSelect.options.length; i++) {
                    if (accountSelect.options[i].value === savedAccount) {
                        accountSelect.selectedIndex = i;
                        accountSet = true;
                        break;
                    }
                }
            }
            
            // 如果没有缓存或缓存的账户不存在，使用默认账户
            if (!accountSet) {
                for (let i = 0; i < accountSelect.options.length; i++) {
                    if (accountSelect.options[i].value === '现金') {
                        accountSelect.selectedIndex = i;
                        break;
                    }
                }
            }
        });
    });
    
    // 初始过滤分类选项
    const initialType = document.querySelector('.type-btn.active').getAttribute('data-type');
    
    // 清空选择框
    categorySelect.innerHTML = '';
    
    // 添加默认选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = '请选择分类';
    categorySelect.appendChild(defaultOption);
    
    // 添加对应类型的分类选项
    allCategories.forEach(category => {
        if (category.type === initialType) {
            const option = document.createElement('option');
            option.value = category.value;
            option.textContent = category.text;
            option.setAttribute('data-type', category.type);
            categorySelect.appendChild(option);
        }
    });
    
    // 加载本地缓存的分类和账户选择
    function loadSavedSelection() {
        const savedType = localStorage.getItem('lastRecordType') || initialType;
        const savedCategory = localStorage.getItem('lastRecordCategory');
        const savedAccount = localStorage.getItem('lastRecordAccount');
        
        // 切换到保存的类型
        document.querySelector(`.type-btn[data-type="${savedType}"]`).click();
        
        // 选择保存的分类
        if (savedCategory) {
            const categorySelect = document.getElementById('category');
            for (let i = 0; i < categorySelect.options.length; i++) {
                if (categorySelect.options[i].value === savedCategory) {
                    categorySelect.selectedIndex = i;
                    break;
                }
            }
        } else {
            // 设置默认分类
            const categorySelect = document.getElementById('category');
            for (let i = 0; i < categorySelect.options.length; i++) {
                if ((savedType === 'expense' && categorySelect.options[i].value === '餐饮') ||
                    (savedType === 'income' && categorySelect.options[i].value === '工资')) {
                    categorySelect.selectedIndex = i;
                    break;
                }
            }
        }
        
        // 选择保存的账户或默认账户
        setTimeout(() => {
            const accountSelect = document.getElementById('account');
            if (savedAccount) {
                for (let i = 0; i < accountSelect.options.length; i++) {
                    if (accountSelect.options[i].value === savedAccount) {
                        accountSelect.selectedIndex = i;
                        break;
                    }
                }
            } else {
                // 设置默认账户为现金
                for (let i = 0; i < accountSelect.options.length; i++) {
                    if (accountSelect.options[i].value === '现金') {
                        accountSelect.selectedIndex = i;
                        break;
                    }
                }
            }
        }, 500); // 等待账户选项加载完成
    }
    
    // 页面加载完成后加载保存的选择
    setTimeout(loadSavedSelection, 1000);
    
    // 保存记录
    document.querySelector('.submit-btn').addEventListener('click', function() {
        const type = document.querySelector('.type-btn.active').getAttribute('data-type');
        const amount = document.getElementById('amount').value;
        const category = document.getElementById('category').value;
        const date = document.getElementById('date').value;
        const remark = document.getElementById('remark').value;
        const account = document.getElementById('account').value;
        const submitBtn = this;
        const recordId = submitBtn.dataset.recordId;
        
        if (!amount || !category || !account) {
            showToast('请填写金额、分类和账户', 'error');
            return;
        }
        
        // 显示加载状态
        submitBtn.textContent = '保存中...';
        submitBtn.disabled = true;
        
        // 构建请求数据
        const requestData = { type, amount, category, date, remark, account };
        if (recordId) {
            requestData.id = recordId;
        }
        
        // 确定API路径
        const apiPath = recordId ? '/ask/edit_record.api' : '/ask/add_record.api';
        
        // 调用API
        fetch(apiPath, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                showToast(recordId ? '记录更新成功！' : '记录保存成功！', 'success');
                
                // 保存用户选择到本地缓存
                localStorage.setItem('lastRecordType', type);
                localStorage.setItem('lastRecordCategory', category);
                localStorage.setItem('lastRecordAccount', account);
                
                // 清空表单（保留分类选择）
                document.getElementById('amount').value = '';
                document.getElementById('date').valueAsDate = new Date();
                document.getElementById('remark').value = '';
                // 重置按钮状态
                delete submitBtn.dataset.recordId;
                submitBtn.textContent = '保存记录';
                // 重新加载记录和统计数据
                loadRecords();
                loadStats();
            } else {
                showToast('操作失败：' + data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('操作失败，请稍后重试', 'error');
            console.error('操作错误:', error);
        })
        .finally(() => {
            // 恢复按钮状态
            if (!recordId) {
                submitBtn.textContent = '保存记录';
            }
            submitBtn.disabled = false;
        });
    });
}

// 加载记账记录
function loadRecords() {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    // 获取时间范围
    const startDate = document.getElementById('start-date')?.value || '';
    const endDate = document.getElementById('end-date')?.value || '';
    
    // 构建查询参数
    let url = '/ask/get_records.api';
    const params = [];
    if (startDate) params.push(`start_date=${startDate}`);
    if (endDate) params.push(`end_date=${endDate}`);
    if (params.length > 0) url += '?' + params.join('&');
    
    fetch(url, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderRecords(data.data);
        } else {
            console.error('加载记录失败:', data.msg);
        }
    })
    .catch(error => {
        console.error('加载记录错误:', error);
    });
}

// 渲染记账记录
function renderRecords(records) {
    const historyList = document.getElementById('history-list');
    // 清空现有记录
    historyList.innerHTML = '';
    
    if (records.length === 0) {
        historyList.innerHTML = '<div style="text-align: center; padding: 20px; color: #6c757d;">暂无记录</div>';
        return;
    }
    
    // 渲染记录
    records.forEach(record => {
        const item = document.createElement('div');
        item.className = `history-item ${record.FType}`;
        
        // 创建编辑按钮
        const editBtn = document.createElement('button');
        editBtn.className = 'action-btn edit-btn';
        editBtn.textContent = '编辑';
        editBtn.onclick = function() {
            editRecord(record);
        };
        
        // 创建删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'action-btn delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.onclick = function() {
            deleteRecord(record.FId);
        };
        
        // 创建actions容器
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'actions';
        actionsDiv.appendChild(editBtn);
        actionsDiv.appendChild(deleteBtn);
        
        // 设置item内容
        item.innerHTML = `
            <div class="info">
                <div class="category">${record.FCategory}</div>
                <div class="date">${record.FDate}</div>
            </div>
            <div class="amount">${record.FType === 'income' ? '+' : '-' }¥${parseFloat(record.FAmount).toFixed(2)}</div>
        `;
        
        // 添加actions容器
        item.appendChild(actionsDiv);
        historyList.appendChild(item);
    });
}

// 清除记账表单
function clearAddForm() {
    // 清空表单数据
    document.getElementById('amount').value = '';
    document.getElementById('category').value = '';
    document.getElementById('date').valueAsDate = new Date();
    document.getElementById('remark').value = '';

    // 重置按钮状态
    const submitBtn = document.querySelector('.submit-btn');
    delete submitBtn.dataset.recordId;
    submitBtn.textContent = '保存记录';

    // 重置类型为支出
    document.querySelector('.type-btn[data-type="expense"]').click();
}

// 编辑记录
function editRecord(record) {
    // 切换到记账标签
    document.querySelector('.nav-item[data-tab="add"]').click();

    // 填充表单数据
    document.querySelector(`.type-btn[data-type="${record.FType}"]`).click();
    document.getElementById('amount').value = record.FAmount;
    document.getElementById('category').value = record.FCategory;

    // 处理日期格式 - 确保是 YYYY-MM-DD 格式
    let dateValue = record.FDate;
    if (dateValue) {
        // 如果日期包含时间部分，只取日期部分
        if (dateValue.includes(' ')) {
            dateValue = dateValue.split(' ')[0];
        }
        // 如果日期是其他格式，尝试转换
        if (dateValue.includes('/')) {
            const parts = dateValue.split('/');
            if (parts.length === 3) {
                dateValue = `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
            }
        }
        document.getElementById('date').value = dateValue;
    }

    document.getElementById('remark').value = record.FRemark || '';

    // 保存记录ID到表单
    document.querySelector('.submit-btn').dataset.recordId = record.FId;
    document.querySelector('.submit-btn').textContent = '更新记录';

    // 显示提示
    showToast('已加载记录，请修改后保存', 'info');
}

// 删除记录
function deleteRecord(id) {
    showConfirm('删除记录', '确定要删除这条记录吗？删除后无法恢复。', '删除', '', 'delete', function(confirmed) {
        if (confirmed) {
            fetch('/ask/delete_record.api', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                body: JSON.stringify({ id: id })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('记录删除成功！', 'success');
                    // 重新加载记录和统计数据
                    loadRecords();
                    loadStats();
                } else {
                    showToast('删除失败：' + data.msg, 'error');
                }
            })
            .catch(error => {
                showToast('删除失败，请稍后重试', 'error');
                console.error('删除错误:', error);
            });
        }
    });
}

// 加载统计数据
function loadStats() {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    fetch('/ask/get_stats.api', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderStats(data.data);
            // 更新余额
            document.querySelector('.balance-amount').textContent = '¥' + parseFloat(data.data.balance).toFixed(2);
        } else {
            console.error('加载统计数据失败:', data.msg);
        }
    })
    .catch(error => {
        console.error('加载统计数据错误:', error);
    });
}

// 渲染统计数据
function renderStats(stats) {
    const statsContainer = document.querySelector('#stats-tab .card');
    // 清空现有数据
    statsContainer.innerHTML = '<div class="card-title">本月统计</div>';
    
    // 渲染统计卡片
    statsContainer.innerHTML += `
        <div class="stats-grid">
            <div class="stat-card income">
                <div class="stat-label">总收入</div>
                <div class="stat-value">¥${parseFloat(stats.income).toFixed(2)}</div>
            </div>
            
            <div class="stat-card expense">
                <div class="stat-label">总支出</div>
                <div class="stat-value">¥${parseFloat(stats.expense).toFixed(2)}</div>
            </div>
        </div>
        
        <div class="summary-card">
            <div class="summary-item">
                <div class="summary-label">结余</div>
                <div class="summary-value">¥${parseFloat(stats.balance).toFixed(2)}</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">日均支出</div>
                <div class="summary-value">¥${parseFloat(stats.daily_expense).toFixed(2)}</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">最大支出</div>
                <div class="summary-value">¥${parseFloat(stats.max_expense).toFixed(2)}</div>
            </div>
        </div>
    `;
    
    // 渲染账户统计
    renderAccountStats();
}

// 渲染账户统计
function renderAccountStats() {
    const accountStatsContainer = document.getElementById('account-stats');
    // 清空现有数据
    accountStatsContainer.innerHTML = '';
    
    const token = localStorage.getItem('token');
    if (!token) return;
    
    fetch('/ask/get_accounts.api', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            const accounts = data.data;
            
            // 计算总余额
            const totalBalance = accounts.reduce((sum, account) => sum + parseFloat(account.balance || 0), 0);
            
            // 渲染账户列表
            accounts.forEach(account => {
                const item = document.createElement('div');
                item.className = 'history-item';
                
                item.innerHTML = `
                    <div class="info">
                        <div class="category">${account.name}</div>
                    </div>
                    <div class="amount">¥${parseFloat(account.balance || 0).toFixed(2)}</div>
                `;
                
                accountStatsContainer.appendChild(item);
            });
            
            // 渲染总余额
            const totalItem = document.createElement('div');
            totalItem.className = 'history-item';
            totalItem.style.fontWeight = 'bold';
            totalItem.style.borderTop = '1px solid #eaeaea';
            totalItem.style.marginTop = '10px';
            totalItem.style.paddingTop = '10px';
            
            totalItem.innerHTML = `
                <div class="info">
                    <div class="category">总余额</div>
                </div>
                <div class="amount">¥${parseFloat(totalBalance).toFixed(2)}</div>
            `;
            
            accountStatsContainer.appendChild(totalItem);
        }
    })
    .catch(error => {
        console.error('加载账户统计错误:', error);
    });
}

// 加载账户列表
function loadAccounts() {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    fetch('/ask/get_accounts.api', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderAccounts(data.data);
        } else {
            console.error('加载账户失败:', data.msg);
        }
    })
    .catch(error => {
        console.error('加载账户错误:', error);
    });
}

// 渲染账户列表
function renderAccounts(accounts) {
    const accountsList = document.getElementById('accounts-list');
    // 清空现有账户
    accountsList.innerHTML = '';
    
    if (accounts.length === 0) {
        accountsList.innerHTML = '<div style="text-align: center; padding: 20px; color: #6c757d;">暂无账户</div>';
        return;
    }
    
    // 渲染账户
    accounts.forEach(account => {
        const item = document.createElement('div');
        item.className = 'history-item';
        
        // 创建编辑按钮
        const editBtn = document.createElement('button');
        editBtn.className = 'action-btn edit-btn';
        editBtn.textContent = '编辑';
        editBtn.onclick = function() {
            editAccount(account);
        };
        
        // 创建删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'action-btn delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.onclick = function() {
            deleteAccount(account.id);
        };
        
        // 创建actions容器
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'actions';
        actionsDiv.appendChild(editBtn);
        actionsDiv.appendChild(deleteBtn);
        
        // 设置item内容
        item.innerHTML = `
            <div class="info">
                <div class="category">${account.name}</div>
                <div class="date">余额: ¥${parseFloat(account.balance).toFixed(2)}</div>
            </div>
        `;
        
        // 添加actions容器
        item.appendChild(actionsDiv);
        accountsList.appendChild(item);
    });
}

// 显示添加账户模态框
function showAddAccountModal() {
    // 这里可以实现添加账户的模态框
    // 为了简化，这里直接使用prompt获取账户名称
    const accountName = prompt('请输入账户名称:');
    if (accountName && accountName.trim() !== '') {
        addAccount(accountName.trim());
    }
}

// 添加账户
function addAccount(name) {
    const token = localStorage.getItem('token');
    if (!token) return;
    
    fetch('/ask/add_account.api', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        },
        body: JSON.stringify({ name: name })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            showToast('账户添加成功！', 'success');
            // 重新加载账户列表
            loadAccounts();
            // 重新加载账户选择下拉框
            loadAccountOptions();
        } else {
            showToast('添加失败：' + data.msg, 'error');
        }
    })
    .catch(error => {
        showToast('操作失败，请稍后重试', 'error');
        console.error('添加账户错误:', error);
    });
}

// 编辑账户
function editAccount(account) {
    const newName = prompt('请输入新的账户名称:', account.name);
    if (newName && newName.trim() !== '') {
        const token = localStorage.getItem('token');
        if (!token) return;
        
        fetch('/ask/edit_account.api', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            },
            body: JSON.stringify({ id: account.id, name: newName.trim() })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                showToast('账户更新成功！', 'success');
                // 重新加载账户列表
                loadAccounts();
                // 重新加载账户选择下拉框
                loadAccountOptions();
            } else {
                showToast('更新失败：' + data.msg, 'error');
            }
        })
        .catch(error => {
            showToast('操作失败，请稍后重试', 'error');
            console.error('编辑账户错误:', error);
        });
    }
}

// 删除账户
function deleteAccount(id) {
    showConfirm('删除账户', '确定要删除这个账户吗？删除后相关记录可能会受影响。', '删除', '', 'delete', function(confirmed) {
        if (confirmed) {
            const token = localStorage.getItem('token');
            if (!token) return;
            
            fetch('/ask/delete_account.api', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
                body: JSON.stringify({ id: id })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showToast('账户删除成功！', 'success');
                    // 重新加载账户列表
                    loadAccounts();
                    // 重新加载账户选择下拉框
                    loadAccountOptions();
                } else {
                    showToast('删除失败：' + data.msg, 'error');
                }
            })
            .catch(error => {
                showToast('操作失败，请稍后重试', 'error');
                console.error('删除账户错误:', error);
            });
        }
    });
}

// 加载账户选择选项
function loadAccountOptions() {
    const accountSelect = document.getElementById('account');
    // 清空选择框
    accountSelect.innerHTML = '';
    
    // 添加默认选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = '请选择账户';
    accountSelect.appendChild(defaultOption);
    
    const token = localStorage.getItem('token');
    if (!token) return;
    
    fetch('/ask/get_accounts.api', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 添加账户选项
            data.data.forEach(account => {
                const option = document.createElement('option');
                option.value = account.name;
                option.textContent = account.name;
                accountSelect.appendChild(option);
            });
        }
    })
    .catch(error => {
        console.error('加载账户选项错误:', error);
    });
}

// 绑定添加账户按钮事件
document.getElementById('add-account-btn').addEventListener('click', showAddAccountModal);

// 编辑记录时包含账户信息
function editRecord(record) {
    // 切换到记账标签
    document.querySelector('.nav-item[data-tab="add"]').click();

    // 填充表单数据
    document.querySelector(`.type-btn[data-type="${record.FType}"]`).click();
    document.getElementById('amount').value = record.FAmount;
    document.getElementById('category').value = record.FCategory;
    document.getElementById('account').value = record.FAccount || '现金';

    // 处理日期格式 - 确保是 YYYY-MM-DD 格式
    let dateValue = record.FDate;
    if (dateValue) {
        // 如果日期包含时间部分，只取日期部分
        if (dateValue.includes(' ')) {
            dateValue = dateValue.split(' ')[0];
        }
        // 如果日期是其他格式，尝试转换
        if (dateValue.includes('/')) {
            const parts = dateValue.split('/');
            if (parts.length === 3) {
                dateValue = `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
            }
        }
        document.getElementById('date').value = dateValue;
    }

    document.getElementById('remark').value = record.FRemark || '';

    // 保存记录ID到表单
    document.querySelector('.submit-btn').dataset.recordId = record.FId;
    document.querySelector('.submit-btn').textContent = '更新记录';

    // 显示提示
    showToast('已加载记录，请修改后保存', 'info');
}

// 清除记账表单时重置账户选择
function clearAddForm() {
    // 清空表单数据
    document.getElementById('amount').value = '';
    document.getElementById('category').value = '';
    document.getElementById('account').value = '';
    document.getElementById('date').valueAsDate = new Date();
    document.getElementById('remark').value = '';

    // 重置按钮状态
    const submitBtn = document.querySelector('.submit-btn');
    delete submitBtn.dataset.recordId;
    submitBtn.textContent = '保存记录';

    // 重置类型为支出
    document.querySelector('.type-btn[data-type="expense"]').click();
}

// 页面加载完成后初始化
window.onload = function() {
    initPage();
    // 加载账户选项
    loadAccountOptions();
};
