

<template>
  <div class="w-full h-full flex flex-col calendarPlugin">
    <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: '01:00:00', // 一个小时一格（timeGrid生效）
  events: [],
  headerToolbar: {  // 自定义头部
    left: 'today,prev,next',  // 左侧按钮：上一页，下一页，今天
    center: 'title',
    right: 'dayGridMonth,timeGridWeek,timeGridDay'  // 右侧显示视图切换按钮
  },
  slotLabelContent: (arg: any) => {
    const hour = arg.date.getHours()
    const meridiem = hour < 12 ? '上午' : '下午'
    return `${meridiem} ${hour} 时`
  },
  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,
        // backgroundColor: ['#909399', '#075985', '#67C23A', '#F56C6C'][item.status],
        // borderColor: ['#909399', '#075985', '#67C23A', '#F56C6C'][item.status]
        backgroundColor: ['#a6a9b0', '#3a7fc1', '#7fbf72', '#e28c8c'][item.status],
        borderColor: ['#a6a9b0', '#3a7fc1', '#7fbf72', '#e28c8c'][item.status],
      }
    })
  }
}

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()
})

defineExpose({
  getTaskCalendar
})
</script>

<style lang="scss" scoped>
.calendarPlugin {
  :deep(.fc-today-button) {
    margin-right: 10px;
  }
  :deep(table) {
    height: 100%;
  }
  
  /* 强制事件内文字换行 */
  :deep(.fc-timegrid-col-events .fc-event-main) div {
    width: 50%;
    white-space: normal !important;
    word-break: break-word;
  }

  :deep(.fc-timegrid-col-events .fc-timegrid-event-harness:last-child .fc-event-main) div {
    width: 100%;
    white-space: normal !important;
    word-break: break-word;
  }
}
</style> 