// 获取URL参数
function getUrlParams() {
    const params = new URLSearchParams(window.location.search);
    return {
        groupId: params.get('groupId'),
        userName: params.get('userName'),
        robotId: params.get('robotId'),
        robotTemplate: params.get('robotTemplate'),
        d: params.get('d')
    };
}

// 格式化金额
function formatAmount(amount) {
    return parseFloat(amount).toFixed(2);
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 更新统计数据
function updateSummary(data) {
    const totalDeposit = data.deposits.reduce((sum, d) => sum + d.amount, 0);
    const totalWithdrawal = data.withdrawals.reduce((sum, w) => sum + w.amount, 0);
    const depositFee = totalDeposit * 0.05; // 5% 费率
    const withdrawalFee = totalWithdrawal * 0.0; // 0% 费率
    const shouldWithdraw = totalDeposit - depositFee;
    const currentBalance = shouldWithdraw - totalWithdrawal - withdrawalFee;

    document.getElementById('totalDeposit').textContent = formatAmount(totalDeposit);
    document.getElementById('depositFee').textContent = formatAmount(depositFee);
    document.getElementById('totalWithdrawal').textContent = formatAmount(totalWithdrawal);
    document.getElementById('withdrawalFee').textContent = formatAmount(withdrawalFee);
    document.getElementById('shouldWithdraw').textContent = formatAmount(shouldWithdraw);
    document.getElementById('currentBalance').textContent = formatAmount(currentBalance);
}

// 更新表格数据
function updateTables(data) {
    // 更新入款表格
    const depositTable = document.getElementById('depositTable').getElementsByTagName('tbody')[0];
    depositTable.innerHTML = '';
    data.deposits.forEach(deposit => {
        const row = depositTable.insertRow();
        row.insertCell(0).textContent = formatTime(deposit.time);
        row.insertCell(1).textContent = formatAmount(deposit.amount);
    });

    // 更新下发表格
    const withdrawalTable = document.getElementById('withdrawalTable').getElementsByTagName('tbody')[0];
    withdrawalTable.innerHTML = '';
    data.withdrawals.forEach(withdrawal => {
        const row = withdrawalTable.insertRow();
        row.insertCell(0).textContent = formatTime(withdrawal.time);
        row.insertCell(1).textContent = formatAmount(withdrawal.amount);
    });
}

// 加载数据
async function loadData() {
    try {
        const params = getUrlParams();
        const response = await fetch(`/api/bill?${new URLSearchParams(params)}`);
        const data = await response.json();
        
        updateSummary(data);
        updateTables(data);
    } catch (error) {
        console.error('加载数据失败:', error);
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', loadData);