

<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex-1" v-loading="calendarLoading">
      <FullCalendar ref="calendarRef" :options="calendarOptions" class="h-full w-full">
        <template v-slot:eventContent='arg'>
          <div>{{ arg.event.title }}</div>
        </template>
      </FullCalendar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import zhCnLocale from '@fullcalendar/core/locales/zh-cn' 
import { post, uploadFile } from '@/utils/request';
import { GET_TASK_LIST_BY_START_AND_END } from './api'
import { formatDate, getFirstDayOfMonth, getLastDayOfMonth } from '@/utils/times';
import { dayjs } from 'element-plus';

// 当前选中的视图
const currentView = ref('dayGridMonth')
// 日历实例引用
const calendarRef = ref()

const dateForm = ref({
  startDate: getFirstDayOfMonth(new Date()),
  endDate: getLastDayOfMonth(new Date())
})
const calendarListData = ref([])
const calendarLoading = ref(false)

// FullCalendar 配置
const calendarOptions = ref<any>({
  plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
  locale: zhCnLocale,
  initialView: currentView.value,
  slotMinTime: '06:00:00',  // 最早显示时间
  slotMaxTime: '22:00:00',  // 最晚显示时间
  slotDuration: '00:30:00', // 30分钟一格（timeGrid生效）
  events: [],
  headerToolbar: {  // 自定义头部
    left: 'today,prev,next',  // 左侧按钮：上一页，下一页，今天
    center: 'title',
    right: 'dayGridMonth,timeGridWeek,timeGridDay'  // 右侧显示视图切换按钮
  },
  datesSet: (arg: any) => { // 📌 每次切换视图或日期都会触发
    const { startStr = '', endStr = '' } = arg
    if (startStr && endStr) {
      dateForm.value = {
        startDate: startStr,
        endDate: endStr,
      }
      getTaskCalendar()
    }
  }
})

// 重新渲染表格数据
function renderTableData() {
  calendarOptions.value = {
    ...calendarOptions.value,
    events: (calendarListData.value || []).map((item: any) => {
      return {
        ...item,
        start: item.startDate,
        end: item.endDate,
        title: item.taskName
      }
    })
  }
}

function getTaskCalendar() {
  const { startDate, endDate } = dateForm.value
  calendarLoading.value = true
  post(GET_TASK_LIST_BY_START_AND_END, {
    startDate: dayjs(startDate).format('YYYY-MM-DD'),
    endDate: dayjs(endDate).format('YYYY-MM-DD')
  }).then((res) => {
    calendarListData.value = res.data || []
    renderTableData()
  }).finally(() => {
    calendarLoading.value = false
  })
}

onMounted(() => {
  getTaskCalendar()
})

</script>

<style lang="scss" scoped>
:deep(.fc-today-button) {
  margin-right: 10px;
} 
</style> 