<template>
	<div class="calendar-view">
		<FullCalendar ref="calendarRef" :options="calendarOptions" />
	</div>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted, nextTick } from 'vue';
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { useProjectStore } from '../../store/project';

const emit = defineEmits<{
	(e: 'open-task', taskId: number): void;
}>();

const store = useProjectStore();
const calendarRef = ref();

// Tab 切换后首次渲染时容器尺寸未稳定，需要延迟刷新布局
onMounted(() => {
	nextTick(() => {
		setTimeout(() => {
			calendarRef.value?.getApi()?.updateSize();
		}, 150);
	});
});

const events = computed(() => {
	return store.tasks.map((t: any) => {
		const taskId = parseInt(String(t.id).replace('t_', ''));
		const priorityColor: Record<number, string> = {
			0: '#F56C6C',
			1: '#E6A23C',
			2: '#409EFF',
			3: '#909399',
		};
		return {
			id: String(taskId),
			title: t.text,
			start: t.start_date,
			end: t.end_date,
			color: t.color || priorityColor[t.priority] || '#409EFF',
			extendedProps: { taskId },
		};
	}).filter((e: any) => e.start);
});

const calendarOptions = computed(() => ({
	plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
	initialView: 'dayGridMonth',
	locale: 'zh-cn',
	headerToolbar: {
		left: 'prev,next today',
		center: 'title',
		right: 'dayGridMonth,timeGridWeek',
	},
	events: events.value,
	editable: false,
	eventClick: (info: any) => {
		const taskId = info.event.extendedProps.taskId;
		if (taskId) {
			emit('open-task', taskId);
		}
	},
	height: 'calc(100vh - 260px)',
}));
</script>

<style lang="scss" scoped>
.calendar-view {
	padding: 10px;
}
</style>
