<template>
  <div class="wh-full bg-white">
    <n-form style="justify-content: center; margin-top: 1rem" :label-width="200" inline>
      <n-form-item class="min-w-34" label="请选择查询学员" path="scheduleParamsOptions.studentId">
        <n-select
          v-model:value="scheduleParamsOptions.studentId"
          filterable
          placeholder="请选择查询学员"
          :options="studentOptions"
          :loading="studentOptionsLoading"
          clearable
          remote
          @search="studentOptionsSearch"
        />
      </n-form-item>
      <n-form-item class="min-w-34" label="请选择要查询的班级" path="scheduleParamsOptions.classId">
        <n-select
          v-model:value="scheduleParamsOptions.classId"
          :options="groupList"
          clearable
          placeholder="请选择班级"
        />
      </n-form-item>
      <n-form-item class="min-w-34" label="要查询的授课教师" path="scheduleParamsOptions.teacherId">
        <n-select
          v-model:value="scheduleParamsOptions.teacherId"
          :options="teacherOptions"
          placeholder="请选择授课教师"
          clearable
        />
      </n-form-item>
      <n-form-item>
        <n-button type="primary" @click="loadScheduleQuery"> 搜索 </n-button>
      </n-form-item>
    </n-form>
    <div class="flex-col-center" style="width: 70%; margin: 0 auto; margin-top: 1%">
      <n-calendar
        v-if="show"
        style="width: 100%"
        #="{ year, month, date }"
        @panel-change="handlePanelChange"
        @update:value="handleUpdateValue"
      >
        {{ year }}年{{ month }}月{{ date }}日 <br />
        <n-tag v-if="dataList[`${year}-${doubleMonth(month)}-${date}`]" type="success">
          共有课时:
          {{ dataList[`${year}-${doubleMonth(month)}-${date}`] }}
          节
        </n-tag>
        <n-tag v-else> 共有课时:0 节 </n-tag>
      </n-calendar>

      <n-modal v-model:show="showModal" preset="dialog" title="Dialog">
        <template #header>
          <div>当日课程详情</div>
        </template>
        <div style="margin-top: 2rem">
          <n-timeline v-if="list.length > 0">
            <n-timeline-item
              v-for="item in list"
              :key="item.id"
              type="success"
              :title="item.teacherName"
              :time="item.startTime + ' - ' + item.endTime"
            >
              <template #default>
                {{ `${item.category} -- ${item.subjects}` }}
                <br />
                <n-button
                  @click="
                    () => {
                      router.push({
                        path: '/lesson/checkin',
                        query: {
                          scheduleId: item.id
                        }
                      });
                    }
                  "
                >
                  考勤打卡
                </n-button>
              </template>
            </n-timeline-item>
          </n-timeline>
        </div>
        <template #action>
          <n-button @click="showModal = false">关闭</n-button>
        </template>
      </n-modal>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { formatDate, getFirstDayOfMonth, getLastDayOfMonth } from '@/utils';
import {
  querySchedule,
  getStudentByKeyword,
  queryCategoryParams,
  queryUserAll,
  queryClassAll,
  queryClassRoomList
} from './api';
import type { QueryScheduleParams } from './api';
const route = useRoute();
const router = useRouter();
const classId = route.query.classId;
const studentId = route.query.studentId;
const show = ref(false);
const showModal = ref(false);
const list = ref<any>([]);
const allList = reactive<any>({});
const studentOptions = ref<any[]>([]);
const studentOptionsLoading = ref<boolean>(false);
const categoryAndSubjectOptions = ref<any[]>([]);
const groupList = ref<any[]>([]);
const classRoomList = ref<any[]>([]);
const teacherOptions = ref<any[]>();
const scheduleParamsOptions = ref<QueryScheduleParams>({
  studentId: null,
  classId: null,
  subjectId: null,
  teacherId: null,
  startTime: formatDate(getFirstDayOfMonth(new Date())),
  endTime: formatDate(getLastDayOfMonth(new Date())),
  roomId: null,
  assistantId: null,
  categoryId: null
});
const dataList = reactive<{ [index: string]: any }>({});
function handleUpdateValue(_: number, { year, month, date }: { year: number; month: number; date: number }) {
  if (dataList[`${year}-${doubleMonth(month)}-${date}`]) {
    list.value = allList[`${year}-${doubleMonth(month)}-${date}`];
    showModal.value = true;
  }
}
async function findStudent(sId: number) {
  if (sId) {
    studentOptionsLoading.value = true;
    studentOptions.value = [];
    getStudentByKeyword(sId.toString()).then(response => {
      response.data?.forEach(r => {
        studentOptions.value.push({
          label: r.studentName,
          value: r.id
        });
        if (Number(sId) === r.id) {
          scheduleParamsOptions.value.studentId = Number(sId);
        }
      });
    });
    studentOptionsLoading.value = false;
    loadScheduleQuery();
  }
}
function studentOptionsSearch(keyword: string) {
  if (!keyword.length) {
    studentOptions.value = [];
    return;
  }
  studentOptionsLoading.value = true;
  studentOptions.value = [];
  getStudentByKeyword(keyword).then(response => {
    response.data?.forEach(r => {
      studentOptions.value.push({
        label: r.studentName,
        value: r.id
      });
    });
  });
  studentOptionsLoading.value = false;
}
function doubleMonth(month: number) {
  return month < 10 ? `0${month}` : month;
}

function handlePanelChange(event: { year: number; month: number }) {
  scheduleParamsOptions.value.startTime = formatDate(getFirstDayOfMonth(new Date(event.year, event.month - 1)));
  scheduleParamsOptions.value.endTime = formatDate(getLastDayOfMonth(new Date(event.year, event.month - 1)));
  loadScheduleQuery();
}

async function loadData() {
  await queryUserAll().then(response => {
    teacherOptions.value = response.data?.map(r => {
      return {
        label: r.relname,
        value: r.id
      };
    });
  });
  await queryCategoryParams(1, 100, {}).then(response => {
    response.data?.map(r => {
      categoryAndSubjectOptions.value.push({
        label: r.name,
        value: r.id,
        depth: 1,
        isLeaf: false
      });
      return r;
    });
  });
  await queryClassAll().then(response => {
    response.data?.map(r => {
      groupList.value.push({
        label: r.name,
        value: r.id
      });
      if (Number(classId) === r.id) {
        scheduleParamsOptions.value.classId = Number(classId);
      }
      return r;
    });
  });
  await queryClassRoomList(1, 100, {}).then(response => {
    response.data?.map(r => {
      classRoomList.value.push({
        label: r.name,
        value: r.id
      });
      return r;
    });
  });

  await findStudent(Number(studentId));

  loadScheduleQuery();
}

function loadScheduleQuery() {
  querySchedule(scheduleParamsOptions.value).then(response => {
    if (dataList) {
      for (const key in dataList) {
        if (dataList[key]) {
          delete dataList[key];
        }
      }
    }
    if (allList) {
      for (const key in allList) {
        if (allList[key]) {
          delete allList[key];
        }
      }
    }
    list.value = [];
    response.data?.forEach(result => {
      if (result.startTime) {
        const key = result.startTime.split(' ')[0].toString();
        if (!allList[key]) {
          allList[key] = [];
        }
        allList[key].push(result);
        if (dataList[key]) {
          dataList[key] += dataList[key];
        } else {
          dataList[key] = 1;
        }
      }
    });
    show.value = true;
  });
}
loadData();
</script>
<style scoped></style>
