import { StudentEnrollment } from '../entities/student-enrollment.entity';
import { esc } from './archive-report.helpers';

export function buildEnrollmentSection(enrollments: StudentEnrollment[]): string {
  if (enrollments.length === 0) return '';

  const renderEnrollmentTable = (enrs: StudentEnrollment[]): string => {
    if (enrs.length === 0) return '';

    let rows = '';
    for (const e of enrs) {
      rows += `<tr>
          <td>${esc(e.courseCategory || '-')}</td>
          <td>${esc(e.classType || '-')}</td>
          <td>${esc(e.className || '-')}</td>
          <td>${esc(e.headTeacher || '-')}</td>
          <td>${esc(e.subjectTeacher || '-')}</td>
          <td class="nowrap">${esc(e.startDate || '-')}</td>
          <td class="nowrap">${esc(e.endDate || '-')}</td>
        </tr>`;
    }

    return `<table class="data-table">
        <thead><tr>
          <th>课程类别</th><th>班型</th><th>班级</th>
          <th>班主任</th><th>任课老师</th><th>开班日期</th><th>结课日期</th>
        </tr></thead>
        <tbody>${rows}</tbody>
      </table>`;
  };

  // Multi-enrollment: split culture vs professional
  const cultureEnrollments = enrollments.filter(
    (e) => e.courseCategory && e.courseCategory.includes('文化'),
  );
  const profEnrollments = enrollments.filter(
    (e) => e.courseCategory && e.courseCategory.includes('专业'),
  );
  const otherEnrollments = enrollments.filter(
    (e) =>
      !e.courseCategory ||
      (!e.courseCategory.includes('文化') && !e.courseCategory.includes('专业')),
  );

  const cultureTable = renderEnrollmentTable(cultureEnrollments);
  const profTable = renderEnrollmentTable(profEnrollments);
  const otherTable = renderEnrollmentTable(otherEnrollments);

  let html = '<div class="card" style="margin-bottom:14px;"><h3>报读记录</h3>';
  if (cultureTable && profTable) {
    html += '<div class="grid-2" style="gap:14px;">';
    html += `<div><h3 style="font-size:13px;margin-bottom:8px;">文化课报读</h3>${cultureTable}</div>`;
    html += `<div><h3 style="font-size:13px;margin-bottom:8px;">专业课报读</h3>${profTable}</div>`;
    html += '</div>';
  } else {
    if (cultureTable) html += `<h3 style="font-size:13px;margin:0 0 8px;">文化课报读</h3>${cultureTable}`;
    if (profTable) html += `<h3 style="font-size:13px;margin:0 0 8px;">专业课报读</h3>${profTable}`;
  }
  if (otherTable) html += `<h3 style="font-size:13px;margin:10px 0 8px;">其他报读</h3>${otherTable}`;
  html += '</div>';
  return html;
}
