<template>
  <div class="lesson-records-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="goBack">
          <ArrowLeftOutlined />
        </a-button>
        <div class="header-info">
          <h2>课后记录</h2>
          <p class="page-desc" v-if="lessonInfo">{{ lessonInfo.className }} - 学生课堂表现评价</p>
        </div>
      </div>
      <div class="header-right">
        <a-tag :color="getStatusColor(lessonInfo?.status)">
          {{ getStatusText(lessonInfo?.status) }}
        </a-tag>
      </div>
    </div>

    <a-spin :spinning="loading">
      <div class="records-content" v-if="(students ?? []).length > 0">
        <!-- 提示信息 -->
        <div class="tip-banner">
          <BulbOutlined />
          <span>请为每个学生的课堂表现进行评分，评分范围为 1-5 分，5 分为最高分</span>
        </div>

        <!-- 学生列表 -->
        <div class="student-list">
          <div
            v-for="(student, index) in students"
            :key="student.id"
            class="student-card"
          >
            <div class="card-header">
              <div class="student-info">
                <a-avatar :style="{ backgroundColor: getAvatarColor(index) }">
                  {{ student.name.charAt(0) }}
                </a-avatar>
                <div class="student-detail">
                  <span class="student-name">{{ student.name }}</span>
                  <span class="student-gender">
                    <ManOutlined v-if="student.gender === '男'" style="color: #1890ff;" />
                    <WomanOutlined v-else style="color: #eb2f96;" />
                  </span>
                </div>
              </div>
              <div class="record-status" v-if="student.record">
                <CheckCircleFilled style="color: #52c41a;" />
                <span>已记录</span>
              </div>
            </div>

            <div class="card-body">
              <div class="rating-group">
                <div class="rating-item">
                  <span class="rating-label">
                    <EyeOutlined /> 专注度
                  </span>
                  <a-rate
                    v-model:value="records[student.id].focus"
                    allow-half
                    :count="5"
                  />
                </div>
                <div class="rating-item">
                  <span class="rating-label">
                    <TeamOutlined /> 参与度
                  </span>
                  <a-rate
                    v-model:value="records[student.id].participation"
                    allow-half
                    :count="5"
                  />
                </div>
                <div class="rating-item">
                  <span class="rating-label">
                    <HeartOutlined /> 兴趣度
                  </span>
                  <a-rate
                    v-model:value="records[student.id].interest"
                    allow-half
                    :count="5"
                  />
                </div>
                <div class="rating-item">
                  <span class="rating-label">
                    <BulbOutlined /> 理解度
                  </span>
                  <a-rate
                    v-model:value="records[student.id].understanding"
                    allow-half
                    :count="5"
                  />
                </div>
              </div>

              <div class="notes-section">
                <a-textarea
                  v-model:value="records[student.id].notes"
                  placeholder="添加备注（可选）"
                  :rows="2"
                  :maxlength="200"
                  show-count
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 保存按钮 -->
        <div class="action-bar">
          <a-button @click="resetRecords" style="margin-right: 12px;">
            重置
          </a-button>
          <a-button
            type="primary"
            :loading="saving"
            @click="saveRecords"
          >
            <SaveOutlined /> 保存全部记录
          </a-button>
          <a-button
            v-if="lessonInfo?.status === 'COMPLETED'"
            type="default"
            style="margin-left: 12px;"
            @click="showTaskModal"
          >
            <CheckSquareOutlined /> 布置阅读任务
          </a-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!loading">
        <InboxOutlined class="empty-icon" />
        <p>暂无学生数据</p>
        <p class="empty-hint">该班级暂无学生</p>
      </div>
    </a-spin>

    <!-- 布置任务弹窗 -->
    <a-modal
      v-model:open="taskModalVisible"
      title="布置阅读任务"
      :confirm-loading="taskSaving"
      @ok="handleCreateTask"
      width="600px"
    >
      <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="任务标题" required>
          <a-input v-model:value="taskForm.title" placeholder="请输入任务标题" />
        </a-form-item>

        <a-form-item label="关联课程">
          <a-select
            v-model:value="taskForm.relatedCourseId"
            placeholder="选择关联课程（可选）"
            allow-clear
            :loading="coursesLoading"
          >
            <a-select-option
              v-for="course in courses"
              :key="course.id"
              :value="course.id"
            >
              {{ course.name }}
              <span v-if="course.pictureBookName"> - {{ course.pictureBookName }}</span>
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="任务类型" required>
          <a-radio-group v-model:value="taskForm.taskType">
            <a-radio value="READING">阅读任务</a-radio>
            <a-radio value="ACTIVITY">活动任务</a-radio>
            <a-radio value="HOMEWORK">课后作业</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="任务描述">
          <a-textarea
            v-model:value="taskForm.description"
            placeholder="请输入任务描述（可选）"
            :rows="3"
            :maxlength="500"
          />
        </a-form-item>

        <a-form-item label="任务时间" required>
          <a-range-picker
            v-model:value="taskForm.dateRange"
            style="width: 100%"
            :placeholder="['开始日期', '截止日期']"
          />
        </a-form-item>

        <a-alert
          message="任务将自动分配给本班级所有学生"
          type="info"
          show-icon
          style="margin-top: 16px;"
        />
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import {
  ArrowLeftOutlined,
  BulbOutlined,
  EyeOutlined,
  TeamOutlined,
  HeartOutlined,
  SaveOutlined,
  InboxOutlined,
  CheckCircleFilled,
  CheckSquareOutlined,
  ManOutlined,
  WomanOutlined,
} from '@ant-design/icons-vue';
import {
  getStudentRecords,
  batchSaveStudentRecords,
  getLesson,
  getTeacherCourses,
  createTeacherTask,
  type StudentWithRecord,
  type TeacherCourse,
} from '@/api/teacher';
import { translateGenericStatus } from '@/utils/tagMaps';

const router = useRouter();
const route = useRoute();
const lessonId = computed(() => (route.params.id as string) || '');

const loading = ref(false);
const saving = ref(false);
const lessonInfo = ref<{ id: number; status: string; className: string } | null>(null);
const lessonDetail = ref<{
  id: number;
  courseId?: number;
  courseName?: string;
  classId?: number;
  className?: string;
} | null>(null);
const students = ref<StudentWithRecord[]>([]);
const records = reactive<Record<number, { focus: number; participation: number; interest: number; understanding: number; notes: string }>>({});

// 任务相关状态
const taskModalVisible = ref(false);
const taskSaving = ref(false);
const coursesLoading = ref(false);
const courses = ref<TeacherCourse[]>([]);
const taskForm = reactive<{
  title: string;
  description: string;
  taskType: 'READING' | 'ACTIVITY' | 'HOMEWORK';
  relatedCourseId: number | undefined;
  dateRange: [Dayjs, Dayjs] | null;
}>({
  title: '',
  description: '',
  taskType: 'READING',
  relatedCourseId: undefined,
  dateRange: null,
});

const avatarColors = [
  '#FF8C42', '#667eea', '#f093fb', '#4facfe', '#43e97b',
  '#faad14', '#eb2f96', '#722ed1', '#13c2c2', '#fa541c'
];

const getAvatarColor = (index: number) => avatarColors[index % avatarColors.length];

// 状态映射 - 使用统一工具函数
const getStatusText = (status?: string): string => {
  if (!status) return '-';
  const directMap: Record<string, string> = {
    'PLANNED': '已计划',
    'IN_PROGRESS': '进行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
  };
  if (directMap[status]) {
    return directMap[status];
  }
  return translateGenericStatus(status);
};

const getStatusColor = (status?: string): string => {
  if (!status) return 'default';
  const colorMap: Record<string, string> = {
    'PLANNED': 'blue',
    'IN_PROGRESS': 'orange',
    'COMPLETED': 'green',
    'CANCELLED': 'default',
  };
  return colorMap[status] || 'default';
};

const loadRecords = async () => {
  loading.value = true;
  try {
    const data = await getStudentRecords(lessonId.value);
    // 兼容后端返回格式：{ lesson, students } 或异常结构
    const studentList = Array.isArray(data?.students) ? data.students : [];
    lessonInfo.value = data?.lesson ?? null;
    students.value = studentList;

    // 初始化记录数据
    for (const student of studentList) {
      records[student.id] = {
        focus: student.record?.focus ?? 0,
        participation: student.record?.participation ?? 0,
        interest: student.record?.interest ?? 0,
        understanding: student.record?.understanding ?? 0,
        notes: student.record?.notes ?? '',
      };
    }

    // 加载课程详情获取更多课程信息
    await loadLessonDetail();
  } catch (error: any) {
    message.error(error?.message || '获取学生记录失败');
  } finally {
    loading.value = false;
  }
};

const loadLessonDetail = async () => {
  try {
    // 后端返回 LessonDetailResponse: { lesson, course, class }，需从嵌套结构解析
    const res = await getLesson(lessonId.value);
    const l = res?.lesson ?? res;
    const classInfo = res?.class ?? res?.classInfo;
    lessonDetail.value = {
      id: l?.id,
      courseId: l?.courseId ?? res?.course?.id,
      courseName: res?.course?.name ?? l?.courseName,
      classId: l?.classId ?? classInfo?.id,
      className: classInfo?.name ?? l?.className,
    };
  } catch (error) {
    console.error('加载课程详情失败', error);
  }
};

const loadCourses = async () => {
  coursesLoading.value = true;
  try {
    const result = await getTeacherCourses({ pageSize: 100 });
    courses.value = result.items;
  } catch (error) {
    console.error('加载课程列表失败', error);
  } finally {
    coursesLoading.value = false;
  }
};

const showTaskModal = async () => {
  // 重置表单
  taskForm.title = lessonDetail.value?.courseName
    ? `阅读《${lessonDetail.value.courseName}》`
    : '';
  taskForm.description = '';
  taskForm.taskType = 'READING';
  taskForm.relatedCourseId = lessonDetail.value?.courseId;
  taskForm.dateRange = [
    dayjs(),
    dayjs().add(7, 'day'),
  ];

  // 加载课程列表
  if (courses.value.length === 0) {
    await loadCourses();
  }

  taskModalVisible.value = true;
};

const handleCreateTask = async () => {
  // 验证表单
  if (!taskForm.title.trim()) {
    message.warning('请输入任务标题');
    return;
  }
  if (!taskForm.dateRange) {
    message.warning('请选择任务时间');
    return;
  }
  if (!lessonDetail.value?.classId) {
    message.error('无法获取班级信息');
    return;
  }

  taskSaving.value = true;
  try {
    await createTeacherTask({
      title: taskForm.title,
      description: taskForm.description || undefined,
      taskType: taskForm.taskType,
      targetType: 'CLASS',
      targetIds: [lessonDetail.value.classId],
      relatedCourseId: taskForm.relatedCourseId,
      startDate: taskForm.dateRange[0].format('YYYY-MM-DD'),
      endDate: taskForm.dateRange[1].format('YYYY-MM-DD'),
    });

    message.success('任务布置成功');
    taskModalVisible.value = false;
  } catch (error: any) {
    message.error(error.message || '创建任务失败');
  } finally {
    taskSaving.value = false;
  }
};

const resetRecords = () => {
  for (const studentId of Object.keys(records)) {
    records[Number(studentId)] = {
      focus: 0,
      participation: 0,
      interest: 0,
      understanding: 0,
      notes: '',
    };
  }
  message.success('已重置所有记录');
};

const saveRecords = async () => {
  // 构建保存数据
  const recordsToSave = students.value.map((student) => ({
    studentId: student.id,
    focus: records[student.id].focus,
    participation: records[student.id].participation,
    interest: records[student.id].interest,
    understanding: records[student.id].understanding,
    notes: records[student.id].notes,
  }));

  // 检查是否有评分
  const hasAnyRating = recordsToSave.some(
    (r) => r.focus > 0 || r.participation > 0 || r.interest > 0 || r.understanding > 0
  );

  if (!hasAnyRating) {
    message.warning('请至少为一个学生评分');
    return;
  }

  saving.value = true;
  try {
    await batchSaveStudentRecords(lessonId.value, recordsToSave);
    message.success('保存成功');
    // 重新加载数据
    await loadRecords();
  } catch (error: any) {
    message.error(error.message || '保存失败');
  } finally {
    saving.value = false;
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  loadRecords();
});
</script>

<style scoped lang="scss">
.lesson-records-view {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;

      .header-info {
        h2 {
          margin: 0;
          font-size: 24px;
          font-weight: 600;
          color: #333;
        }

        .page-desc {
          margin: 4px 0 0;
          color: #999;
          font-size: 14px;
        }
      }
    }
  }

  .tip-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: linear-gradient(135deg, #FFF8F0 0%, #FFEEE0 100%);
    border-radius: 8px;
    color: #FF8C42;
    font-size: 14px;
    margin-bottom: 24px;
  }

  .student-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .student-card {
    background: white;
    border: 1px solid #f0f0f0;
    border-radius: 12px;
    overflow: hidden;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      background: #fafafa;
      border-bottom: 1px solid #f0f0f0;

      .student-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .student-detail {
          display: flex;
          align-items: center;
          gap: 8px;

          .student-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
          }

          .student-gender {
            font-size: 16px;
          }
        }
      }

      .record-status {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 13px;
        color: #52c41a;
      }
    }

    .card-body {
      padding: 20px;

      .rating-group {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        margin-bottom: 16px;

        @media (max-width: 768px) {
          grid-template-columns: 1fr;
        }

        .rating-item {
          display: flex;
          align-items: center;
          gap: 12px;

          .rating-label {
            display: flex;
            align-items: center;
            gap: 6px;
            min-width: 80px;
            font-size: 14px;
            color: #666;

            .anticon {
              color: #999;
            }
          }
        }
      }

      .notes-section {
        margin-top: 12px;
      }
    }
  }

  .action-bar {
    display: flex;
    justify-content: center;
    padding: 24px;
    background: white;
    border-radius: 12px;
    margin-top: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;

    .empty-icon {
      font-size: 64px;
      color: #d9d9d9;
      margin-bottom: 16px;
    }

    p {
      margin: 4px 0;
    }

    .empty-hint {
      font-size: 13px;
      color: #bfbfbf;
    }
  }
}
</style>
