<script setup lang="ts">
// @ts-ignore
import { computed, defineEmits, defineProps, onMounted, ref, watch } from 'vue'

const props = defineProps({
  overduedaylist: {
    type: Array,
    default: () => [],
  },
  todoaskslist: {
    type: Array,
    default: () => [],
  },
  selectedDate: {
    type: Date,
    default: '',
  },
})
const emit = defineEmits(['handletabs'])
// props.selectedDate:Thu Jan 29 2026 18:47:27 GMT+0800 (中国标准时间)
// console.log(props.selectedDate)
// console.log(new Date(props.selectedDate))
watch(
  () => props.todoaskslist,
  (newVal, oldVal) => {
    if (newVal) {
      console.log(newVal)
    }
  },
)

const tab = ref<string>('全部')
const tabs = ref(['全部', '可授权', '已授权', '被授权'])

// 颜色映射
const authStatusMap = {
  0: {
    name: '可授权',
    color: '#215ACD',
    backcolr: '#E4EDFF',
  },
  1: {
    name: '已授权',
    color: '#339169',
    backcolr: '#D6EFE6',
  },
  2: {
    name: '被授权',
    color: '#EB5E12',
    backcolr: '#FFEAD6',
  },
  null: {
    name: '未知',
    color: '#D34B27',
    backcolr: '#FFE6E0',
  },
} as any

// 逾期任务列表
const overduelist = computed(() => {
  return props.overduedaylist.map((item: any) => {
    // 计算已逾期天数
    let overduedays = 0
    if (item.endTime) {
      try {
        // 获取当前时间（UTC+8时区）
        const now = new Date()
        const currentDate = new Date(
          now.getFullYear(),
          now.getMonth(),
          now.getDate(),
        )

        // 解析任务截止日期
        const taskDate = new Date(item.endTime)
        const deadlineDate = new Date(
          taskDate.getFullYear(),
          taskDate.getMonth(),
          taskDate.getDate(),
        )

        // 计算天数差（毫秒转天数）
        const timeDiff = currentDate.getTime() - deadlineDate.getTime()
        overduedays = Math.ceil(timeDiff / (1000 * 3600 * 24))
      }
      catch (error) {
        console.error('日期解析错误:', error)
        overduedays = 0
      }
    }
    return {
      ...item,
      overduedays: `已逾期${overduedays}天`,
    }
  })
})

// 今日任务
const todaylist = computed(() => {
  if (!props.selectedDate || props.todoaskslist.length === 0)
    return []
  // 解析选中日期，处理不同格式
  let selected: Date
  try {
    if (typeof props.selectedDate === 'string') {
      // @ts-ignore
      if (props.selectedDate.includes('-')) {
        // YYYY-MM-DD 格式
        // @ts-ignore
        const [year, month, day] = props.selectedDate.split('-').map(Number)
        selected = new Date(year, month - 1, day)
      }
      else {
        // 其他字符串格式，直接转换
        selected = new Date(props.selectedDate)
      }
    }
    else {
      // 已经是 Date 对象
      selected = new Date(props.selectedDate)
    }
  }
  catch (error) {
    console.error('选中日期解析错误:', error)
    selected = new Date() // 失败时使用当前日期
  }

  const selectedYear = selected.getFullYear()
  const selectedMonth = selected.getMonth()
  const selectedDay = selected.getDate()

  return props.todoaskslist
    .filter((item: any) => {
      if (!item.displayDate)
        return false
      try {
        const taskDate = new Date(item.displayDate)
        return (
          taskDate.getFullYear() === selectedYear
          && taskDate.getMonth() === selectedMonth
          && taskDate.getDate() === selectedDay
          && item.isOverdue !== '1' // 排除逾期任务
        )
      }
      catch (error) {
        console.error('任务日期解析错误:', error)
        return false
      }
    })
    .map((item: any) => {
      // 如果没有完成时间就计算截止时间
      if (!item.completeTime && item.endTime) {
        try {
          const endTime = new Date(item.endTime)
          const timeDiff = endTime.getTime() - selected.getTime()

          // 计算剩余时间（毫秒转天、小时、分钟）
          const days = Math.floor(timeDiff / (1000 * 3600 * 24))
          const hours = Math.floor(
            (timeDiff % (1000 * 3600 * 24)) / (1000 * 3600),
          )
          const minutes = Math.floor((timeDiff % (1000 * 3600)) / (1000 * 60))

          // 格式化剩余时间
          const remainingTime = {
            dayobj: {
              day: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            hours: {
              hour: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            minutes: {
              minute: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            default: {
              topbackcolor: '',
              mainbackcolor: '',
            },
          }
          if (item.status === 0) {
            remainingTime.dayobj.day += `还剩${days}天截止`
            remainingTime.dayobj.topbackcolor = '#86909C'
            remainingTime.dayobj.mainbackcolor = '#F1F1F1'
          }
          else if (days > 0) {
            remainingTime.dayobj.day += `还剩${days}天截止`
            if (days >= 30) {
              remainingTime.dayobj.topbackcolor = '#86909C'
              remainingTime.dayobj.mainbackcolor = '#F1F1F1'
            }
            else {
              remainingTime.dayobj.topbackcolor = '#215ACD'
              remainingTime.dayobj.mainbackcolor = '#E4EDFF'
            }
          }
          else if (hours > 0) {
            remainingTime.hours.hour += `还剩${hours}小时截止`
            remainingTime.hours.topbackcolor = '#FF9428'
            remainingTime.hours.mainbackcolor = '#FFEAD6'
          }
          else if (minutes > 0) {
            remainingTime.minutes.minute += `还剩${minutes}分钟截止`
            remainingTime.minutes.topbackcolor = '#FF9428'
            remainingTime.minutes.mainbackcolor = '#FFEAD6'
          }
          else {
            remainingTime.default.topbackcolor = '#339169'
            remainingTime.default.mainbackcolor = '#D6EFE6'
          }
          return {
            ...item,
            remainingTime,
            timeDiff,
          }
        }
        catch (error) {
          console.error('日期解析错误:', error)
          return {
            ...item,
            remainingTime: '时间格式错误',
            timeDiff: 0,
          }
        }
      }

      return item
    })
})

// 明日任务列表
const tomorrowlist = computed(() => {
  if (!props.selectedDate || props.todoaskslist.length === 0)
    return []

  // 解析选中日期，处理不同格式
  let selected: Date
  try {
    if (typeof props.selectedDate === 'string') {
      // @ts-ignore
      if (props.selectedDate.includes('-')) {
        // YYYY-MM-DD 格式
        // @ts-ignore
        const [year, month, day] = props.selectedDate.split('-').map(Number)
        selected = new Date(year, month - 1, day)
      }
      else {
        // 其他字符串格式，直接转换
        selected = new Date(props.selectedDate)
      }
    }
    else {
      // 已经是 Date 对象
      selected = new Date(props.selectedDate)
    }
  }
  catch (error) {
    console.error('选中日期解析错误:', error)
    selected = new Date() // 失败时使用当前日期
  }

  // 加一天得到明日日期
  const tomorrow = new Date(selected)
  tomorrow.setDate(tomorrow.getDate() + 1)

  const tomorrowYear = tomorrow.getFullYear()
  const tomorrowMonth = tomorrow.getMonth()
  const tomorrowDay = tomorrow.getDate()

  return props.todoaskslist
    .filter((item: any) => {
      if (!item.displayDate)
        return false
      try {
        const taskDate = new Date(item.displayDate)
        return (
          taskDate.getFullYear() === tomorrowYear
          && taskDate.getMonth() === tomorrowMonth
          && taskDate.getDate() === tomorrowDay
          && item.isOverdue !== '1' // 排除逾期任务
        )
      }
      catch (error) {
        console.error('任务日期解析错误:', error)
        return false
      }
    })
    .map((item: any) => {
      // 如果没有完成时间就计算截止时间
      if (!item.completeTime && item.endTime) {
        try {
          const endTime = new Date(item.endTime)
          const timeDiff = endTime.getTime() - tomorrow.getTime()

          // 计算剩余时间（毫秒转天、小时、分钟）
          const days = Math.floor(timeDiff / (1000 * 3600 * 24))
          const hours = Math.floor(
            (timeDiff % (1000 * 3600 * 24)) / (1000 * 3600),
          )
          const minutes = Math.floor((timeDiff % (1000 * 3600)) / (1000 * 60))

          // 格式化剩余时间
          const remainingTime = {
            dayobj: {
              day: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            hours: {
              hour: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            minutes: {
              minute: '',
              topbackcolor: '',
              mainbackcolor: '',
            },
            default: {
              topbackcolor: '',
              mainbackcolor: '',
            },
          }
          if (days > 0) {
            remainingTime.dayobj.day += `还剩${days}天截止`
            if (days >= 30) {
              remainingTime.dayobj.topbackcolor = '#86909C'
              remainingTime.dayobj.mainbackcolor = '#F1F1F1'
            }
            else {
              remainingTime.dayobj.topbackcolor = '#215ACD'
              remainingTime.dayobj.mainbackcolor = '#E4EDFF'
            }
          }
          else if (hours > 0) {
            remainingTime.hours.hour += `还剩${hours}小时截止`
            remainingTime.hours.topbackcolor = '#FF9428'
            remainingTime.hours.mainbackcolor = '#FFEAD6'
          }
          else if (minutes > 0) {
            remainingTime.minutes.minute += `还剩${minutes}分钟截止`
            remainingTime.minutes.topbackcolor = '#FF9428'
            remainingTime.minutes.mainbackcolor = '#FFEAD6'
          }
          else {
            remainingTime.default.topbackcolor = '#339169'
            remainingTime.default.mainbackcolor = '#D6EFE6'
          }
          return {
            ...item,
            remainingTime,
            timeDiff,
          }
        }
        catch (error) {
          console.error('日期解析错误:', error)
          return {
            ...item,
            remainingTime: '时间格式错误',
            timeDiff: 0,
          }
        }
      }

      return item
    })
})

// 按类型分组的任务列表
const filList = computed(() => {
  return {
    已逾期: overduelist.value,
    今日: todaylist.value,
    明日: tomorrowlist.value,
  }
})

// 跳转到任务详情页
function goTaskDetail(taskId: number) {
  uni.navigateTo({
    url: `/pages/schedule/details/index?id=${taskId}`,
  })
}
function handleClick(item: string) {
  tab.value = item
  emit('handletabs', tab.value)
}
</script>

<template>
  <view class="box-day">
    <view class="tab">
      <view
        v-for="item in tabs"
        :key="item"
        class="tab-item" :class="[{ 'tab-item-active': tab === item }]"
        @click="handleClick(item)"
      >
        {{ item }}
        <view v-if="tab === item" class="tab-item-line" />
      </view>
    </view>
    <view
      style="
        display: flex;
        flex-direction: column;
        gap: 28rpx;
        height: calc(100% - 96rpx);
        overflow-y: auto;
        box-sizing: border-box;
        padding: 0 16rpx 450rpx 16rpx;
      "
    >
      <!-- 已逾期 -->
      <view>
        <view class="title">
          已逾期（{{ filList['已逾期'].length }}）
        </view>
        <view
          v-for="task in filList['已逾期']"
          :key="task.id"
          class="list_dev"
          style="background-color: #ffe6e0"
          @click="goTaskDetail(task.id)"
        >
          <view class="list_dev_left" style="background-color: #d34b27" />
          <view class="list_dev_right">
            <text style="color: #31373d">{{ task.taskName }}</text>
            <view class="list_dev_right_text">
              <view
                class="list_dev_right_top"
                :style="{
                  background:
                    task?.isLicensable === 1 && task?.authStatus === 0
                      ? '#215ACD'
                      : authStatusMap[task?.authStatus || 'null']?.color,
                }"
              >
                {{
                  task?.isLicensable === 1 && task?.authStatus === 0
                    ? '可授权'
                    : authStatusMap[task?.authStatus || 'null']?.name
                }}
              </view>
              <view class="list_dev_right_bottom" style="color: #d85e3e">
                {{
                  task.overduedays
                }}
              </view>
            </view>
          </view>
        </view>
        <view v-if="filList['已逾期'].length === 0" class="no-data">
          暂无数据
        </view>
      </view>
      <!-- 今日 -->
      <view>
        <view class="title">
          今日（{{ filList['今日'].length }}）
        </view>
        <view
          v-for="task in filList['今日']"
          :key="task.id"
          class="list_dev"
          :style="{
            backgroundColor: task.completeTime
              ? '#D6EFE6'
              : task?.remainingTime?.dayobj?.day !== ''
                ? task?.remainingTime?.dayobj?.mainbackcolor
                : task?.remainingTime?.hours?.hour !== ''
                  ? task?.remainingTime?.hours?.mainbackcolor
                  : task?.remainingTime?.minutes?.minute !== ''
                    ? task?.remainingTime?.minutes?.mainbackcolor
                    : task?.remainingTime?.default?.mainbackcolor,
          }"
          @click="goTaskDetail(task.id)"
        >
          <view
            class="list_dev_left"
            :style="{
              backgroundColor: task.completeTime
                ? '#339169'
                : task?.remainingTime?.dayobj?.day !== ''
                  ? task?.remainingTime?.dayobj?.topbackcolor
                  : task?.remainingTime?.hours?.hour !== ''
                    ? task?.remainingTime?.hours?.topbackcolor
                    : task?.remainingTime?.minutes?.minute !== ''
                      ? task?.remainingTime?.minutes?.topbackcolor
                      : task?.remainingTime?.default?.topbackcolor,
            }"
          />
          <view class="list_dev_right">
            <text style="color: #31373d">{{ task.taskName }}</text>
            <view class="list_dev_right_text">
              <view
                class="list_dev_right_top"
                :style="{
                  background:
                    task?.isLicensable === 1 && task?.authStatus === 0
                      ? '#215ACD'
                      : authStatusMap[task?.authStatus || 'null']?.color,
                }"
              >
                {{
                  task?.isLicensable === 1 && task?.authStatus === 0
                    ? '可授权'
                    : authStatusMap[task?.authStatus || 'null']?.name
                }}
              </view>
              <view class="list_dev_right_bottom">
                {{
                  task.completeTime
                    ? `${task.completeTime}完成`
                    : task?.remainingTime?.dayobj?.day !== ''
                      ? task?.remainingTime?.dayobj?.day
                      : task?.remainingTime?.hours?.hour !== ''
                        ? task?.remainingTime?.hours?.hour
                        : task?.remainingTime?.minutes?.minute !== ''
                          ? task?.remainingTime?.minutes?.minute
                          : ''
                }}
              </view>
            </view>
          </view>
        </view>
        <view v-if="filList['今日'].length === 0" class="no-data">
          暂无数据
        </view>
      </view>
      <!-- 明日 -->
      <view>
        <view class="title">
          明日（{{ filList['明日'].length }}）
        </view>
        <view
          v-for="task in filList['明日']"
          :key="task.id"
          class="list_dev"
          :style="{
            backgroundColor: task.completeTime
              ? '#D6EFE6'
              : task?.remainingTime?.dayobj?.day !== ''
                ? task?.remainingTime?.dayobj?.mainbackcolor
                : task?.remainingTime?.hours?.hour !== ''
                  ? task?.remainingTime?.hours?.mainbackcolor
                  : task?.remainingTime?.minutes?.minute !== ''
                    ? task?.remainingTime?.minutes?.mainbackcolor
                    : task?.remainingTime?.default?.mainbackcolor,
          }"
          @click="goTaskDetail(task.id)"
        >
          <view
            class="list_dev_left"
            :style="{
              backgroundColor: task.completeTime
                ? '#339169'
                : task?.remainingTime?.dayobj?.day !== ''
                  ? task?.remainingTime?.dayobj?.topbackcolor
                  : task?.remainingTime?.hours?.hour !== ''
                    ? task?.remainingTime?.hours?.topbackcolor
                    : task?.remainingTime?.minutes?.minute !== ''
                      ? task?.remainingTime?.minutes?.topbackcolor
                      : task?.remainingTime?.default?.topbackcolor,
            }"
          />
          <view class="list_dev_right">
            <text style="color: #31373d">{{ task.taskName }}</text>
            <view class="list_dev_right_text">
              <view
                class="list_dev_right_top"
                :style="{
                  background:
                    task?.isLicensable === 1 && task?.authStatus === 0
                      ? '#215ACD'
                      : authStatusMap[task?.authStatus || 'null']?.color,
                }"
              >
                {{
                  task?.isLicensable === 1 && task?.authStatus === 0
                    ? '可授权'
                    : authStatusMap[task?.authStatus || 'null']?.name
                }}
              </view>
              <view class="list_dev_right_bottom">
                {{
                  task.completeTime
                    ? `${task.completeTime}完成`
                    : task?.remainingTime?.dayobj?.day !== ''
                      ? task?.remainingTime?.dayobj?.day
                      : task?.remainingTime?.hours?.hour !== ''
                        ? task?.remainingTime?.hours?.hour
                        : task?.remainingTime?.minutes?.minute !== ''
                          ? task?.remainingTime?.minutes?.minute
                          : ''
                }}
              </view>
            </view>
          </view>
        </view>
        <view v-if="filList['明日'].length === 0" class="no-data">
          暂无数据
        </view>
      </view>
      <view
        style="
          color: #bbbdbf;
          font-size: 24rpx;
          font-weight: 400;
          margin: 0 auto;
        "
      >
        - 加载完毕 -
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.box-day {
  padding-left: 8px;
  padding-right: 8px;
  height: calc(100vh - 120rpx);
  overflow-y: auto;
}
.tab {
  display: flex;
  height: 96rpx;
  width: 80%;
  align-items: center;
  // border: 1px solid red;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  .tab-item {
    font-size: 32rpx;
    font-weight: 400;
    color: #4e5969;
    position: relative;
  }
  .tab-item-active {
    color: #31373d;
    font-weight: 500;
  }
  .tab-item-line {
    position: absolute;
    left: 30%;
    width: 46%;
    height: 4rpx;
    background-color: #215acd;
    margin-top: 8rpx;
  }
}

.title {
  font-size: 36rpx;
  color: #31373d;
  font-weight: 500;
  margin-bottom: 24rpx;
}

.list_dev {
  width: 100%;
  height: 120rpx;
  // background-color: #ffe6e0;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  gap: 14px;
  margin-bottom: 30rpx;
  .list_dev_left {
    width: 10px;
    height: 100%;
    background-color: #d34b27;
    border-radius: 10px 0 0 10px;
  }
  .list_dev_right {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    height: 100%;
    font-size: 28rpx;
    font-weight: 400;
    .list_dev_right_text {
      width: 55%;
      position: relative;
      height: 100%;
      .list_dev_right_top {
        border-radius: 0 10px 0 10px;
        position: absolute;
        top: 0;
        right: 0px;
        width: 88rpx;
        height: 40rpx;
        // background-color: #215acd;
        color: white;
        font-size: 24rpx;
        font-weight: 400;
        line-height: 20px;
        padding-left: 8px;
      }
      .list_dev_right_bottom {
        position: absolute;
        bottom: 6px;
        right: 8px;
        font-size: 28rpx;
        font-weight: 400;
        color: #31373d;
        word-wrap: normal;
      }
    }
  }
}

.no-data {
  text-align: center;
  color: #86909c;
  font-size: 24rpx;
  padding: 40rpx 0;
  background-color: #f1f1f1;
  border-radius: 10px;
  margin-bottom: 30rpx;
}
</style>
