<script setup>
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

import dayjs from 'dayjs';
import { ElCalendar, ElTooltip } from 'element-plus';
// Props from parent component
const props = defineProps(['month', 'daylist', 'overduedaylist']);
// const emit = defineEmits(['update:month']);
// 控制展开状态
const expandedDates = ref({});
// 最大显示任务数
const MAX_DISPLAY_TASKS = 4;
// 模拟任务数据
// const tasks = ref([
//   {
//     id: 1,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-15',
//     start: '23:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 2,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-15',
//     start: '23:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 3,
//     name: '中州大道监控设备维护',
//     date: '2025-12-15',
//     start: '07:59',
//     status: 'not-started',
//     department: '技术部',
//   },
//   {
//     id: 4,
//     name: '农业路交通流量分析',
//     date: '2025-12-15',
//     start: '09:30',
//     status: 'cancelled',
//     department: '数据分析部',
//   },
//   {
//     id: 5,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-16',
//     start: '08:15',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 6,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-16',
//     start: '09:45',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 7,
//     name: '文化路监控系统升级',
//     date: '2025-12-16',
//     start: '07:00',
//     status: 'completed',
//     department: '技术部',
//   },
//   {
//     id: 8,
//     name: '纬五路设备巡检',
//     date: '2025-12-16',
//     start: '08:30',
//     status: 'overdue',
//     department: '运维部',
//   },
//   {
//     id: 9,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-17',
//     start: '10:00',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 10,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-17',
//     start: '11:20',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 11,
//     name: '经三路摄像头调试',
//     date: '2025-12-17',
//     start: '13:15',
//     status: 'not-started',
//     department: '技术部',
//   },
//   {
//     id: 12,
//     name: '东风路设备更新计划',
//     date: '2025-12-17',
//     start: '14:00',
//     status: 'cancelled',
//     department: '采购部',
//   },
//   {
//     id: 13,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-18',
//     start: '09:10',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 14,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-18',
//     start: '10:05',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 15,
//     name: '花园路监控中心改造',
//     date: '2025-12-18',
//     start: '15:00',
//     status: 'completed',
//     department: '技术部',
//   },
//   {
//     id: 16,
//     name: '桐柏路设备维护',
//     date: '2025-12-18',
//     start: '16:30',
//     status: 'overdue',
//     department: '运维部',
//   },
//   {
//     id: 17,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-19',
//     start: '08:20',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 18,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-19',
//     start: '09:05',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 19,
//     name: '大学路监控设备安装',
//     date: '2025-12-19',
//     start: '10:00',
//     status: 'not-started',
//     department: '技术部',
//   },
//   {
//     id: 20,
//     name: '汝河路系统测试',
//     date: '2025-12-19',
//     start: '11:10',
//     status: 'cancelled',
//     department: '质量部',
//   },
//   {
//     id: 21,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-20',
//     start: '14:30',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 22,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-20',
//     start: '15:00',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 23,
//     name: '航海路监控数据分析',
//     date: '2025-12-20',
//     start: '09:00',
//     status: 'completed',
//     department: '数据分析部',
//   },
//   {
//     id: 24,
//     name: '长江路设备巡检',
//     date: '2025-12-20',
//     start: '16:45',
//     status: 'overdue',
//     department: '运维部',
//   },
//   {
//     id: 25,
//     name: '未来路摄像头抓图AI检查',
//     date: '2025-12-21',
//     start: '08:40',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 26,
//     name: '龙飞街摄像头抓图AI检查',
//     date: '2025-12-21',
//     start: '09:25',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 27,
//     name: '嵩山路监控系统优化',
//     date: '2025-12-21',
//     start: '10:50',
//     status: 'not-started',
//     department: '技术部',
//   },
//   {
//     id: 28,
//     name: '紫荆山路设备调试',
//     date: '2025-12-21',
//     start: '11:30',
//     status: 'completed',
//     department: '技术部',
//   },
//   {
//     id: 29,
//     name: '商城路设备维护计划',
//     date: '2025-12-21',
//     start: '13:05',
//     status: 'overdue',
//     department: '运维部',
//   },
//   {
//     id: 30,
//     name: '金水路交通管理培训',
//     date: '2025-12-21',
//     start: '09:15',
//     status: 'cancelled',
//     department: '人力资源部',
//   },
//   {
//     id: 31,
//     name: '龙飞街量缸试水检查',
//     date: '2025-12-17',
//     start: '07:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 32,
//     name: '龙飞街量缸试水检查',
//     date: '2025-12-17',
//     start: '07:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 33,
//     name: '龙飞街量缸试水检查',
//     date: '2025-12-17',
//     start: '07:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 34,
//     name: '龙飞街量缸试水检查',
//     date: '2025-12-17',
//     start: '07:59',
//     status: 'processable',
//     department: '管理部',
//   },
//   {
//     id: 35,
//     name: '龙飞街量缸试水检查',
//     date: '2025-12-17',
//     start: '07:59',
//     status: 'processable',
//     department: '管理部',
//   },
// ]);
const moonlist = computed(() => {
  const daylists = [...props.daylist];
  return daylists
    .filter((item) => item.isOverdue !== '1')
    .map((item) => {
      let status = '#215acd';
      switch (item.status) {
        case 0: {
          status = '#8c8c8c'; // 任务未开始或取消
          break;
        }
        case 1: {
          if (item?.endTime) {
            const endTime = new Date(item.endTime).getTime();
            const currentTime = Date.now();
            if (endTime <= currentTime) {
              status = '#d34b27';
            } else if (
              endTime > currentTime &&
              endTime - currentTime <= 24 * 60 * 60 * 1000
            ) {
              status = '#ff9429';
            }
          }
          break;
        }
        case 2: {
          status = '#d34b27';
          break;
        }
        case 3: {
          status = '#339169';
          break;
        }
        default: {
          break;
        }
      }
      return {
        id: item.id,
        name: item.taskName,
        date: dayjs(new Date(item?.displayDate))
          .format('YYYY-MM-DD HH:mm:ss')
          .split(' ')[0],
        start: dayjs(new Date(item?.displayDate)).format('HH:mm'),
        status,
      };
    });
});
const overduelist = computed(() => {
  const daylists = [...props.overduedaylist];
  return daylists.map((item) => ({
    id: item.id,
    name: item?.taskName,
    date: dayjs(new Date(item?.displayDate))
      .format('YYYY-MM-DD HH:mm:ss')
      .split(' ')[0],
    start: dayjs(new Date(item?.displayDate))
      .format('YYYY-MM-DD HH:mm:ss')
      .split(' ')[1],
    status: item?.isOverdue == '1' ? 'overdue' : '',
  }));
});
const tasks = computed(() => {
  return [...moonlist.value, ...overduelist.value];
});

const getTasksForDate = (date) => {
  // console.log(date, 'data');
  // const dateStr = date.toISOString().split('T')[0];
  const dateStr = dayjs(date).format('YYYY-MM-DD');
  return tasks.value.filter((task) => {
    if (typeof task.date === 'string') {
      return task.date === dateStr;
    }
    return false;
  });
};
// Toggle expand/collapse for a date
const toggleExpand = (date) => {
  const dateStr = date.toISOString().split('T')[0];
  expandedDates.value[dateStr] = !expandedDates.value[dateStr];
};

// Get filtered tasks based on expand state
const getFilteredTasks = (date) => {
  const allTasks = getTasksForDate(date);
  const dateStr = date.toISOString().split('T')[0];
  const isExpanded = expandedDates.value[dateStr] || false;

  if (isExpanded || allTasks.length <= MAX_DISPLAY_TASKS) {
    return allTasks;
  }
  return allTasks.slice(0, MAX_DISPLAY_TASKS);
};
// Check if a date is expanded
const isDateExpanded = (date) => {
  const dateStr = date.toISOString().split('T')[0];
  return expandedDates.value[dateStr] || false;
};

const todayWeek = computed(() => dayjs().day() - 1);

const router = useRouter();

const handleTaskClick = (task) => {
  router.push(`/schedule/detail/${task.id}`);
};
</script>

<template>
  <div class="month-schedule">
    <ElCalendar v-model="props.month">
      <template #date-cell="{ data }">
        <div
          class="calendar-cell"
          :class="{ expanded: isDateExpanded(data.date) }"
        >
          <div class="cell-date-number">
            {{ data.date.getDate() }}
          </div>
          <div class="tasks-container">
            <!-- :class="getTaskStatusClass(task)" -->
            <div
              v-for="task in getFilteredTasks(data.date)"
              :key="task.id"
              class="task-item"
              @click="handleTaskClick(task)"
            >
              <ElTooltip
                :content="`${task.start ? `${task.start} ` : ''}${task.name}${task.department ? ` — ${task.department}` : ''}`"
                placement="top"
              >
                <div class="task-row">
                  <span
                    class="task-dot"
                    :style="{ backgroundColor: task.status }"
                  ></span>
                  <span v-if="task.start || task.time" class="task-time">
                    {{ task.start || task.time }}
                  </span>
                  <span class="task-name">{{ task.name }}</span>
                </div>
              </ElTooltip>
            </div>
            <!-- Expand/Collapse button -->
            <div
              v-if="getTasksForDate(data.date).length > MAX_DISPLAY_TASKS"
              class="expand-button"
              :class="[
                isDateExpanded(data.date) ? 'expand-button-expanded' : '',
              ]"
              @click="toggleExpand(data.date)"
            >
              {{
                expandedDates[data.date.toISOString().split('T')[0]]
                  ? '收起'
                  : `还有 ${getTasksForDate(data.date).length - MAX_DISPLAY_TASKS} 个日程...`
              }}
            </div>
          </div>
        </div>
      </template>
    </ElCalendar>
  </div>
</template>

<style scoped>
:deep(.el-calendar__button-group) {
  display: none;
}
:deep(.el-calendar-table thead th) {
  text-align: left;
  padding-left: 10px;
  color: #d61111;
  font-size: 12px;
  font-weight: 400;
}

/* 今天对应的星期标题高亮 */
:deep(.el-calendar-table thead th:nth-child(1)) {
  /* background-color: v-bind("todayWeek === 0 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 0 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(2)) {
  /* background-color: v-bind("todayWeek === 1 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 1 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(3)) {
  /* background-color: v-bind("todayWeek === 2 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 2 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(4)) {
  /* background-color: v-bind("todayWeek === 3 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 3 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(5)) {
  /* background-color: v-bind("todayWeek === 4 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 4 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(6)) {
  /* background-color: v-bind("todayWeek === 5 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 5 ? '#409eff' : '#959DA8'");
}
:deep(.el-calendar-table thead th:nth-child(7)) {
  /* background-color: v-bind("todayWeek === 6 ? '#409eff' : 'transparent'"); */
  color: v-bind("todayWeek === 6 ? '#409eff' : '#959DA8'");
}

:deep(.el-calendar-table thead th:nth-child(1)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(2)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(3)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(4)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(5)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(6)):before {
  content: '周';
}

:deep(.el-calendar-table thead th:nth-child(7)):before {
  content: '周';
}
.month-schedule {
  width: 100%;
  overflow-x: auto;
}

.calendar-cell {
  position: relative;
  height: 150px;
  padding: 6px 6px 4px 6px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.calendar-cell.expanded {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  background-color: #f9f9f9;
  border: 1px solid #e5e5e5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 6px 6px 4px 6px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: auto !important;
  min-height: 150px;
}

::v-deep .el-calendar-day {
  position: relative;
}

.cell-date-number {
  position: absolute;
  top: 6px;
  left: 8px;
  font-size: 12px;
  /* color: #666; */
  font-weight: 600;
  z-index: 3;
}
.selected {
  color: #409eff;
}
.tasks-container {
  margin-top: 22px;
}

.status-legend {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-indicator.not-started {
  background-color: #ccc;
}

.status-indicator.processable {
  background-color: #67c23a !important;
}

.status-indicator.overdue {
  background-color: #ff0000;
}

.status-indicator.completed {
  background-color: #000;
  position: relative;
}

.status-indicator.completed::after {
  content: '';
  position: absolute;
  top: 50%;
  left: -2px;
  right: -2px;
  height: 1px;
  background-color: #fff;
  transform: rotate(45deg);
}

/* .calendar-cell {
  height: 150px;
  padding: 4px;
  display: flex;
  flex-direction: column;
} */

::v-deep .el-calendar-table__row {
  height: 150px !important;
}

::v-deep .el-calendar-table__row .current {
  height: 150px;
}

::v-deep .el-calendar-table__row .el-calendar-day {
  height: 150px !important;
  min-height: 150px;
}

::v-deep .el-calendar-table__row .el-calendar-day.expanded {
  height: 150px;
}

::v-deep .el-calendar-day {
  position: relative;
}

.date-text {
  font-weight: bold;
  margin-bottom: 4px;
}

.tasks-container {
  flex: 1;
  overflow-y: visible;
}

.calendar-cell:not(.expanded) .tasks-container {
  overflow-y: auto;
}

.task-item {
  margin-bottom: 4px;
  padding: 2px;
  transition: all 0.2s;
  cursor: pointer;
}

.task-item.not-started {
  cursor: default;
}

.task-name {
  font-size: 12px;
  color: #31373d;
  line-height: 1.2;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.task-row {
  display: flex;
  align-items: center;
  gap: 4px;
}
.task-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex: 0 0 8px;
}
.task-time {
  font-size: 11px;
  /* color: #666; */
  color: #31373d;
  width: 30px;
  /* flex: 0 0 40px; */
}

/* Expand button styles */
.expand-button {
  font-size: 11px;
  color: #409eff;
  cursor: pointer;
  margin-top: 4px;
  padding: 2px 0;
}

.expand-button-expanded {
  font-size: 11px;
  color: #409eff;
  cursor: pointer;
  margin-top: 4px;
  margin-bottom: 20px;
  padding: 2px 0;
}

.expand-button:hover {
  /* color: #409eff; */
  text-decoration: underline;
}

/* Task status styles */
.task-item.not-started {
  color: #999;
  pointer-events: none;
}

.task-item.processable {
  color: #000;
}

.task-item.overdue {
  color: #ff0000;
}

.task-item.completed {
  color: #000;
  text-decoration: line-through;
}
</style>
