<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="排课单号" prop="scheduleNo">
              <el-input v-model="queryParams.scheduleNo" placeholder="请输入单号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学生ID" prop="studentId">
              <el-input v-model="queryParams.studentId" placeholder="请输入学生ID" clearable style="width: 150px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="老师ID" prop="tutorId">
              <el-input v-model="queryParams.tutorId" placeholder="请输入老师ID" clearable style="width: 150px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学科" prop="subject">
              <el-input v-model="queryParams.subject" placeholder="请输入学科" clearable style="width: 140px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="课型" prop="lessonType">
              <el-select v-model="queryParams.lessonType" placeholder="课型" clearable style="width: 140px">
                <el-option v-for="opt in lessonTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 140px">
                <el-option v-for="opt in scheduleStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:schedule:add']" type="primary" plain icon="Plus" @click="handleAdd">新增排课</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:schedule:export']" type="warning" plain icon="Download" @click="handleExport">导出课表</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="scheduleList">
        <el-table-column label="排课单号" align="center" prop="scheduleNo" width="180" />
        <el-table-column label="学生ID" align="center" prop="studentId" width="90" />
        <el-table-column label="老师ID" align="center" prop="tutorId" width="90" />
        <el-table-column label="学科" align="center" prop="subject" width="80" />
        <el-table-column label="课型" align="center" prop="lessonType" width="100">
          <template #default="scope">
            <el-tag :type="getLessonTypeTag(scope.row.lessonType)">{{ getLessonTypeLabel(scope.row.lessonType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上课日期" align="center" prop="lessonDate" width="110">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.lessonDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" width="150">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.startTime, '{h}:{i}') }} - {{ proxy.parseTime(scope.row.endTime, '{h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时长" align="center" prop="durationHours" width="70" />
        <el-table-column label="消课时" align="center" prop="consumeHours" width="80" />
        <el-table-column label="状态" align="center" prop="status" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['edu:schedule:query']" link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="修改" placement="top">
              <el-button v-hasPermi="['edu:schedule:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0' || scope.row.status === '1'" content="签到" placement="top">
              <el-button v-hasPermi="['edu:schedule:checkIn']" link type="success" icon="CircleCheck" @click="handleCheckIn(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '1'" content="消课" placement="top">
              <el-button v-hasPermi="['edu:schedule:consume']" link type="warning" icon="Finished" @click="handleConsume(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="请假" placement="top">
              <el-button v-hasPermi="['edu:schedule:leave']" link type="info" icon="Clock" @click="handleLeave(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="删除" placement="top">
              <el-button v-hasPermi="['edu:schedule:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailVisible" title="排课详情" size="45%">
      <el-descriptions v-if="detailData.id" :column="2" border>
        <el-descriptions-item label="排课单号">{{ detailData.scheduleNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(detailData.status)">{{ getStatusLabel(detailData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="学生ID">{{ detailData.studentId }}</el-descriptions-item>
        <el-descriptions-item label="老师ID">{{ detailData.tutorId }}</el-descriptions-item>
        <el-descriptions-item label="学科">{{ detailData.subject }}</el-descriptions-item>
        <el-descriptions-item label="课型">{{ getLessonTypeLabel(detailData.lessonType) }}</el-descriptions-item>
        <el-descriptions-item label="上课时间">{{ proxy.parseTime(detailData.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="下课时间">{{ proxy.parseTime(detailData.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="时长(小时)">{{ detailData.durationHours }}</el-descriptions-item>
        <el-descriptions-item label="消课比例">{{ detailData.consumeRate }}</el-descriptions-item>
        <el-descriptions-item label="消课时数">{{ detailData.consumeHours }}</el-descriptions-item>
        <el-descriptions-item label="签到时间">{{ proxy.parseTime(detailData.checkInAt) }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">课堂信息</el-divider>
      <p>{{ detailData.lessonContent || '无' }}</p>
      <el-divider content-position="left">作业</el-divider>
      <p>{{ detailData.homework || '无' }}</p>
      <el-divider content-position="left">参与学生</el-divider>
      <el-table border :data="detailData.students" size="small">
        <el-table-column label="学生ID" prop="studentId" align="center" />
        <el-table-column label="应扣课时" prop="hoursShould" align="center" />
        <el-table-column label="实扣课时" prop="hoursActual" align="center" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="820px" append-to-body>
      <el-form ref="scheduleFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="学生ID" prop="studentId">
              <el-input v-model="form.studentId" placeholder="学生ID" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="辅导老师" prop="tutorId">
              <el-input v-model="form.tutorId" placeholder="辅导老师ID" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学科" prop="subject">
              <el-input v-model="form.subject" placeholder="如: 数学" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="课型" prop="lessonType">
              <el-select v-model="form.lessonType" placeholder="请选择" style="width: 100%" @change="onTypeChange">
                <el-option v-for="opt in lessonTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="绑定合同" prop="contractId">
              <el-input v-model="form.contractId" placeholder="合同ID(可选)" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消课比例" prop="consumeRate">
              <el-input-number v-model="form.consumeRate" :min="0" :step="0.5" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上课日期" prop="lessonDate">
              <el-date-picker v-model="form.lessonDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="时长(小时)" prop="durationHours">
              <el-input-number v-model="form.durationHours" :min="0" :step="0.5" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="教室/链接" prop="classroom">
              <el-input v-model="form.classroom" placeholder="教室或线上链接" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="课堂内容" prop="lessonContent">
          <el-input v-model="form.lessonContent" type="textarea" placeholder="本次课内容" />
        </el-form-item>
        <el-form-item label="作业" prop="homework">
          <el-input v-model="form.homework" type="textarea" placeholder="本次作业" />
        </el-form-item>

        <!-- 学生关联子表(小班课多人) -->
        <el-divider content-position="left">参与学生（消课扣课时）</el-divider>
        <el-table border :data="form.students" size="small">
          <el-table-column label="学生ID" min-width="120" align="center">
            <template #default="{ row }">
              <el-input v-model="row.studentId" placeholder="学生ID" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="扣课合同ID" min-width="120" align="center">
            <template #default="{ row }">
              <el-input v-model="row.contractId" placeholder="合同ID" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="应扣课时" width="130" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.hoursShould" :min="0" :step="0.5" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" @click="form.students.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-2" type="primary" plain icon="Plus" size="small" @click="addStudent">添加学生</el-button>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduSchedule" lang="ts">
import {
  listSchedule,
  getSchedule,
  addSchedule,
  updateSchedule,
  delSchedule,
  checkInSchedule,
  consumeSchedule,
  leaveSchedule
} from '@/api/edu/schedule';
import {
  ScheduleForm,
  ScheduleQuery,
  ScheduleVO,
  lessonTypeOptions,
  scheduleStatusOptions,
  consumeRateMap,
  LessonStudentForm
} from '@/api/edu/schedule/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const scheduleList = ref<ScheduleVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const scheduleFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({ visible: false, title: '' });
const detailVisible = ref(false);
const detailData = ref<ScheduleVO>({} as ScheduleVO);

const initFormData: ScheduleForm = {
  id: undefined,
  scheduleNo: '',
  studentId: undefined,
  contractId: undefined,
  tutorId: undefined,
  subject: '',
  lessonType: 'ONE_ON_ONE',
  className: '',
  lessonDate: '',
  startTime: '',
  endTime: '',
  durationHours: 2,
  classroom: '',
  lessonContent: '',
  homework: '',
  maxStudents: 1,
  consumeRate: 2,
  comment: '',
  remark: '',
  students: []
};

const data = reactive<PageData<ScheduleForm, ScheduleQuery>>({
  form: { ...initFormData, students: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scheduleNo: '',
    studentId: undefined,
    tutorId: undefined,
    subject: '',
    lessonType: '',
    status: ''
  },
  rules: {
    studentId: [{ required: true, message: '学生ID不能为空', trigger: 'blur' }],
    tutorId: [{ required: true, message: '辅导老师不能为空', trigger: 'blur' }],
    subject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
    lessonType: [{ required: true, message: '课型不能为空', trigger: 'change' }],
    lessonDate: [{ required: true, message: '上课日期不能为空', trigger: 'change' }],
    startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getLessonTypeLabel = (val: string) => lessonTypeOptions.find((o) => o.value === val)?.label || val;
const getLessonTypeTag = (val: string) => lessonTypeOptions.find((o) => o.value === val)?.elTagType || 'info';
const getStatusLabel = (val: string) => scheduleStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => scheduleStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

/** 课型变化时联动消课比例 */
const onTypeChange = (val: string) => {
  const rate = consumeRateMap[val];
  if (rate !== undefined) {
    form.value.consumeRate = rate;
  }
};

const getList = async () => {
  loading.value = true;
  const res = await listSchedule(queryParams.value);
  scheduleList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData, students: [] };
  scheduleFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增排课';
};

const handleUpdate = async (row: ScheduleVO) => {
  reset();
  const res = await getSchedule(row.id);
  Object.assign(form.value, res.data);
  form.value.students = res.data.students || [];
  dialog.visible = true;
  dialog.title = '修改排课';
};

const submitForm = () => {
  scheduleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 若未添加学生明细, 默认用主表学生构造一条
      if (form.value.students.length === 0 && form.value.studentId) {
        form.value.students.push({
          studentId: form.value.studentId,
          contractId: form.value.contractId,
          hoursShould: form.value.durationHours,
          consumeRate: form.value.consumeRate,
          remark: ''
        });
      }
      form.value.id ? await updateSchedule(form.value) : await addSchedule(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const handleDetail = async (row: ScheduleVO) => {
  const res = await getSchedule(row.id);
  detailData.value = res.data;
  detailVisible.value = true;
};

const handleDelete = async (row: ScheduleVO) => {
  await proxy?.$modal.confirm('是否确认删除排课"' + row.scheduleNo + '"？');
  await delSchedule(row.id);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleExport = () => {
  proxy?.download('edu/schedule/export', { ...queryParams.value }, `schedule_${new Date().getTime()}.xlsx`);
};

/** 签到 */
const handleCheckIn = async (row: ScheduleVO) => {
  await checkInSchedule({ scheduleId: row.id, studentId: row.studentId });
  proxy?.$modal.msgSuccess('签到成功');
  await getList();
};

/** 消课 */
const handleConsume = async (row: ScheduleVO) => {
  await proxy?.$modal.confirm(`确认对排课"${row.scheduleNo}"进行消课？将按消课比例扣减合同课时`);
  await consumeSchedule(row.id);
  proxy?.$modal.msgSuccess('消课成功');
  await getList();
};

/** 请假 */
const handleLeave = async (row: ScheduleVO) => {
  await proxy?.$modal.confirm('确认该学生请假？请假不扣课时');
  await leaveSchedule({ scheduleId: row.id, studentId: row.studentId });
  proxy?.$modal.msgSuccess('已标记请假');
  await getList();
};

/** 添加学生行 */
const addStudent = () => {
  const item: LessonStudentForm = {
    studentId: '',
    contractId: '',
    hoursShould: form.value.durationHours,
    consumeRate: form.value.consumeRate,
    remark: ''
  };
  form.value.students.push(item);
};

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