const axios = require('axios');
require('dotenv').config();

const API_BASE_URL = process.env.API_BASE_URL;
const AUTHORIZATION = process.env.AUTHORIZATION;

// 查询橙子老师上周整体出勤率
async function getTeacherAttendanceRate() {
  try {
    console.log('🔍 正在查询橙子老师上周整体出勤率...');
    const response = await axios.get(`${API_BASE_URL}/reports/teacher-attendance-rates`, {
      headers: {
        'Authorization': AUTHORIZATION
      },
      params: {
        teacher_name: '橙子（程城）',
        begin_date: '2026-04-21',
        end_date: '2026-04-27'
      }
    });

    console.log('✅ 整体出勤率数据获取成功：');
    console.log(JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    console.error('❌ 查询失败：', error.response ? error.response.data : error.message);
    return null;
  }
}

// 查询上周每天的详细课程和学生出勤明细
async function getDailyTeachingSchedule() {
  const dates = [
    '2026-04-21', '2026-04-22', '2026-04-23', '2026-04-24',
    '2026-04-25', '2026-04-26', '2026-04-27'
  ];

  const allData = [];

  for (const date of dates) {
    try {
      console.log(`\n🔍 正在查询 ${date} 的课程明细...`);
      const response = await axios.get(`${API_BASE_URL}/reports/teaching-schedule`, {
        headers: {
          'Authorization': AUTHORIZATION
        },
        params: {
          teacher_name: '橙子（程城）',
          teaching_date: date
        }
      });

      if (response.data.code === 0 && response.data.data.items.length > 0) {
        allData.push({
          date: date,
          courses: response.data.data.items
        });
        console.log(`✅ ${date} 找到 ${response.data.data.items.length} 节课`);
      } else {
        console.log(`ℹ️ ${date} 没有课程安排`);
      }
    } catch (error) {
      console.error(`❌ 查询 ${date} 失败：`, error.response ? error.response.data : error.message);
    }
  }

  return allData;
}

// 主函数
async function main() {
  // 1. 获取整体出勤率
  const overallRate = await getTeacherAttendanceRate();

  // 2. 获取每日明细
  const dailyDetails = await getDailyTeachingSchedule();

  // 3. 汇总数据并保存
  const result = {
    query_range: '2026-04-21 至 2026-04-27',
    teacher_name: '橙子（程城）',
    overall_attendance_rate: overallRate,
    daily_course_details: dailyDetails
  };

  // 保存到文件
  const fs = require('fs');
  const outputPath = '上周学生出勤原始数据.json';
  fs.writeFileSync(outputPath, JSON.stringify(result, null, 2));

  console.log(`\n🎉 所有数据查询完成，已保存到：${outputPath}`);
  console.log('\n📊 数据摘要：');

  // 统计总出勤情况
  let totalStudents = 0;
  let attendedStudents = 0;
  let leaveStudents = 0;
  let absentStudents = 0;

  dailyDetails.forEach(day => {
    day.courses.forEach(course => {
      course.students.forEach(student => {
        totalStudents++;
        if (student.attendance_status === '✅ 出勤') attendedStudents++;
        else if (student.attendance_status === '⏸ 请假') leaveStudents++;
        else if (student.attendance_status === '❌ 缺勤') absentStudents++;
      });
    });
  });

  console.log(`- 总学生人次：${totalStudents}`);
  console.log(`- 正常出勤：${attendedStudents} 人次（${totalStudents > 0 ? ((attendedStudents / totalStudents) * 100).toFixed(2) : 0}%）`);
  console.log(`- 请假：${leaveStudents} 人次（${totalStudents > 0 ? ((leaveStudents / totalStudents) * 100).toFixed(2) : 0}%）`);
  console.log(`- 缺勤：${absentStudents} 人次（${totalStudents > 0 ? ((absentStudents / totalStudents) * 100).toFixed(2) : 0}%）`);
}

main();
