<script setup lang="ts">
// @ts-ignore
import { ref, computed, defineProps } from 'vue'
const props = defineProps({
  overduedaylist: {
    type: Array,
    default: () => [],
  },
  todoaskslist: {
    type: Array,
    default: () => [],
  },
  currentMonth: {
    type: Date,
    default: '',
  },
})
// props.currentMonth: Fri Jan 30 2026 10:00:58 GMT+0800 (中国标准时间)
console.log('props.currentMonth:', props.currentMonth)

// 最大显示任务数
const MAX_DISPLAY_TASKS = 6

// 星期名称
const weekdayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 获取今天是星期几（1-7，周一为1）
const today = new Date()
const todayWeekday = today.getDay() || 7 // 将周日(0)转为7

// 处理任务数据
const moonlist = computed(() => {
  const daylists = [...props.todoaskslist]
  return daylists
    .filter((item:any) => item.isOverdue !== 1)
    .map((item:any) => {
      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: new Date(item?.displayDate),
        start: new Date(item?.displayDate).toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
        }),
        status,
      }
    })
})
const overduelist = computed(() => {
  const daylists = [...props.overduedaylist]
  return daylists.map((item:any) => ({
    id: item.id,
    name: item?.taskName,
    date: new Date(item?.displayDate),
    start: new Date(item?.displayDate).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    }),
    status: '#d34b27', // 逾期任务使用红色
  }))
})
// 合并任务列表
const allTasks = computed(() => {
  return [...moonlist.value, ...overduelist.value]
})

// 生成日历数据
const generateCalendarDays = () => {
  const days = []
  const year = props.currentMonth.getFullYear()
  const month = props.currentMonth.getMonth()
  const today = new Date()

  // 当月第一天
  const firstDay = new Date(year, month, 1)
  // 当月最后一天
  const lastDay = new Date(year, month + 1, 0)
  // 第一周的开始（周一）
  const startDate = new Date(firstDay)
  const dayOfWeek = firstDay.getDay() || 7 // 将周日(0)转为7
  startDate.setDate(startDate.getDate() - dayOfWeek + 1)

  // 生成6周数据
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)
    const isToday = date.toDateString() === today.toDateString()
    const isOtherMonth = date.getMonth() !== month

    // 查找当天的任务
    const dayTasks = allTasks.value.filter((task) => {
      return task.date.toDateString() === date.toDateString()
    })

    days.push({
      day: date.getDate(),
      date: date,
      isOtherMonth: isOtherMonth,
      isToday: isToday,
      tasks: dayTasks,
    })
  }

  return days
}

const calendarDays = computed(() => generateCalendarDays())

// 展开状态管理
const expandedDates = ref({})

// 切换展开/收起状态
const toggleExpand = (date: Date) => {
  const dateStr = date.toDateString()
  expandedDates.value[dateStr] = !expandedDates.value[dateStr]
}

// 检查日期是否展开
const isDateExpanded = (date: Date) => {
  const dateStr = date.toDateString()
  return expandedDates.value[dateStr] || false
}

// 获取过滤后的任务列表
const getFilteredTasks = (day: any) => {
  const allTasks = day.tasks
  if (isDateExpanded(day.date) || allTasks.length <= MAX_DISPLAY_TASKS) {
    return allTasks
  }
  return allTasks.slice(0, MAX_DISPLAY_TASKS)
}

// 跳转到任务详情页
const goTaskDetail = (taskId: number) => {
  uni.navigateTo({
    url: `/pages/schedule/details/index?id=${taskId}`,
  })
}
</script>

<template>
  <view class="moon-calendar">
    <!-- 星期标题 -->
    <view class="weekdays">
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 1 }">{{
        weekdayNames[0]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 2 }">{{
        weekdayNames[1]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 3 }">{{
        weekdayNames[2]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 4 }">{{
        weekdayNames[3]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 5 }">{{
        weekdayNames[4]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 6 }">{{
        weekdayNames[5]
      }}</view>
      <view class="weekday" :class="{ 'today-weekday': todayWeekday === 7 }">{{
        weekdayNames[6]
      }}</view>
    </view>

    <!-- 日历网格 -->
    <view class="calendar-grid">
      <view
        v-for="(day, index) in calendarDays"
        :key="index"
        class="calendar-day"
        :class="{
          'other-month': day.isOtherMonth,
          today: day.isToday,
          expanded: isDateExpanded(day.date),
        }"
      >
        <!-- 日期 -->
        <view class="day-number">{{ day.day }}</view>

        <!-- 任务列表 -->
        <view class="tasks">
          <view
            v-for="task in getFilteredTasks(day)"
            :key="task.id"
            class="task-item"
            @click="goTaskDetail(task.id)"
          >
            <view class="task-row">
              <view
                class="task-dot"
                :style="{ backgroundColor: task.status }"
              ></view>
              <!-- <view class="task-time">{{ task.start }}</view> -->
              <view class="task-name">{{ task.name }}</view>
            </view>
          </view>

          <!-- 任务数量超过最大显示数时显示更多 -->
          <view
            v-if="day.tasks.length > MAX_DISPLAY_TASKS"
            class="more-tasks"
            @click="toggleExpand(day.date)"
          >
            {{ isDateExpanded(day.date) ? '收起' : `展开` }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.moon-calendar {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  padding-left: 10rpx;
  padding-right: 10rpx;
  padding-bottom: 300rpx;
  position: absolute;
  top: 230rpx;
  bottom: 120rpx;
  touch-action: pan-y;
}

.weekdays {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fafafa;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0;
  margin-bottom: 0;
  width: 100%;
}

.weekday {
  text-align: center;
  font-size: 24rpx;
  font-weight: 400;
  color: #606266;
  padding: 6rpx 0;
  border-right: 1rpx solid #e4e7ed;
  border-bottom: 1rpx solid #e4e7ed;

  &:last-child {
    border-right: none;
  }

  &.today-weekday {
    color: #409eff;
    font-weight: 600;
  }
}

.calendar-grid {
  overflow-y: auto;
  overflow-x: hidden;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0;
  height: calc(100% - 100rpx);
  width: 100%;
}

.calendar-day {
  background-color: #ffffff;
  border-radius: 0;
  padding: 8rpx;
  height: 360rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  border-bottom: 1rpx solid #e4e7ed;
  box-shadow: none;
  transition: all 0.2s ease;
  overflow: hidden;

  &:nth-child(7n) {
    border-right: none;
  }

  &.other-month {
    opacity: 0.5;
    background-color: #fafafa;
  }

  &.today {
    background-color: #f5f7fa;
  }

  &.expanded {
    background-color: #f9f9f9;
    border: 1rpx solid #e5e5e5;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    z-index: 10;
  }
}

.day-number {
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
  padding: 2rpx;
  border-radius: 0;
  margin-left: 10rpx;

  .calendar-day.today & {
    color: #409eff;
    font-weight: 600;
  }
}

.tasks {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 300rpx;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.task-item {
  margin-bottom: 8rpx;
  padding: 2rpx;
  transition: all 0.2s;
  cursor: pointer;

  &:active {
    background-color: #f0f0f0;
  }
}

.task-row {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.task-dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  flex: 0 0 8rpx;
}

.task-time {
  font-size: 20rpx;
  color: #606266;
  width: 50rpx;
  flex: 0 0 50rpx;
}

.task-name {
  font-size: 22rpx;
  color: #31373d;
  line-height: 1.2;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  // flex: 1;
  // max-width: calc(100% - 60rpx);
}

.more-tasks {
  font-size: 20rpx;
  color: #409eff;
  margin-top: 4rpx;
  padding: 2rpx 0;
  cursor: pointer;

  &:active {
    text-decoration: underline;
  }
}
</style>
