document.addEventListener("DOMContentLoaded", () => {
    let students = [];
    let scores = {};

    // 读取 Excel 文件
    document.getElementById('fileInput').addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });

            // 将数据转化为学生对象
            students = jsonData.slice(1).map(row => ({
                id: row[0],
                name: row[1],
                score: 0 // 初始积分为0
            }));

            // 初始化每个学生的积分
            students.forEach(student => {
                scores[student.id] = 0;
            });

            console.log('学生名单加载成功:', students);
            document.getElementById('normalModeButton').classList.remove('hidden');
            document.getElementById('advancedModeButton').classList.remove('hidden');
            document.getElementById('viewRankButton').classList.remove('hidden');
        };

        reader.readAsArrayBuffer(file);
    });

    // 普通模式按钮
    document.getElementById('normalModeButton').addEventListener('click', () => {
        selectStudent('普通模式');
    });

    // 进阶模式按钮
    document.getElementById('advancedModeButton').addEventListener('click', () => {
        selectStudent('进阶模式');
    });

    // 查看积分排行榜
    document.getElementById('viewRankButton').addEventListener('click', () => {
        displayRankTable();
    });

    // 退出按钮
    document.getElementById('exitButton').addEventListener('click', () => {
        window.close(); // 关闭网页
    });

    // 随机选择学生
    function selectStudent(mode) {
        if (students.length === 0) {
            alert('学生名单尚未加载！');
            return;
        }

        const selectedStudent = students[Math.floor(Math.random() * students.length)];
        const studentInfo = document.getElementById('studentInfo');
        studentInfo.classList.remove('hidden');

        // 随机生成积分(1-3分)作为示例
        const pointsEarned = Math.random() > 0.5 ? 1 : Math.floor(Math.random() * 3) + 1;
        updateScore(selectedStudent.id, pointsEarned); // 更新积分

        // 动态显示学生信息和积分变化
        studentInfo.innerHTML = `
            模式: ${mode}<br>姓名: ${selectedStudent.name}<br>学号: ${selectedStudent.id}<br>
            <span class="points-earned">获得积分: ${pointsEarned} 分</span>
        `;

        // 添加动画效果
        const pointsSpan = document.querySelector('.points-earned');
        pointsSpan.style.animation = 'pop-in 0.5s ease';

        // 延时移除动画效果
        setTimeout(() => {
            pointsSpan.style.animation = '';
        }, 500);
    }

    // 更新学生积分
    function updateScore(studentId, points) {
        scores[studentId] += points;
        console.log('更新积分:', scores);
    }

    // 显示积分排行榜，从高到低排序
    function displayRankTable() {
        const rankList = document.getElementById('rankList');
        rankList.innerHTML = '';

        // 按积分从高到低排序
        const sortedStudents = students.sort((a, b) => scores[b.id] - scores[a.id]);

        sortedStudents.forEach(student => {
            const tr = document.createElement('tr');
            const tdId = document.createElement('td');
            tdId.textContent = student.id;

            const tdName = document.createElement('td');
            tdName.textContent = student.name;

            const tdScore = document.createElement('td');
            tdScore.textContent = scores[student.id];

            tr.appendChild(tdId);
            tr.appendChild(tdName);
            tr.appendChild(tdScore);
            rankList.appendChild(tr);
        });

        document.getElementById('rankTable').classList.remove('hidden');
    }
});
