<template>
  <div class="task-detail">
    <!-- 返回按钮（可选） -->
    <div v-if="showBackButton" class="back-header">
      <el-button @click="handleBack" :icon="ArrowLeft">{{ backButtonText }}</el-button>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 任务详情 -->
    <div v-else-if="taskVO" class="task-content">

      <!-- 任务基本信息卡片 -->
      <div class="task-info-card">
        <div class="section-header">
          <div class="header-bar"></div>
          <span class="header-text">任务信息</span>
        </div>
        <div class="task-info-section">
          <!-- 任务信息标题 -->

          <!-- 任务标题 -->
          <h1 class="task-title">{{ taskVO.learningTask.name }}</h1>

          <!-- 任务描述 -->
          <p v-if="taskVO.learningTask.description" class="task-description">
            {{ taskVO.learningTask.description }}
          </p>

          <!-- 任务元信息 -->
          <div class="task-meta">
            <div class="meta-item">
              <img src="@/assets/imgs/default-avatar.png" alt="创建者" class="creator-avatar" />
              <span>{{ taskVO.learningTask.creator || '系统' }}</span>
            </div>
            <div class="meta-divider"></div>
            <div class="meta-item">
              <img src="@/assets/imgs/clock.svg" alt="时间" class="meta-icon" />
              <span>截止时间：{{ formatDate(taskVO.learningTask.endTime) }}{{ getDeadlineText() }}</span>
            </div>
            <div class="meta-divider"></div>
            <div class="meta-item">
              <img src="@/assets/imgs/book-read.svg" alt="学习" class="meta-icon" />
              <span>{{ taskVO.taskUsers?.length || 0 }}人学习</span>
            </div>
          </div>

          <!-- 任务统计卡片 -->
          <div class="task-stats">
            <div class="stat-card">
              <div class="stat-content">
                <div class="stat-label">总任务数</div>
                <div class="stat-value">{{ taskVO.totalTaskNum || 0 }}</div>
              </div>
              <img src="@/assets/imgs/task-total.svg" alt="总任务数" class="meta-icon" />
            </div>

            <div class="stat-card">
              <div class="stat-content">
                <div class="stat-label">已完成</div>
                <div class="stat-value">{{ taskVO.completedTaskNum || 0 }}</div>
              </div>
              <img src="@/assets/imgs/task-finish.svg" alt="已完成" class="meta-icon" />
            </div>

            <div class="stat-card">
              <div class="stat-content">
                <div class="stat-label">学习中</div>
                <div class="stat-value">{{ taskVO.learningTaskNum || 0 }}</div>
              </div>
              <img src="@/assets/imgs/task-learning.svg" alt="学习中" class="meta-icon" />
            </div>

            <div class="stat-card">
              <div class="stat-content">
                <div class="stat-label">未开始</div>
                <div class="stat-value">{{ taskVO.notStartTaskNum || 0 }}</div>
              </div>
              <img src="@/assets/imgs/task-notstart.svg" alt="未开始" class="meta-icon" />
            </div>
          </div>

          <!-- 进度条区域 -->
          <div v-if="taskVO.totalTaskNum && taskVO.totalTaskNum > 0" class="progress-section">
            <div class="progress-header">
              <span class="progress-label">当前任务进度</span>
              <span class="progress-value">已完成{{ progressPercent }}%</span>
            </div>
            <div class="progress-bar-container">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="task-content-section">
        <div class="section-header">
          <div class="header-bar"></div>
          <span class="header-text">任务信息</span>
        </div>

        <!-- 课程列表 -->
        <el-card v-if="taskVO.taskCourses && taskVO.taskCourses.length > 0" class="course-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon">
                  <VideoPlay />
                </el-icon>
                <span class="header-title">学习课程</span>
              </div>
              <span class="item-count">共 {{ taskVO.taskCourses.length }} 门课程</span>
            </div>
          </template>

          <div class="course-list">
            <div v-for="(course, index) in taskVO.taskCourses" :key="course.courseID" class="course-item"
              @click="handleCourseClick(course)">
              <div class="course-index">{{ index + 1 }}</div>
              <div class="course-info">
                <div class="course-name-row">
                  <span class="course-name">{{ course.courseName }}</span>
                  <el-tag v-if="course.required" type="danger" size="small" effect="plain">
                    必修
                  </el-tag>
                </div>
                <div class="course-meta">
                  <div class="status-info">
                    <el-tag :type="getItemStatusType(course.status)" size="small">
                      {{ getItemStatusText(course.status) }}
                    </el-tag>
                    <span v-if="course.status === 2 && course.completeTime" class="complete-time">
                      <el-icon>
                        <CircleCheck />
                      </el-icon>
                      {{ formatDateTime(course.completeTime) }}
                    </span>
                  </div>
                  <div v-if="course.progress !== null && course.progress !== undefined" class="progress-info">
                    <span class="progress-text">{{ course.progress }}%</span>
                  </div>
                </div>
              </div>
              <div class="course-action">
                <el-button type="primary"
                  :icon="course.status === 2 ? CircleCheck : (course.status === 1 ? VideoPlay : Reading)"
                  :disabled="course.status === 2" @click.stop="handleCourseClick(course)">
                  {{ course.status === 2 ? '已完成' : (course.status === 1 ? '继续学习' : '开始学习') }}
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 文章/资源列表 -->
        <el-card v-if="taskVO.taskResources && taskVO.taskResources.length > 0" class="resource-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon class="header-icon">
                  <Document />
                </el-icon>
                <span class="header-title">学习资源</span>
              </div>
              <span class="item-count">共 {{ taskVO.taskResources.length }} 篇文章</span>
            </div>
          </template>

          <div class="resource-list">
            <div v-for="(resource, index) in taskVO.taskResources" :key="resource.resourceID" class="resource-item"
              @click="handleResourceClick(resource)">
              <div class="resource-index">{{ index + 1 }}</div>
              <div class="resource-info">
                <div class="resource-name-row">
                  <span class="resource-name">{{ resource.resourceName }}</span>
                  <el-tag v-if="resource.required" type="danger" size="small" effect="plain">
                    必修
                  </el-tag>
                </div>
                <div class="resource-meta">
                  <div class="status-info">
                    <el-tag :type="getItemStatusType(resource.status)" size="small">
                      {{ getItemStatusText(resource.status) }}
                    </el-tag>
                    <span v-if="resource.status === 2 && resource.completeTime" class="complete-time">
                      <el-icon>
                        <CircleCheck />
                      </el-icon>
                      {{ formatDateTime(resource.completeTime) }}
                    </span>
                  </div>
                  <div v-if="resource.progress !== null && resource.progress !== undefined" class="progress-info">
                    <span class="progress-text">{{ resource.progress }}%</span>
                  </div>
                </div>
              </div>
              <div class="resource-action">
                <el-button type="primary"
                  :icon="resource.status === 2 ? CircleCheck : (resource.status === 1 ? Reading : View)"
                  :disabled="resource.status === 2" @click.stop="handleResourceClick(resource)">
                  {{ resource.status === 2 ? '已完成' : (resource.status === 1 ? '继续阅读' : '开始阅读') }}
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 空状态 -->
        <el-card v-if="(!taskVO.taskCourses || taskVO.taskCourses.length === 0) &&
          (!taskVO.taskResources || taskVO.taskResources.length === 0)" class="empty-card" shadow="never">
          <el-empty description="暂无学习内容" />
        </el-card>
      </div>

    </div>

    <!-- 加载失败 -->
    <div v-else class="error-tip">
      <el-empty description="加载任务失败" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  Document,
  CircleCheck,
  Reading,
  VideoPlay,
  View
} from '@element-plus/icons-vue';
import { learningTaskApi } from '@/apis/study';
import type { TaskVO, TaskItemVO } from '@/types';

interface Props {
  taskId?: string;
  showBackButton?: boolean;
  backButtonText?: string;
}

defineOptions({
  name: 'LearingTaskDetail'
});

const props = withDefaults(defineProps<Props>(), {
  showBackButton: false,
  backButtonText: '返回'
});

const emit = defineEmits<{
  back: [];
}>();

const router = useRouter();

const loading = ref(false);
const taskVO = ref<TaskVO | null>(null);
const currentTaskId = computed(() => props.taskId || '');

// 计算学习进度百分比
const progressPercent = computed(() => {
  if (!taskVO.value || !taskVO.value.totalTaskNum || taskVO.value.totalTaskNum === 0) {
    return 0;
  }
  const completed = taskVO.value.completedTaskNum || 0;
  const total = taskVO.value.totalTaskNum;
  return Math.round((completed / total) * 100);
});


watch(() => currentTaskId.value, (newId) => {
  if (newId) {
    loadTaskDetail();
  }
}, { immediate: true });

// 加载任务详情
async function loadTaskDetail() {
  if (!currentTaskId.value) {
    ElMessage.error('任务ID不存在');
    return;
  }

  loading.value = true;
  try {
    const res = await learningTaskApi.getUserTask(currentTaskId.value);
    if (res.success && res.data) {
      taskVO.value = res.data;

      // 确保数据结构完整
      if (!taskVO.value.taskCourses) {
        taskVO.value.taskCourses = [];
      }
      if (!taskVO.value.taskResources) {
        taskVO.value.taskResources = [];
      }
      if (!taskVO.value.taskUsers) {
        taskVO.value.taskUsers = [];
      }
    } else {
      ElMessage.error(res.message || '加载任务失败');
    }
  } catch (error: any) {
    console.error('加载任务失败:', error);
    ElMessage.error(error?.message || '加载任务失败');
  } finally {
    loading.value = false;
  }
}

// 处理课程点击
function handleCourseClick(course: TaskItemVO) {
  if (!course.courseID) {
    ElMessage.warning('课程ID不存在');
    return;
  }

  // 跳转到课程学习路由
  router.push({
    path: '/study-plan/course-study',
    query: {
      courseId: course.courseID,
      chapterIndex: '0',
      nodeIndex: '0',
      taskId: currentTaskId.value
    }
  });
}

// 处理资源点击
function handleResourceClick(resource: TaskItemVO) {
  if (!resource.resourceID) {
    ElMessage.warning('资源ID不存在');
    return;
  }

  // 跳转到文章查看页面
  router.push({
    path: '/article/show',
    query: {
      articleId: resource.resourceID,
      taskId: currentTaskId.value // 传递 taskId
    }
  });
}

// 处理返回
function handleBack() {
  emit('back');
}

// 格式化日期
function formatDate(dateString?: string): string {
  if (!dateString) return '--';
  const date = new Date(dateString);
  return `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')}`;
}

// 获取截止时间提示文本
function getDeadlineText(): string {
  if (!taskVO.value?.learningTask?.endTime) return '';

  const now = new Date();
  const endTime = new Date(taskVO.value.learningTask.endTime);
  const diffTime = endTime.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays < 0) {
    return '（已截止）';
  } else if (diffDays === 0) {
    return '（今天截止）';
  } else {
    return `（${diffDays}天后截止）`;
  }
}

// 格式化日期时间
function formatDateTime(dateString?: string): string {
  if (!dateString) return '--';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 获取学习项状态文本（课程/资源通用）
function getItemStatusText(status?: number): string {
  switch (status) {
    case 0:
      return '未开始';
    case 1:
      return '学习中';
    case 2:
      return '已完成';
    default:
      return '未知';
  }
}

// 获取学习项状态类型（课程/资源通用）
function getItemStatusType(status?: number): 'info' | 'warning' | 'success' {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'warning';
    case 2:
      return 'success';
    default:
      return 'info';
  }
}
</script>

<style lang="scss" scoped>
.task-detail {
  height: 100%;
  background: #f5f7fa;
  padding-bottom: 60px;
}

.back-header {
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 16px 24px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.loading {
  padding: 24px;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
}

.task-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.task-content-section {
  padding: 20px;
  background: #FFFFFF;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;

    .header-icon {
      font-size: 20px;
      color: #409eff;
    }

    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .item-count {
    font-size: 14px;
    color: #909399;
  }
}

// 任务信息卡片容器
.task-info-card {
  background: #FFFFFF;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

}

.section-header {
  display: flex;

  align-items: center;
  gap: 4px;
  height: 25px;

}

.header-bar {
  width: 3px;
  height: 14px;
  background: #C62828;
  border-radius: 2px;
}

.header-text {
  font-family: 'PingFang SC';
  font-weight: 600;
  font-size: 16px;
  line-height: 1.5;
  color: #1E293B;
}

// 任务信息区域
.task-info-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
  padding: 10px;

  .task-title {
    font-family: 'PingFang SC';
    font-weight: 600;
    font-size: 20px;
    line-height: 1.4;
    color: #141F38;
    // margin: -5px 0 0 0;
  }

  .task-description {
    font-family: 'PingFang SC';
    font-weight: 400;
    font-size: 14px;
    line-height: 1.5714285714285714;
    color: rgba(0, 0, 0, 0.3);
    margin: -20px 0 0 0;
    max-height: 66px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .task-meta {
    display: flex;
    align-items: center;
    gap: 7px;
    margin-top: -10px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 7px;
      font-family: 'PingFang SC';
      font-weight: 400;
      font-size: 14px;
      line-height: 1.5714285714285714;
      color: #4E5969;

      .creator-avatar {
        width: 20px;
        height: 20px;
        border-radius: 10px;
        object-fit: cover;
      }

      .meta-icon {
        width: 18px;
        height: 18px;
      }
    }

    .meta-divider {
      width: 0;
      height: 14px;
      border-left: 1px solid #F1F5F9;
    }
  }

  .task-stats {
    display: flex;
    gap: 32px;
    flex-wrap: wrap;

    .stat-card {
      width: calc(25% - 24px);
      height: 95px;
      padding: 7px 20px;
      background: #FEFEFF;
      border: 1px solid rgba(0, 0, 0, 0.05);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;

      .stat-content {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
        flex: 1;
        gap: 8px;

        .stat-label {
          font-family: 'PingFang SC';
          font-weight: 600;
          font-size: 16px;
          line-height: 1.5714285714285714;
          color: #4E5969;
        }

        .stat-value {
          font-family: 'PingFang SC';
          font-weight: 600;
          font-size: 32px;
          line-height: 1;
          color: #141F38;
        }
      }

      .meta-icon {
        width: 66px;
        height: 66px;
        flex-shrink: 0;
      }

    }
  }

  .progress-section {
    background: #F7F8F9;
    border-radius: 10px;
    padding: 31px 36px;
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 6px;

    .progress-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .progress-label,
      .progress-value {
        font-family: 'PingFang SC';
        font-weight: 500;
        font-size: 16px;
        line-height: 1.5;
        color: #334155;
      }
    }

    .progress-bar-container {
      width: 100%;

      .progress-bar {
        width: 100%;
        height: 8px;
        background: #FFFFFF;
        border-radius: 27px;
        overflow: hidden;

        .progress-fill {
          height: 100%;
          background: #3D3D3D;
          border-radius: 27px;
          transition: width 0.3s ease;
        }
      }
    }
  }
}

// 课程卡片
.course-card {
  margin-top: 24px;
  // padding: 10px;
  :deep(.el-card__header) {
    background: #fff9f0;
  }
}

.course-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.course-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #f0f2f5;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateX(4px);
  }

  .course-index {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 600;
    flex-shrink: 0;
  }

  .course-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .course-name-row {
      display: flex;
      align-items: center;
      gap: 12px;

      .course-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .course-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;

      .status-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .complete-time {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: #67c23a;

          .el-icon {
            font-size: 16px;
          }
        }
      }

      .progress-info {
        .progress-text {
          font-size: 14px;
          font-weight: 600;
          color: #409eff;
        }
      }
    }
  }

  .course-action {
    flex-shrink: 0;
  }
}

// 资源卡片
.resource-card {
  margin-top: 24px;

  :deep(.el-card__header) {
    background: #f0f9ff;
  }
}

.resource-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.resource-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #f0f2f5;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateX(4px);
  }

  .resource-index {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 600;
    flex-shrink: 0;
  }

  .resource-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .resource-name-row {
      display: flex;
      align-items: center;
      gap: 12px;

      .resource-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .resource-meta {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;

      .status-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .complete-time {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 13px;
          color: #67c23a;

          .el-icon {
            font-size: 16px;
          }
        }
      }

      .progress-info {
        .progress-text {
          font-size: 14px;
          font-weight: 600;
          color: #409eff;
        }
      }
    }
  }

  .resource-action {
    flex-shrink: 0;
  }
}

// 空状态卡片
.empty-card {
  margin-bottom: 24px;
}

.error-tip {
  padding: 40px;
}

// 响应式设计
@media (max-width: 768px) {
  .task-content {
    padding: 16px;
  }

  .task-info {
    .task-title {
      font-size: 22px;
    }

    .task-meta {
      .meta-row {
        flex-direction: column;
        gap: 12px;
      }
    }

    .task-stats {
      grid-template-columns: repeat(2, 1fr);
    }
  }

  .course-item,
  .resource-item {
    flex-direction: column;
    align-items: flex-start;

    .course-action,
    .resource-action {
      width: 100%;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
