const axios = require('axios');
require('dotenv').config({ path: 'E:/cc/4work_project/ClassFeedback/.env' });

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

// 查询整体出勤率
async function getTeacherAttendanceRate(beginDate, endDate) {
  try {
    console.log(`🔍 正在查询橙子老师 ${beginDate} 至 ${endDate} 整体出勤率...`);
    const response = await axios.get(`${API_BASE_URL}/reports/teacher-attendance-rates`, {
      headers: { 'Authorization': AUTHORIZATION },
      params: {
        teacher_name: '橙子（程城）',
        begin_date: beginDate,
        end_date: endDate
      }
    });
    console.log('✅ 整体出勤率数据获取成功');
    return response.data;
  } catch (error) {
    console.error('❌ 整体出勤率查询失败：', error.response ? error.response.data : error.message);
    return null;
  }
}

// 查询每日详细课程和学生出勤明细
async function getDailyTeachingSchedule(dates) {
  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} 节课`);
        
        // 打印每节课的学生出勤情况
        response.data.data.items.forEach((course, idx) => {
          console.log(`\n  📚 课程 ${idx + 1}: ${course.class_name || '未命名班级'}`);
          console.log(`     时间: ${course.teaching_begin_time} - ${course.teaching_end_time}`);
          console.log(`     学生明细:`);
          if (course.students && course.students.length > 0) {
            course.students.forEach(student => {
              const status = student.attendance_status || '❓ 未知';
              const remark = student.attendance_remark ? ` (${student.attendance_remark})` : '';
              console.log(`       - ${student.student_name}: ${status}${remark}`);
            });
          } else {
            console.log(`       (无学生数据)`);
          }
        });
      } else {
        console.log(`ℹ️ ${date} 没有课程安排`);
      }
    } catch (error) {
      console.error(`❌ 查询 ${date} 失败：`, error.response ? error.response.data : error.message);
    }
  }

  return allData;
}

// 主函数
async function main() {
  const dates = ['2026-05-15', '2026-05-16', '2026-05-17'];
  const beginDate = '2026-05-15';
  const endDate = '2026-05-17';
  
  console.log('========================================');
  console.log('  橙子老师 5月15日-5月17日 出勤查询');
  console.log('========================================\n');

  // 1. 获取整体出勤率
  const overallRate = await getTeacherAttendanceRate(beginDate, endDate);
  if (overallRate && overallRate.data && overallRate.data.数据) {
    const data = overallRate.data.数据[0];
    if (data) {
      console.log('\n📊 整体出勤率摘要:');
      console.log(`   校区: ${data.校区名称}`);
      console.log(`   综合出勤率: ${(data.综合.一次出勤率 * 100).toFixed(2)}%`);
      console.log(`   固定班应消耗课时: ${data.综合.固定班应消耗课时}`);
      console.log(`   固定班实际到课课时: ${data.综合.固定班实际到课课时}`);
      console.log(`   固定班请假课时: ${data.综合.固定班请假课时}`);
      console.log(`   固定班旷课课时: ${data.综合.固定班旷课课时}`);
    }
  }

  // 2. 获取每日明细
  console.log('\n----------------------------------------');
  console.log('  每日课程及学生出勤明细');
  console.log('----------------------------------------');
  const dailyDetails = await getDailyTeachingSchedule(dates);

  // 3. 汇总统计
  console.log('\n========================================');
  console.log('  汇总统计');
  console.log('========================================');
  
  let totalStudents = 0;
  let attendedStudents = 0;
  let leaveStudents = 0;
  let absentStudents = 0;
  let makeupStudents = 0;

  dailyDetails.forEach(day => {
    day.courses.forEach(course => {
      if (course.students) {
        course.students.forEach(student => {
          totalStudents++;
          const status = student.attendance_status || '';
          if (status.includes('出勤')) attendedStudents++;
          else if (status.includes('请假')) leaveStudents++;
          else if (status.includes('缺勤') || status.includes('旷课')) absentStudents++;
          else if (status.includes('补课')) makeupStudents++;
        });
      }
    });
  });

  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}%)`);
  console.log(`- 补课: ${makeupStudents} 人次 (${totalStudents > 0 ? ((makeupStudents / totalStudents) * 100).toFixed(2) : 0}%)`);

  // 保存到文件
  const fs = require('fs');
  const result = {
    query_range: '2026-05-15 至 2026-05-17',
    teacher_name: '橙子（程城）',
    overall_attendance_rate: overallRate,
    daily_course_details: dailyDetails
  };
  const outputPath = 'E:/cc/4work_project/ClassFeedback/data/orange_attendance_0515_0517.json';
  fs.writeFileSync(outputPath, JSON.stringify(result, null, 2));
  console.log(`\n🎉 数据已保存到: ${outputPath}`);
}

main();
