<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 { IotMainWorkOrderApi } from '@/api/pms/iotmainworkorder'
import '@fullcalendar/core/locales-all'
import 'bootstrap-icons/font/bootstrap-icons.css'
const { push } = useRouter() // 路由跳转

defineOptions({ name: 'MaintenanceCalendar' })
const { t } = useI18n() // 国际化
const router = useRouter()
const loading = ref(false)
const calendar = ref(null)

// 模拟API返回的数据结构
const mockData = {
  '2025-05-01': { mains: 3, orders: 2 },
  '2025-05-15': { mains: 5, orders: 1 },
  '2025-05-20': { mains: 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: t('calender.today'),
    month: t('calender.month'),
    week: t('calender.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.mains}|${counts.orders}`,
      start: date,
      allDay: true,
      extendedProps: counts
    })
  })
}

// 自定义内容渲染
function renderEventContent(eventInfo) {
  const { mains, 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> 维修工单${mains}
          </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: 'IotMaintenancePlan',
      query: { date }
    }) */
    router.push({ name: 'IotMaintain', params:{} })
  }

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

// 初始化
onMounted(async () => {
  const calendarApi = calendar.value.getApi()
  calendarApi.setOption('eventDidMount', (info) => {
    info.el.addEventListener('click', handleDayClick)
  })
  const data = await IotMainWorkOrderApi.allWorkOrderCountByResult();

})
</script>

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

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

:deep(.fc-event) {
  background-color: #e6f7ff !important; /* 浅蓝色背景 */
  border-color: #e6f7ff !important;     /* 边框颜色同步 */
  color: #333 !important;               /* 文字颜色加深 */
}

.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: 4px;
  font-size: 0.85em;
}

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

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

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

:deep(.count-item:hover) {
  background: rgba(240, 240, 240, 0.8);
  transform: translateX(2px);
}

:deep(.bi) {
  margin-right: 5px;
  font-size: 0.9em;
}

/* 精确控制prev/next/today按钮 */
:deep(.fc-prev-button),
:deep(.fc-next-button),
:deep(.fc-today-button) {
  background-color: #f0f0f0 !important;
  border-color: #d9d9d9 !important;
  color: #333 !important;
  position: relative;
  padding: 6px 12px !important; /* 增加按钮宽度 */
}

/* 隐藏默认图标 */
:deep(.fc-button .fc-icon) {
  display: none !important;
}

/* 添加自定义箭头 */
:deep(.fc-prev-button)::before {
  content: "<";
  display: inline-block;
  font-weight: bold;
  margin-right: 4px;
}

:deep(.fc-next-button)::after {
  content: ">";
  display: inline-block;
  font-weight: bold;
  margin-left: 4px;
}

/* 调整today按钮间距 */
:deep(.fc-today-button) {
  margin: 0 8px !important;
}

:deep(.fc-prev-button:hover),
:deep(.fc-next-button:hover),
:deep(.fc-today-button:hover) {
  background-color: #e0e0e0 !important;
  border-color: #c0c0c0 !important;
}

/* 保持按钮组对齐 */
:deep(.fc-toolbar-chunk:first-child) {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 新增样式 */
:deep(.all-count) {
  color: #1890ff;
}
:deep(.todo-count) {
  color: #faad14;
}
:deep(.done-count) {
  color: #52c41a;
}

</style>
