<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>任务详情</span>
          <el-button type="primary" plain size="small" @click="handleBack">返回列表</el-button>
        </div>
      </template>

      <div v-if="loading" class="text-center py-10">
        <el-skeleton :rows="15" animated />
      </div>

      <div v-else-if="taskDetail" class="detail-content">
        <!-- 顶部布局：左上角任务名称和状态，右上角项目名称和完成度 -->
        <el-row :gutter="20" class="mb-6">
          <el-col :span="12">
            <div class="flex items-center">
              <h1 class="text-2xl font-bold mr-4">{{ taskDetail.name }}</h1>
              <el-tag v-if="taskDetail.status === 0" type="info" size="large">未开始</el-tag>
              <el-tag v-else-if="taskDetail.status === 1" type="warning" size="large">进行中</el-tag>
              <el-tag v-else-if="taskDetail.status === 2" type="success" size="large">已完成</el-tag>
              <el-tag v-else type="info" size="large">未知</el-tag>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="flex flex-col items-end">
              <div class="mb-4 p-3 bg-gray-50 rounded-lg w-full max-w-md">
                <div class="mb-2">
                  <span class="text-sm text-gray-500">质控项目</span>
                  <div class="text-xl font-semibold">{{ taskDetail.projectName || taskDetail.projectId }}</div>
                </div>
                <div>
                  <span class="text-sm text-gray-500">完成度</span>
                  <div class="mt-1">
                    <el-progress :percentage="Math.round((Number(taskDetail.schedule) || 0) * 100 * 100) / 100"
                      :stroke-width="12" :show-text="true" :format="(percentage) => `${percentage}%`"
                      :empty-color="'#e0e0e0'" color="#409eff" style="width: 100%" />
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <!-- 任务基本信息 -->
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="创建时间">{{ parseTime(taskDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="截止时间">{{ parseTime(taskDetail.deadline, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="3">{{ taskDetail.note || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <!-- 任务详情列表 -->
        <div class="mb-8">
          <h3 class="text-xl font-semibold mb-3">任务列表</h3>
          <el-table v-loading="taskItemsLoading" :data="taskItems" border>
            <el-table-column prop="id" label="序号" width="80" />
            <el-table-column prop="documentName" label="文档名称" width="180" show-overflow-tooltip />
            <el-table-column prop="executorName" label="质控人" width="150" />
            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0 || scope.row.status === 3" type="info">待审核</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="success">审核通过</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="danger">审核拒绝</el-tag>
                <el-tag v-else type="warning">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="executionTime" label="执行时间" width="180" />
            <el-table-column prop="finishTime" label="完成时间" width="180" />
            <el-table-column prop="note" label="备注" />
          </el-table>

          <div class="mt-4">
            <pagination v-show="taskItemsTotal > 0" :total="taskItemsTotal" v-model:page="taskItemsQuery.pageNum"
              v-model:limit="taskItemsQuery.pageSize" @pagination="handleTaskItemsPagination" />
          </div>
        </div>
      </div>

      <div v-else class="text-center py-20">
        <el-result icon="error" title="获取任务详情失败" sub-title="请重试或返回列表">
          <template #extra>
            <el-button type="primary" @click="handleBack">返回列表</el-button>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script setup name="TaskDetail" lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getTask, listTaskDetail } from '@/api/qc/task';
import { TaskVO } from '@/api/qc/task/types';

// 定义任务详情项类型
interface TaskDetailItem {
  id: number;
  document: number;
  documentName: string;
  ossId: number;
  executor: number;
  executorName: string;
  status: number;
  note: string;
  executionTime: string;
  finishTime: string;
}

// 任务列表数据
const taskItems = ref<TaskDetailItem[]>([]);
const taskItemsLoading = ref(false);
const taskItemsTotal = ref(0);
const taskItemsQuery = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  taskId: undefined,
  documentName: undefined,
  status: undefined
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

// 从路由参数获取任务ID
const taskId = computed(() => {
  const id = route.query.id;
  if (!id) return undefined;
  const numId = typeof id === 'string' ? parseInt(id) : id;
  console.log('Task Detail - taskId:', numId, 'from route.query:', route.query.id);
  return numId;
});

const loading = ref(true);
const taskDetail = ref<TaskVO | null>(null);

const fetchTaskDetail = async () => {
  if (!taskId.value) return;

  try {
    loading.value = true;
    const res = await getTask(taskId.value);
    taskDetail.value = res.data;
    // 获取任务列表
    await fetchTaskItems();
  } catch (error) {
    console.error('获取任务详情失败:', error);
    proxy?.$modal.msgError('获取任务详情失败');
    taskDetail.value = null;
  } finally {
    loading.value = false;
  }
};

/** 获取任务列表 */
const fetchTaskItems = async () => {
  if (!taskDetail.value?.id) return;

  try {
    taskItemsLoading.value = true;
    taskItemsQuery.value.projectId = taskDetail.value.projectId;
    taskItemsQuery.value.taskId = taskDetail.value.id;

    const res = await listTaskDetail(taskItemsQuery.value);
    if (res.code === 200) {
      taskItems.value = res.rows;
      taskItemsTotal.value = res.total;
    } else {
      proxy?.$modal.msgError(res.msg || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    proxy?.$modal.msgError('获取任务列表失败');
  } finally {
    taskItemsLoading.value = false;
  }
};

/** 任务列表分页变化 */
const handleTaskItemsPagination = (pageNum: number, pageSize: number) => {
  taskItemsQuery.value.pageNum = pageNum;
  taskItemsQuery.value.pageSize = pageSize;
  fetchTaskItems();
};

const handleBack = () => {
  router.push('/qc/task');
};

watch(
  () => route.query.id,
  (newId) => {
    console.log('Route query id changed:', newId);
    if (newId) {
      fetchTaskDetail();
    }
  }
);

onMounted(() => {
  console.log('Task Detail mounted');
  console.log('Route:', route);
  console.log('Route query:', route.query);
  console.log('TaskId:', taskId.value);
  fetchTaskDetail();
});
</script>

<style scoped>
.detail-content {
  width: 100%;
  margin: 0;
}

/* 确保卡片内容占满宽度 */
:deep(.el-card__body) {
  padding: 20px;
}

/* 调整描述列表的样式 */
:deep(.el-descriptions) {
  margin-bottom: 20px;
}

/* 调整表格的样式 */
:deep(.el-table) {
  margin-top: 20px;
}
</style>
