<template>
  <div class="calendar-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 主体日历 -->
    <FullCalendar
      ref="calendar"
      class="main-calendar"
      :options="calendarOptions"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import '@fullcalendar/core/locales-all'
import 'bootstrap-icons/font/bootstrap-icons.css'

defineOptions({ name: 'MaintenanceCalendar' })

const router = useRouter()
const loading = ref(false)
const calendar = ref(null)

// 模拟API返回的数据结构
const mockData = {
  '2023-08-01': { plans: 3, orders: 2 },
  '2023-08-15': { plans: 5, orders: 1 },
  '2023-08-20': { plans: 2, orders: 4 }
}

// 日历配置
const calendarOptions = ref({
  plugins: [dayGridPlugin, interactionPlugin],
  // locales: [zhCn],
  locale: 'zh-cn',
  initialView: 'dayGridMonth',
  headerToolbar: {
    left: 'prev,next today',
    center: 'title',
    right: 'dayGridMonth,dayGridWeek'
  },
  buttonText: { // ✨ 自定义按钮文本（可选）
    today: '今天',
    month: '月视图',
    week: '周视图'
  },
  events: [],
  datesSet: handleDatesSet, // 月份切换事件
  eventContent: renderEventContent, // 自定义内容渲染
  height: '80vh' // 占据80%视口高度
})

// 获取数据
async function fetchCalendarData(dateRange) {
  try {
    loading.value = true
    // 实际应替换为API调用，这里用mock数据
    return mockData
  } finally {
    loading.value = false
  }
}

// 处理日期范围变化
async function handleDatesSet(dateInfo) {
  const data = await fetchCalendarData({
    start: dateInfo.startStr,
    end: dateInfo.endStr
  })

  calendar.value.getApi().removeAllEvents()
  Object.entries(data).forEach(([date, counts]) => {
    calendar.value.getApi().addEvent({
      title: `${counts.plans}|${counts.orders}`,
      start: date,
      allDay: true,
      extendedProps: counts
    })
  })
}

// 自定义内容渲染
function renderEventContent(eventInfo) {
  const { plans, orders } = eventInfo.event.extendedProps
  return {
    html: `
      <div class="calendar-day-content">
        <div class="count-item">
          <a class="plan-count" data-date="${eventInfo.event.startStr}">
            <i class="bi bi-clipboard-check"></i> ${plans}
          </a>
        </div>
        <div class="count-item">
          <a class="order-count" data-date="${eventInfo.event.startStr}">
            <i class="bi bi-tools"></i> ${orders}
          </a>
        </div>
      </div>
    `
  }
}

// 处理点击事件
function handleDayClick(event) {
  if (event.target.classList.contains('plan-count')) {
    const date = event.target.dataset.date
    router.push({
      path: '/maintenance/plans',
      query: { date }
    })
  }

  if (event.target.classList.contains('order-count')) {
    const date = event.target.dataset.date
    router.push({
      path: '/maintenance/orders',
      query: { date }
    })
  }
}

// 初始化
onMounted(() => {
  const calendarApi = calendar.value.getApi()
  calendarApi.setOption('eventDidMount', (info) => {
    info.el.addEventListener('click', handleDayClick)
  })
})
</script>

<style scoped>
.calendar-container {
  padding: 20px;
  height: 100vh;
}

.main-calendar {
  max-width: 1200px;
  margin: 0 auto;
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px 20px;
  background: rgba(0,0,0,0.7);
  color: white;
  border-radius: 4px;
}

/* 自定义日历样式 */
:deep(.fc-daygrid-day-frame) {
  cursor: pointer;
  min-height: 100px;
}

:deep(.calendar-day-content) {
  padding: 5px;
  font-size: 0.9em;
}

:deep(.count-item) {
  margin: 2px 0;
  padding: 2px;
  border-radius: 3px;
  transition: background 0.3s;
}

:deep(.plan-count) {
  color: #1890ff;
  text-decoration: none;
  display: block;
}

:deep(.order-count) {
  color: #52c41a;
  text-decoration: none;
  display: block;
}

:deep(.count-item:hover) {
  background: #f5f5f5;
}

:deep(.bi) {
  margin-right: 3px;
}
</style>
