<script lang="ts" setup>
// @ts-ignore
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  // @ts-ignore
  defineProps,
  watch,
} from 'vue'
import dayjs from 'dayjs'
const props = defineProps({
  todoaskslist: {
    type: Array,
    required: true,
  },
  overduedaylist: {
    type: Array,
    required: true,
  },
  selectedDate: {
    type: Date,
    required: true,
  },
})
// watch(
//   () => [props.overduedaylist, props.todoaskslist],
//   ([overduedaylist, todoaskslist]) => {
//     console.log(todoaskslist.find((item:any) => item.displayDate === '2026-01-26 00:00:00'));

//   }
// )
// 响应式变量跟踪当前时间
const currentTime = ref(new Date())

// 获取当前日期的YYYY-MM-DD格式
const today = computed(() => {
  return currentTime.value.toISOString().split('T')[0]
})

// 跟踪每天每个时间段任务的展开状态
const expandedTimeSlots = ref({})

const dayweek = computed(() => {
  const selected = dayjs(props.selectedDate)
  const dayOfWeek = selected.day() || 7 // 转换周日为7
  const weekStart = dayjs(selected).subtract(dayOfWeek - 1, 'day') // 周一，创建新对象

  const weekDays = []
  const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

  for (let i = 0; i < 7; i++) {
    const currentDay = dayjs(weekStart).add(i, 'day') // 创建新的dayjs对象
    const dateStr = currentDay.format('MM月DD日')
    const weekName = weekNames[currentDay.day()]
    const fullDate = currentDay.format('YYYY-MM-DD')
    weekDays.push({
      display: `${dateStr}-${weekName}`,
      fullDate: fullDate,
    })
  }

  return weekDays
})
// const timeSlots = ref(['00:00', '08:00', '16:00'])
const timeSlots = ref(['08:00', '16:00', '24:00'])


// 处理非逾期任务列表
const weeklist = computed(() => {
  const daylists = [...props.todoaskslist]
  return daylists.map((item: any) => {
    let status = 'Authorizable'
    switch (item.status) {
      case 0: {
        status = '' // 任务未开始或取消
        break
      }
      case 1: {
        if (item?.endTime) {
          const endTime = new Date(item.endTime).getTime()
          const currentTime = Date.now()
          if (endTime <= currentTime) {
            status = 'overdue'
          } else if (
            endTime > currentTime &&
            endTime - currentTime <= 24 * 60 * 60 * 1000
          ) {
            status = 'Authorized'
          }
        }
        break
      }
      case 2: {
        status = 'overdue'
        break
      }
      case 3: {
        status = 'Completed'
        break
      }
      default: {
        break
      }
    }
    return {
      id: item.id,
      name: item.taskName,
      date: dayjs(new Date(item?.displayDate || item?.startTime))
        .format('YYYY-MM-DD HH:mm:ss')
        .split(' ')[0],
      start: dayjs(new Date(item?.displayDate || item?.startTime))
        .format('YYYY-MM-DD HH:mm:ss')
        .split(' ')[1],
      status,
    }
  })
})

// 处理逾期任务列表
const overduelist = computed(() => {
  const daylists = [...props.overduedaylist]
  return daylists.map((item: any) => ({
    id: item.id,
    name: item?.taskName,
    date: dayjs(new Date(item?.displayDate || item?.startTime))
      .format('YYYY-MM-DD HH:mm:ss')
      .split(' ')[0],
    start: dayjs(new Date(item?.displayDate || item?.startTime))
      .format('YYYY-MM-DD HH:mm:ss')
      .split(' ')[1],
    status: item?.isOverdue === 1 ? 'overdue' : '',
  }))
})

// 合并任务列表
const tasks = computed(() => {
  return [...weeklist.value, ...overduelist.value]
})

// 解析时间字符串为分钟数
const parseMinutes = (timeStr) => {
  if (!timeStr) return 0
  const [hh, mm] = timeStr.split(':').map(Number)
  return hh * 60 + mm
}

// 根据任务时间确定时间段
const getTimeSlot = (timeStr) => {
  if (!timeStr) return '08:00'
  const totalMinutes = parseMinutes(timeStr)
  const hours = Math.floor(totalMinutes / 60)
  if (hours < 8) {
    return '08:00'
  } else if (hours < 16) {
    return '16:00'
  } else {
    return '24:00'
  }
}

// 最终任务列表（按时间段分组并排序）
const list = computed(() => {
  return tasks.value
    .map((task) => ({
      ...task,
      Time: getTimeSlot(task.start),
    }))
    .sort((a, b) => {
      // 首先按时间段排序（00:00, 08:00, 16:00）
      const timeOrder = {
        '08:00': 0,
        '16:00': 1,
        '24:00': 2,
      }
      const timeDiff = timeOrder[a.Time] - timeOrder[b.Time]
      if (timeDiff !== 0) {
        return timeDiff
      }

      // 同一时间段内，逾期任务排在前面
      if (a.status === 'overdue' && b.status !== 'overdue') {
        return -1
      }
      if (a.status !== 'overdue' && b.status === 'overdue') {
        return 1
      }

      // 同一状态下，按开始时间排序
      return a.start.localeCompare(b.start)
    })
})
// 格式化时间为HH:MM格式
const formatTime = (date) => {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 计算属性：根据当前时间计算时间线的垂直位置
const timelinePosition = computed(() => {
  const hours = currentTime.value.getHours()
  const minutes = currentTime.value.getMinutes()
  const totalMinutes = hours * 60 + minutes
  const startTime = 8 * 60 // 8:00的分钟数
  const slotDuration = 8 * 60 // 每个时间段8小时 = 480分钟
  const slotHeight = 500 // 每个时间段的高度（rpx）

  // 计算当前时间在时间线中的位置
  let position
  if (totalMinutes < startTime) {
    // 如果当前时间早于8:00，显示在最顶部
    position = 70 // 考虑到表头高度
  } else if (totalMinutes < startTime + slotDuration) {
    // 8:00-16:00时间段
    const minutesInSlot = totalMinutes - startTime
    position = 70 + (minutesInSlot / slotDuration) * slotHeight
  } else if (totalMinutes < startTime + slotDuration * 2) {
    // 16:00-24:00时间段
    const minutesInSlot = totalMinutes - (startTime + slotDuration)
    position = 70 + slotHeight + (minutesInSlot / slotDuration) * slotHeight
  } else {
    // 如果当前时间晚于24:00，显示在最底部
    position = 70 + slotHeight * 2
  }

  return position
})
//Authorizable 可授权
//overdue 已逾期
//Completed 已完成
//Authorized 已授权
const getColor = (status) => {
  if (status === 'overdue') {
    return { leftcolor: '#d34b27', backcolor: '#ffe6e0' }
  } else if (status === 'Authorizable') {
    return { leftcolor: '#215acd', backcolor: '#e4edff' }
  } else if (status === 'Authorized') {
    return { leftcolor: '#ff9429', backcolor: '#ffead6' }
  } else if (status === 'Completed') {
    return { leftcolor: '#339169', backcolor: '#d6efe6' }
  }
  return { leftcolor: '#8c8c8c', backcolor: '#f1f1f1' }
}

// 切换某天某个时间段任务的展开/折叠状态
const toggleExpand = (date, timeSlot) => {
  const key = `${date}_${timeSlot}`
  expandedTimeSlots.value[key] = !expandedTimeSlots.value[key]
}

// 截断任务名称，最多显示4个字符
const truncateTaskName = (name) => {
  if (!name) return ''
  if (name.length <= 8) return name
  return name.substring(0, 8) + '...'
}

// 检查某个时间段任务是否展开
const isExpanded = (date, timeSlot) => {
  const key = `${date}_${timeSlot}`
  return expandedTimeSlots.value[key] || false
}

// 检查是否需要显示展开按钮
const shouldShowExpandButton = (date, timeSlot) => {
  const tasks = list.value.filter(
    (item) => item.date === date && item.Time === timeSlot
  )
  return tasks.length > 4
}

// 定时器变量
let timeUpdateInterval = null

// 组件挂载后启动定时器
onMounted(() => {
  // 每分钟更新一次当前时间
  timeUpdateInterval = setInterval(() => {
    currentTime.value = new Date()
  }, 60000)
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timeUpdateInterval) {
    clearInterval(timeUpdateInterval)
  }
})
</script>
<template>
  <view class="box-week">
    <!-- <view class="yellow-time-line" :style="{ top: `${timelinePosition}rpx` }">
      <text class="yellow-time-line-text">{{ formatTime(currentTime) }}</text>
    </view> -->

    <table border="1">
      <thead>
        <tr>
          <th class="corner-header">GMT+8</th>
          <th
            class="column-header"
            v-for="item in dayweek"
            :key="item.fullDate"
            :class="{ 'today-highlight': item.fullDate === today }"
          >
            {{ item.display }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="time in timeSlots"
          :key="time"
          style="
            height: 500rpx;
            overflow: hidden;
            min-height: 500rpx;
            max-height: 500rpx;
          "
        >
          <th
            class="row-header"
            style="height: 500rpx; min-height: 500rpx; max-height: 500rpx"
          >
            {{ time }}
          </th>
          <td
            v-for="val in 7"
            :key="val"
            :class="{
              'expanded-slot': isExpanded(dayweek[val - 1].fullDate, time),
            }"
            style="
              height: 500rpx;
              min-height: 500rpx;
              max-height: 500rpx;
              overflow: visible;
              position: relative;
            "
          >
            <!-- 原始任务列表（最多显示4个） -->
            <view
              v-if="!isExpanded(dayweek[val - 1].fullDate, time)"
              style="
                height: 100%;
                overflow: hidden;
                display: flex;
                flex-direction: column;
              "
            >
              <template
                v-for="itemdev in list
                  .filter(
                    (item) =>
                      item.date === dayweek[val - 1].fullDate &&
                      item.Time === time
                  )
                  .slice(0, 4)"
                :key="itemdev.id + itemdev.Time"
              >
                <view
                  class="data-dev"
                  :style="{
                    backgroundColor: getColor(itemdev?.status)?.backcolor,
                  }"
                >
                  <view
                    class="data-dev-left"
                    :style="{
                      backgroundColor: getColor(itemdev?.status)?.leftcolor,
                    }"
                  >
                  </view>
                  <view class="data-dev-rigth">
                    <view style="font-size: 28rpx; font-family: 500">{{
                      truncateTaskName(itemdev.name)
                    }}</view>
                    <view
                      style="color: #86909c; font-size: 24rpx; font-family: 400"
                      >{{ itemdev.start }}</view
                    >
                  </view>
                </view>
              </template>

              <!-- 收起按钮（仅在非展开状态显示） -->
              <view
                v-if="
                  shouldShowExpandButton(dayweek[val - 1].fullDate, time) &&
                  !isExpanded(dayweek[val - 1].fullDate, time)
                "
                class="expand-btn"
                @tap="toggleExpand(dayweek[val - 1].fullDate, time)"
              >
                <text
                  >还有
                  {{
                    list.filter(
                      (item) =>
                        item.date === dayweek[val - 1].fullDate &&
                        item.Time === time
                    ).length - 4
                  }}
                  个任务...</text
                >
              </view>
            </view>

            <!-- 展开的任务列表（使用绝对定位，不影响原始高度） -->
            <view
              v-if="
                isExpanded(dayweek[val - 1].fullDate, time) &&
                shouldShowExpandButton(dayweek[val - 1].fullDate, time)
              "
              :style="{
                position: 'absolute',
                top: '0',
                left: '0',
                right: '0',
                zIndex: time === '8:00' ? 3 : time === '16:00' ? 2 : 1,
                background: 'rgba(255, 255, 255, 0.95)',
                border: '1px solid rgba(24, 144, 255, 0.2)',
                borderRadius: '8rpx',
                boxShadow: '0 4rpx 12rpx rgba(24, 144, 255, 0.15)',
                padding: '12rpx',
                display: 'flex',
                flexDirection: 'column',
              }"
            >
              <template
                v-for="itemdev in list.filter(
                  (item) =>
                    item.date === dayweek[val - 1].fullDate &&
                    item.Time === time
                )"
                :key="itemdev.id + itemdev.Time + 'expanded'"
              >
                <view
                  class="data-dev"
                  :style="{
                    backgroundColor: getColor(itemdev?.status)?.backcolor,
                  }"
                >
                  <view
                    class="data-dev-left"
                    :style="{
                      backgroundColor: getColor(itemdev?.status)?.leftcolor,
                    }"
                  >
                  </view>
                  <view class="data-dev-rigth">
                    <view style="font-size: 28rpx; font-family: 500">{{
                      truncateTaskName(itemdev.name)
                    }}</view>
                    <view
                      style="color: #86909c; font-size: 24rpx; font-family: 400"
                      >{{ itemdev.start }}</view
                    >
                  </view>
                </view>
              </template>

              <!-- 收起按钮（仅在展开状态显示，位于展开列表的最后） -->
              <view
                class="expand-btn"
                @tap="toggleExpand(dayweek[val - 1].fullDate, time)"
                :style="{
                  marginTop: '12rpx',
                  position: 'relative',
                  zIndex: time === '8:00' ? 4 : time === '16:00' ? 3 : 2,
                }"
              >
                <text>收起</text>
              </view>
            </view>
          </td>
        </tr>
      </tbody>
    </table>
  </view>
</template>
<style lang="scss" scoped>
.box-week {
  width: 100%;
  height: 1090rpx;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  background: #fff;
  .yellow-time-line {
    width: 100%;
    min-width: calc(100% - 176rpx);
    height: 2px;
    background-color: #eb5e12;
    z-index: 5;
    position: absolute;
    left: 176rpx;
    transition: top 0.5s ease;
    .yellow-time-line-text {
      font-size: 28rpx;
      position: absolute;
      left: -92rpx;
      top: -18rpx;
      color: #eb5e12;
      background: transparent;
      width: 80rpx;
      text-align: right;
    }
  }
  table {
    border: none;
    border-collapse: collapse;
    min-width: 100%;
    th {
      padding: 12px 20px;
      // text-align: center;
      white-space: nowrap;
      background: #fff;
      // overflow-y: overlay;
    }

    td {
      vertical-align: top;
      padding: 8px 8px;
    }

    .data-dev {
      overflow: hidden;
      width: 100%;
      height: 100rpx;
      border-radius: 8px;
      display: flex;
      gap: 6px;
      align-items: center;
      // background-color: #FCE3DD;
      // border: 1px solid red;
      margin-bottom: 8px;

      .data-dev-left {
        width: 6px;
        height: 100%;
        // background-color: #D24823;
        border-radius: 6px 0 0 6px;
      }

      .data-dev-rigth {
        flex: 1;
        overflow: hidden;

        view:first-child {
          font-size: 28rpx !important;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        view:last-child {
          font-size: 24rpx !important;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    // 左上角固定 - 最高优先级
    .corner-header {
      position: sticky;
      left: 0;
      top: 0;
      z-index: 5;
      color: #86909c;
      font-size: 28rpx;
      font-weight: 400;

      // 下边框
      &::before {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: -3px;
        height: 1px;
        background: #ccc;
        z-index: 6;
      }

      // 右边框
      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        bottom: -3px;
        width: 1px;
        background: #ccc;
        z-index: 6;
      }
    }

    // 顶部列标题固定
    .column-header {
      position: sticky;

      // height: 70rpx;
      top: 0;

      z-index: 4;
      // background: #f5f5f5;
      font-size: 32rpx;
      font-weight: 500;
      color: #31373d;
      // color: #f5f5f5;
      // text-align: left !important;
      // vertical-align: left !important;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: -3px;
        height: 1px;
        background: #ccc;
        z-index: 5;
      }
    }

    // 左侧行标题固定
    .row-header {
      height: 500rpx;
      position: sticky;
      left: 0;
      z-index: 4;
      vertical-align: bottom;
      color: #86909c;
      font-size: 28rpx;
      font-weight: 400;

      &::after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        bottom: -3px;
        width: 1px;
        background: #ccc;
        z-index: 5;
      }
    }

    // 展开/折叠按钮样式
    .expand-btn {
      position: relative;
      margin-top: 8rpx;
      margin-left: 8rpx;
      margin-right: 8rpx;
      height: 60rpx;
      background: transparent;
      // border: 1px solid #1890ff;
      // border-radius: 8rpx;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      color: #1890ff;
      transition: all 0.3s ease;
      z-index: 0;
    }

    .expand-btn:active {
      background: rgba(24, 144, 255, 0.06);
      color: #40a9ff;
    }

    .expand-btn text {
      display: inline-block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
      padding: 0 12rpx;
    }

    // 展开时间段的高亮样式
    .expanded-slot {
      background-color: rgba(24, 144, 255, 0.06);
      // border: 1px solid rgba(24, 144, 255, 0.2);
      border-radius: 8rpx;
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.1);
      transition: all 0.3s ease;
    }

    // 当前日期高亮样式
    .today-highlight {
      color: #215acd !important;
    }
  }
}
</style>
