(function () {
  const datesModule = (typeof require === 'function')
    ? require('./dates.js')
    : (typeof window !== 'undefined' ? window.dates : null);
  const { timeToMinutes } = datesModule;

  function indexBy(items, key) {
    return new Map((items || []).map((item) => [item[key], item]));
  }

  function buildMappings({ classes, courses, teachers, classrooms }) {
    return {
      classes: indexBy(classes, 'id'),
      courses: indexBy(courses, 'id'),
      teachers: indexBy(teachers, 'id'),
      classrooms: indexBy(classrooms, 'id')
    };
  }

  function classLabel(mappings, classId) {
    const cls = mappings.classes.get(classId);
    if (!cls) return '未知班级';
    const course = mappings.courses.get(cls.course_id);
    return course ? `${cls.name} · ${course.name}` : cls.name;
  }

  function scheduleForm(mappings, record) {
    const cls = mappings.classes.get(record.class_id) || {};
    const course = mappings.courses.get(cls.course_id) || {};
    const teacher = mappings.teachers.get(record.teacher_id) || {};
    const classroom = mappings.classrooms.get(record.classroom_id) || {};
    return {
      ...record,
      className: classLabel(mappings, record.class_id),
      courseName: course.name || '未关联课程',
      teacherName: teacher.name || '未指定教师',
      classroomName: classroom.name || '未指定教室'
    };
  }

  function validateForm(values, options = {}) {
    const { availableTimePoints = [] } = options;
    const errors = {};
    for (const field of ['class_id', 'schedule_date', 'start_time', 'topic', 'classroom_id', 'teacher_id', 'status']) {
      if (!values[field]) errors[field] = '该字段为必填项';
    }
    if (values.start_time && availableTimePoints.length && !availableTimePoints.includes(values.start_time)) {
      errors.start_time = '请选择有效的时间点';
    }
    return errors;
  }

  const exports_ = { buildMappings, classLabel, scheduleForm, validateForm };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = exports_;
  }

  if (typeof window !== 'undefined') {
    window.mapping = exports_;
  }
})();