<script setup lang="ts">
import { computed } from 'vue';
import { useRouter } from 'vue-router';

const props = defineProps({
  daylist: {
    type: Array,
    default: () => [],
  },
  selectedDate: {
    type: String,
    default: '',
  },
  overduedaylist: {
    type: Array,
    default: () => [],
  },
});
// displayDate 显示时间来判断今日明日
// isOverdue 是否逾期 是否超期0否1是
const router = useRouter();
// 跳转至任务详情页
const handleTaskClick = (task: any) => {
  if (task.formType === 'workTask') {
    router.push(`/task/taskWaiting?id=${task.templateId}`);
  } else {
    router.push(`/schedule/detail/${task.id}`);
  }
};
// watch(
//   () => todaylist.value,
//   (newVal) => {
//     console.log(newVal);
//   },
// );
// 逾期任务列表
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,
      authStatusInfo: getAuthStatus(item),
      overduedays: `已逾期${overduedays}天`,
    };
  });
});
// 今日任务列表
const todaylist = computed(() => {
  if (!props.selectedDate || props.daylist.length === 0) return [];
  const [year, month, day] = props.selectedDate.split('-').map(Number);
  // @ts-ignore
  const selected = new Date(year, month - 1, day);
  const selectedYear = selected.getFullYear();
  const selectedMonth = selected.getMonth();
  const selectedDay = selected.getDate();
  return props.daylist
    .filter((item: any) => {
      if (!item.displayDate) return false;
      const taskDate = new Date(item.displayDate);
      return (
        taskDate.getFullYear() === selectedYear &&
        taskDate.getMonth() === selectedMonth &&
        taskDate.getDate() === selectedDay &&
        item.isOverdue !== '1' // 排除逾期任务
      );
    })
    .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,
            authStatusInfo: getAuthStatus(item),
            remainingTime,
            timeDiff,
          };
        } catch (error) {
          console.error('日期解析错误:', error);
          return {
            ...item,
            authStatusInfo: getAuthStatus(item),
            remainingTime: '时间格式错误',
            timeDiff: 0,
          };
        }
      }

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

  // 解析选中日期并加一天得到明日日期（使用字符串分割确保正确解析为本地时间）
  const [year, month, day] = props.selectedDate.split('-').map(Number);
  // @ts-ignore
  const selected = new Date(year, month - 1, day);
  const tomorrow = new Date(selected);
  tomorrow.setDate(tomorrow.getDate() + 1);

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

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

          // 计算剩余时间（毫秒转天、小时、分钟）
          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));
          // console.log(days, hours, minutes);

          // 格式化剩余时间
          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,
            authStatusInfo: getAuthStatus(item),
            remainingTime,
            timeDiff,
          };
        } catch (error) {
          console.error('日期解析错误:', error);
          return {
            ...item,
            authStatusInfo: getAuthStatus(item),
            remainingTime: '时间格式错误',
            timeDiff: 0,
          };
        }
      }

      return item;
    });
});
// 颜色映射
const authStatusMap = {
  0: {
    name: '可授权',
    // color: '#215ACD',
    backcolr: '#215ACD',
  },
  1: {
    name: '已授权',
    // color: '#339169',
    backcolr: '#339169',
  },
  2: {
    name: '被授权',
    // color: '#EB5E12',
    backcolr: '#EB5E12',
  },
} as any;

const getAuthStatus = (task: any) => {
  if (task?.authStatus > 0) {
    return authStatusMap[task?.authStatus];
  }
  if (task?.isLicensable === 1 && task?.authStatus === 0) {
    return authStatusMap[0];
  }
  return null;
  // if (task?.isLicensable === '1' && task?.authStatus === '0') {
  //   return authStatusMap[1];
  // }
  // return authStatusMap[task?.authStatus];
};
</script>

<template>
  <div>
    <!-- 逾期待处理 -->
    <div class="mb-6">
      <h3 class="mb-3 text-lg font-semibold">逾期待处理</h3>
      <div
        class="grid auto-rows-fr grid-cols-[repeat(auto-fill,minmax(240px,1fr))] justify-items-start gap-3"
      >
        <div
          v-for="task in overduelist"
          :key="task.id"
          class="h-[96px] w-[240px] cursor-pointer rounded shadow-sm transition-all hover:shadow-md"
          @click="handleTaskClick(task)"
        >
          <div
            class="flex h-8 items-center justify-center rounded-t text-sm font-medium text-white"
            :style="{ backgroundColor: '#D34B27' }"
          >
            {{ task.overduedays }}
          </div>
          <div
            class="flex h-[64px] items-center justify-between rounded-b border border-t-0 border-gray-200 p-4"
            :style="{ backgroundColor: '#FFE6E0' }"
          >
            <div class="flex items-center" style="margin-right: 8px">
              <span
                class="flex-none rounded px-2 py-0.5 text-xs font-medium"
                style="color: #ffffff"
                :style="{
                  backgroundColor: task?.authStatusInfo?.backcolr || '',
                }"
              >
                {{ task?.authStatusInfo?.name || '' }}
              </span>
            </div>
            <div class="flex min-w-0 flex-1 items-center">
              <div class="min-w-0">
                <el-tooltip
                  :content="task?.taskName"
                  placement="top"
                  :show-after="500"
                >
                  <div class="truncate font-medium">
                    {{ task?.taskName }}
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="overduelist.length === 0" class="no-data">暂无数据</div>
    </div>
    <!-- 当日任务 -->
    <div class="mb-6">
      <h3 class="mb-3 text-lg font-semibold">当日</h3>
      <div
        class="grid auto-rows-fr grid-cols-[repeat(auto-fill,minmax(240px,1fr))] justify-items-start gap-3"
      >
        <div
          v-for="task in todaylist"
          :key="task.id"
          class="h-[96px] w-[240px] cursor-pointer rounded shadow-sm transition-all hover:shadow-md"
          @click="handleTaskClick(task)"
        >
          <div
            class="flex h-8 items-center justify-center rounded-t text-sm font-medium text-white"
            :style="{
              backgroundColor: task.completeTime
                ? task.status === 0
                  ? '#86909C'
                  : '#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,
            }"
          >
            {{
              task.completeTime
                ? `${task.completeTime}${task.status === 0 ? '取消' : '完成'}`
                : task?.remainingTime?.dayobj?.day !== ''
                  ? task?.remainingTime?.dayobj?.day
                  : task?.remainingTime?.hours?.hour !== ''
                    ? task?.remainingTime?.hours?.hour
                    : task?.remainingTime?.minutes?.minute !== ''
                      ? task?.remainingTime?.minutes?.minute
                      : ''
            }}
          </div>
          <div
            class="flex h-[64px] items-center justify-between rounded-b border border-t-0 border-gray-200 p-4"
            :style="{
              backgroundColor: task.completeTime
                ? task.status === 0
                  ? '#F1F1F1'
                  : '#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,
            }"
          >
            <div class="flex items-center" style="margin-right: 8px">
              <span
                class="flex-none rounded px-2 py-0.5 text-xs font-medium"
                style="color: #ffffff"
                :style="{
                  backgroundColor: task?.authStatusInfo?.backcolr || '',
                }"
              >
                {{ task?.authStatusInfo?.name || '' }}
              </span>
            </div>
            <div class="flex min-w-0 flex-1 items-center">
              <div class="min-w-0">
                <el-tooltip
                  :content="task?.taskName"
                  placement="top"
                  :show-after="500"
                >
                  <div class="truncate font-medium">{{ task?.taskName }}</div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="todaylist.length === 0" class="no-data">暂无数据</div>
    </div>
    <!-- 明日任务 -->
    <div>
      <h3 class="mb-3 text-lg font-semibold">明日</h3>
      <div
        class="grid auto-rows-fr grid-cols-[repeat(auto-fill,minmax(240px,1fr))] justify-items-start gap-3"
      >
        <div
          v-for="task in tomorrowlist"
          :key="task.id"
          class="h-[96px] w-[240px] cursor-pointer rounded shadow-sm transition-all hover:shadow-md"
          @click="handleTaskClick(task)"
        >
          <div
            class="flex h-8 items-center justify-center rounded-t text-sm font-medium text-white"
            :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,
            }"
          >
            {{
              task.completeTime
                ? `${task.completeTime}${task.status === 0 ? '取消' : '完成'}`
                : task?.remainingTime?.dayobj?.day !== ''
                  ? task?.remainingTime?.dayobj?.day
                  : task?.remainingTime?.hours?.hour !== ''
                    ? task?.remainingTime?.hours?.hour
                    : task?.remainingTime?.minutes?.minute !== ''
                      ? task?.remainingTime?.minutes?.minute
                      : ''
            }}
          </div>
          <div
            class="flex h-[64px] items-center justify-between rounded-b border border-t-0 border-gray-200 p-4"
            :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,
            }"
          >
            <div class="flex items-center" style="margin-right: 8px">
              <span
                class="flex-none rounded px-2 py-0.5 text-xs font-medium"
                style="color: #ffffff"
                :style="{
                  backgroundColor: task?.authStatusInfo?.backcolr || '',
                }"
              >
                {{ task?.authStatusInfo?.name || '' }}
              </span>
            </div>
            <div class="flex min-w-0 flex-1 items-center">
              <div class="min-w-0">
                <el-tooltip
                  :content="task?.taskName"
                  placement="top"
                  :show-after="500"
                >
                  <div class="truncate font-medium">{{ task?.taskName }}</div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="tomorrowlist.length === 0" class="no-data">暂无数据</div>
    </div>
  </div>
</template>

<style scoped>
.no-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 120px;
  margin-top: 16px;
  border-radius: 8px;
  background-color: #f8f9fa;
  color: #6c757d;
  font-size: 18px;
  border: 1px dashed #dee2e6;
}
</style>
