Page({
  data:{
    modalVisible1:false,
    modalVisible2:false,
    modalVisible3:false,
    modalVisible4:false,
    modalVisible5:false,
    modalVisible6:false,
    scoreModalVisible: false, 
    name:'',
    score:'',
    studentCount: "", // 存储输入的学生人数
    dice:0, // 默认模式
    diceImage:'/assets/img/RollClass/RollClass5_1.png', // 初始骰子图像
    roll_or_request:0,
    selectedStudents: [], // 用于存储随机选择的学生
    currentStudentIndex: null, // 当前选中学生的索引
    query: '',
    foundStudent: null, // 存储找到的学生
    students: []
  },
  onLoad() {
    const app = getApp();
    this.setData({
      students: app.globalData.students // 设置全局数据
    });
    // console.log(this.data.students); // 检查此时的学生数据
  },

  onAbout(){
    this.setData({
      modalVisible1:true,
    })
  },

  onAdd(){
    this.setData({
      modalVisible2:true,
    });
  },

  onRank(){
    wx.navigateTo({
      url: '/pages/studentRanking/studentRanking',
    });
  },

  onRoll(){
    this.setData({
      modalVisible4:true
    });
  },

  onRollCall() {
    this.setData({
      modalVisible3:true,
      roll_or_request:0
    });
  },

  onRequest() {
    this.setData({
      modalVisible3:true,
      roll_or_request:1
    });
  },

  // 加分
  addScore(event){
    const index = event.currentTarget.dataset.index; // 获取点击的学生索引
    this.setData({
      currentStudentIndex: index, // 保存当前学生索引
      modalVisible5:true
    })
  },
  // 浮窗
  closeModal(){
    this.setData({
      modalVisible1:false,
      modalVisible2:false,
      modalVisible3:false,
      modalVisible4:false,
      modalVisible5:false,
      modalVisible6:false,
      name:'',
      score:'',
      studentCount:""
    })
  },

  // 浮窗2
  onInputName(event) {
    this.setData({
      name: event.detail.value
    });
  },

  onInputScore(event) {
    this.setData({
      score: parseInt(event.detail.value) || 0 // 确保总是为数字
    });
  },

  // 查询加分
  onConfirm2() {
    const { name, score, students } = this.data;

    // 判断输入是否为数字
    const isNumeric = !isNaN(name) && name.trim() !== '';
    
    // 查找学生
    const foundStudent = students.find(student => {
        return isNumeric ? student.id === parseInt(name) : student.name === name;
    });

    if (foundStudent) {
        foundStudent.score += score; // 修改找到的学生的分数

        this.setData({
            students: [...students], // 更新页面的学生数据
            scoreInfo: { // 设置要显示的分数信息
                name: foundStudent.name,
                id: foundStudent.id,
                score: foundStudent.score
            },
            scoreModalVisible: true // 显示分数弹窗
        });

        console.log("更新后的学生数据:", foundStudent);

        // 获取全局变量并更新
        const app = getApp();
        app.globalData.students = [...students]; // 将修改后的数据同步到全局

    } 
    else {
        // 没有找到学生时显示错误弹窗
        this.setData({
            modalVisible6: true
        });
      }

    // console.log("姓名:", this.data.name);
    // console.log("得分:", this.data.score);

    // 重置输入框和隐藏弹窗
    this.setData({
        name: '',
        score: '',
        modalVisible2: false
    });
  },


  // 浮窗3
  onInputNum(event){
    this.setData({
      studentCount:event.detail.value
    });
  },

  onConfirm3() {
    const { studentCount, students } = this.data;

    if (studentCount > students.length) {
      wx.showToast({ title: '人数超出范围', icon: 'none' });
      return;
    }

    // 随机选择学生
    const selectedStudents = this.getRandomStudents(students, studentCount);
    this.setData({
      selectedStudents,studentCount: '', // 清空输入框
      modalVisible3: false // 关闭弹窗
    });

    console.log("随机选择的学生：", selectedStudents); // 打印随机选择的学生
  },

  // 随机选择学生函数
  getRandomStudents(students, count) {
    const shuffled = students.sort(() => 0.5 - Math.random()); // 打乱数组
    return shuffled.slice(0, count); // 选择前 count 个学生
  },

  // 浮窗4 投掷骰子
  onRollDice() {
    console.log("投掷骰子按钮被点击");
    // 生成1-6随机数
    const rolledValue = Math.floor(Math.random()*6)+1;
    this.setData({
      dice: rolledValue,
      diceImage: `/assets/img/RollClass/RollClass5_${rolledValue}.png`, // 更新图像
    });
  },

  // 浮窗5 加分 处理分数按钮点击
  onScoreChange(event) {
    const scoreChange = parseFloat(event.currentTarget.dataset.score);
    const { currentStudentIndex, selectedStudents } = this.data;

    if (currentStudentIndex != null) {
        selectedStudents[currentStudentIndex].score += scoreChange; // 增加分数

        // 获取全局变量
        const app = getApp();
        const students = app.globalData.students;
        students[currentStudentIndex].score = selectedStudents[currentStudentIndex].score; // 更新全局数据

        this.setData({
            selectedStudents,
            modalVisible5: false, // 关闭加分弹窗
            scoreInfo: {
                name: selectedStudents[currentStudentIndex].name,
                id: selectedStudents[currentStudentIndex].id,
                score: selectedStudents[currentStudentIndex].score
            },
            scoreModalVisible: true // 显示得分弹窗
        });

        console.log("更新后的分数：", selectedStudents[currentStudentIndex].score);
    }
  },


  // 浮窗7 得分信息
  closeScoreModal() {
    this.setData({
        scoreModalVisible: false // 隐藏得分弹窗
    });
  }

});
