<script lang="ts" setup>
  import { RadioGroup, Radio, Divider, TypographyTitle, RadioButton } from 'ant-design-vue';
  import FullCalendar from '@fullcalendar/vue3';
  import dayGridPlugin from '@fullcalendar/daygrid';
  import { CalendarOptions } from '@fullcalendar/core';
  import interactionPlugin from '@fullcalendar/interaction';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getQueryByTenantId, editDay } from './teachorNoteach.api';
  import { useUserStore } from '/@/store/modules/user';
  import { h, ref } from 'vue';
  import dayjs from 'dayjs';
  import { storeToRefs } from 'pinia';
  const { userInfo } = storeToRefs(useUserStore());
  const { createWarningModal, createMessage } = useMessage();
  const isChangeDay = ref(0);
  const changeDay = ref(1);
  const today = new Date();
  const nonTeachingDays = ref<Date[]>([]);
  const fullCalendarRef = ref();
  const TeachingData = ref<{ day: string; id: string; isTeaching: number; orgCode: string }[]>([]);
  const calendarOptions = ref<CalendarOptions>({
    plugins: [dayGridPlugin, interactionPlugin],
    initialView: 'dayGridMonth',
    events: [{ title: '今天', start: new Date() }],
    selectable: true,
    selectMirror: true,
    headerToolbar: {
      left: '',
      right: '',
    },
    locale: 'zh-cn',
    dayCellClassNames: (arg) => {
      const { date } = arg;
      const day = date.getDay();
      if ((day === 0 || day === 6) && isNonTeachingDay(date)) {
        return ['weekend-cell'];
      }
      // const isPast = date < today && !dayjs(date).isSame(dayjs(today), 'day');
      if (isPast(date)) {
        return ['past-day'];
      }
      // 判断是否为非教学日
      // const isNonTeachingDay = nonTeachingDays.value.some((d) => dayjs(d).isSame(dayjs(date), 'day'));
      if (isNonTeachingDay(date)) {
        return ['non-teaching-day'];
      }

      return [];
    },
    select: handleClick,
  });
  function handleClick(selectInfo) {
    const clickedDate = selectInfo.start;
    // const day = dayjs(clickedDate).day();
    if (isPast(clickedDate)) {
      //今天之前的日期不允许点击//或者是周末也不允许点击
      return;
    }
    createWarningModal({
      title: '日期类型修改',
      okText: '确认',
      cancelText: '取消',
      content() {
        const arr = [h(Radio, { value: 0 }, () => '教学日'), h(Radio, { value: 1 }, () => '非教学日')];
        return h(
          RadioGroup,
          {
            value: isChangeDay.value,
            onChange(e) {
              isChangeDay.value = e.target.value;
            },
          },
          () => arr
        );
      },
      okCancel: true,
      onOk: async () => {
        const findData = TeachingData.value.find((it) => dayjs(it.day).valueOf() == dayjs(clickedDate).valueOf());
        if (!findData) return createMessage.error('添加失败，请重新选择');
        await editDay({ isTeaching: isChangeDay.value, id: findData.id });
        getTimeDay();
        fullCalendarRef.value.getApi().render();

        if (isChangeDay.value == 2) {
          nonTeachingDays.value.push(clickedDate);
        } else {
          const index = findNonTeachingDayIndex(clickedDate);
          if (index > -1) {
            nonTeachingDays.value.splice(index, 1);
          }
        }
      },
      onCancel: () => {},
    });
  }
  function isNonTeachingDay(date: Date): boolean {
    // 判断日期是否为非教学日
    return nonTeachingDays.value.some((d) => dayjs(d).isSame(dayjs(date), 'day'));
  }
  function findNonTeachingDayIndex(clickedDate: Date): number {
    // 找到非教学日在数组中的索引
    return nonTeachingDays.value.findIndex((d) => dayjs(d).isSame(dayjs(clickedDate), 'day'));
  }
  function isPast(date) {
    return date < today && !dayjs(date).isSame(dayjs(today), 'day');
  }
  function handleChangeDay() {
    if (changeDay.value == 1) {
      fullCalendarRef.value.getApi().today();
    } else {
      fullCalendarRef.value.getApi().next();
    }
  }
  async function getTimeDay() {
    const res = await getQueryByTenantId({
      orgCode: userInfo.value?.orgCode,
    });
    TeachingData.value = res;
    nonTeachingDays.value = TeachingData.value.filter((it) => it.isTeaching).map((it) => new Date(it.day));
    fullCalendarRef.value.getApi().render();
  }
  getTimeDay();
</script>

<template>
  <div class="px-15 py-3 bg-white">
    <div class="flex items-center justify-between">
      <TypographyTitle :level="3"> {{ changeDay == 1 ? dayjs().format('YYYY-MM') : dayjs().add(1, 'month').format('YYYY-MM') }} </TypographyTitle>
      <RadioGroup v-model:value="changeDay" @change="handleChangeDay">
        <RadioButton :value="1">今天 </RadioButton>
        <RadioButton :value="2">下一个月 </RadioButton>
      </RadioGroup>
    </div>
    <Divider></Divider>
    <div class="flex items-center justify-center customer">
      <div class="w-70%">
        <FullCalendar :options="calendarOptions" ref="fullCalendarRef"> </FullCalendar>
      </div>
    </div>
    <div class="mt-5 w-full text-right"> 红色数字为非教学日，蓝色数字为教学日。 </div>
  </div>
</template>

<style lang="less" scoped>
  .customer {
    :deep(.weekend-cell) {
      .fc-daygrid-day-number {
        color: red !important;
      }
    }
    :deep(.past-day) {
      .fc-daygrid-day-number {
        color: #ccc;
      }
    }
    :deep(.non-teaching-day) {
      .fc-daygrid-day-number {
        color: red !important;
      }
    }
    :deep(.fc-col-header) {
      .fc-day-sat,
      .fc-day-sun {
        .fc-col-header-cell-cushion {
          color: red !important;
        }
      }
    }
  }
</style>
