<template>
  <div class="step3-schedule-ref">
    <div class="section-header">
      <span class="title">排课计划参考</span>
      <a-button type="primary" size="small" @click="addRow">
        <PlusOutlined /> 添加行
      </a-button>
    </div>

    <a-alert
      message="排课参考说明"
      type="info"
      show-icon
      style="margin-bottom: 16px"
    >
      <template #description>
        此表格为排课参考，帮助教师了解课程安排建议。可根据实际情况调整。
      </template>
    </a-alert>

    <a-table
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      bordered
      size="middle"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'dayOfWeek'">
          <a-select
            v-model:value="record.dayOfWeek"
            style="width: 100%"
            @change="handleChange"
          >
            <a-select-option value="周一">周一</a-select-option>
            <a-select-option value="周二">周二</a-select-option>
            <a-select-option value="周三">周三</a-select-option>
            <a-select-option value="周四">周四</a-select-option>
            <a-select-option value="周五">周五</a-select-option>
          </a-select>
        </template>
        <template v-else-if="column.key === 'lessonType'">
          <a-select
            v-model:value="record.lessonType"
            style="width: 100%"
            @change="handleChange"
          >
            <a-select-option value="导入课">导入课</a-select-option>
            <a-select-option value="集体课">集体课</a-select-option>
            <a-select-option value="健康领域">健康领域</a-select-option>
            <a-select-option value="语言领域">语言领域</a-select-option>
            <a-select-option value="社会领域">社会领域</a-select-option>
            <a-select-option value="科学领域">科学领域</a-select-option>
            <a-select-option value="艺术领域">艺术领域</a-select-option>
            <a-select-option value="区域活动">区域活动</a-select-option>
          </a-select>
        </template>
        <template v-else-if="column.key === 'lessonName'">
          <a-input
            v-model:value="record.lessonName"
            placeholder="课程名称"
            @change="handleChange"
          />
        </template>
        <template v-else-if="column.key === 'activity'">
          <a-input
            v-model:value="record.activity"
            placeholder="区域活动"
            @change="handleChange"
          />
        </template>
        <template v-else-if="column.key === 'note'">
          <a-input
            v-model:value="record.note"
            placeholder="备注"
            @change="handleChange"
          />
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" size="small" danger @click="removeRow(index)">
            <DeleteOutlined /> 删除
          </a-button>
        </template>
      </template>
    </a-table>

    <div class="preset-section">
      <a-divider>快速填充</a-divider>
      <a-space>
        <a-button @click="applyPreset('week')">填充一周模板</a-button>
        <a-button @click="clearAll">清空全部</a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

interface ScheduleRow {
  key: string;
  dayOfWeek: string;
  lessonType: string;
  lessonName: string;
  activity: string;
  note: string;
}

interface Props {
  modelValue: string; // JSON string
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
  (e: 'change'): void;
}>();

const columns = [
  { title: '时间', key: 'dayOfWeek', width: 100 },
  { title: '课程类型', key: 'lessonType', width: 120 },
  { title: '课程名称', key: 'lessonName', width: 150 },
  { title: '区域活动', key: 'activity', width: 150 },
  { title: '备注', key: 'note', width: 150 },
  { title: '操作', key: 'action', width: 80 },
];

const tableData = ref<ScheduleRow[]>([]);

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (!newVal || typeof newVal !== 'string') {
      tableData.value = [];
      return;
    }
    try {
      const parsed = JSON.parse(newVal);
      const rows = Array.isArray(parsed) ? parsed : [];
      tableData.value = rows.map((row: any, index: number) => ({
        ...row,
        key: row.key || `row_${index}`,
      }));
    } catch (e) {
      console.error('解析排课数据失败', e);
      tableData.value = [];
    }
  },
  { immediate: true }
);

// 生成唯一key
const generateKey = () => `row_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

// 添加行
const addRow = () => {
  tableData.value.push({
    key: generateKey(),
    dayOfWeek: '',
    lessonType: '',
    lessonName: '',
    activity: '',
    note: '',
  });
  handleChange();
};

// 删除行
const removeRow = (index: number) => {
  tableData.value.splice(index, 1);
  handleChange();
};

// 清空全部
const clearAll = () => {
  tableData.value = [];
  handleChange();
};

// 应用一周模板
const applyPreset = (preset: string) => {
  if (preset === 'week') {
    tableData.value = [
      { key: generateKey(), dayOfWeek: '周一', lessonType: '导入课', lessonName: '', activity: '', note: '' },
      { key: generateKey(), dayOfWeek: '周二', lessonType: '集体课', lessonName: '', activity: '', note: '' },
      { key: generateKey(), dayOfWeek: '周三', lessonType: '语言领域', lessonName: '', activity: '', note: '' },
      { key: generateKey(), dayOfWeek: '周四', lessonType: '艺术领域', lessonName: '', activity: '', note: '' },
      { key: generateKey(), dayOfWeek: '周五', lessonType: '区域活动', lessonName: '', activity: '', note: '' },
    ];
    handleChange();
  }
};

// 处理变化
const handleChange = () => {
  const dataStr = JSON.stringify(tableData.value);
  emit('update:modelValue', dataStr);
  emit('change');
};

// 验证：若有行且选了课程类型，则课程名称必填
const validate = () => {
  const rows = tableData.value || [];
  if (rows.length === 0) {
    return { valid: true, errors: [] };
  }
  const invalidRow = rows.find(
    (row) => row.lessonType && (!row.lessonName || !row.lessonName.trim())
  );
  if (invalidRow) {
    return { valid: false, errors: ['请填写课程名称'] };
  }
  return { valid: true, errors: [] };
};

defineExpose({
  validate,
  tableData,
});
</script>

<style scoped lang="scss">
.step3-schedule-ref {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .preset-section {
    margin-top: 16px;
    text-align: center;
  }

  :deep(.ant-table) {
    .ant-input,
    .ant-select {
      width: 100%;
    }
  }
}
</style>
