<template>
  <section class="page projects-page">
    <div class="panel">
      <div class="panel-header">
        <div>
          <h1 class="panel-title">我的项目</h1>
          <p class="muted">继续编辑已创建的项目草稿，或打开已经生成的项目预览。</p>
        </div>
        <div class="toolbar">
          <el-button :icon="Refresh" :loading="loading" @click="loadProjects">刷新</el-button>
          <el-button type="primary" :icon="Plus" @click="router.push({ path: '/generate', query: { mode: 'one-click' } })">新建项目</el-button>
        </div>
      </div>

      <div class="content">
        <el-table v-loading="loading" :data="projects" class="project-table">
          <el-table-column prop="projectName" label="项目名称" min-width="190">
            <template #default="{ row }">
              <div class="project-name">{{ row.projectName || '未命名项目' }}</div>
              <div class="project-desc">{{ row.projectDesc || row.requirementKeyword || '暂无描述' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="140">
            <template #default="{ row }">
              <el-tag :type="statusMeta(row).type" effect="light">
                {{ statusMeta(row).label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" min-width="160">
            <template #default="{ row }">
              {{ row.updateTime || row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="328" fixed="right">
            <template #default="{ row }">
              <div class="row-actions">
                <el-tooltip content="专家编辑" placement="top">
                  <el-button class="project-icon-button" :icon="EditPen" circle plain aria-label="专家编辑" @click="continueProject(row)" />
                </el-tooltip>
                <el-tooltip content="图表中心" placement="top">
                  <el-button class="project-icon-button" :icon="DataAnalysis" circle plain aria-label="图表中心" @click="openDiagrams(row)" />
                </el-tooltip>
                <el-tooltip content="模块图" placement="top">
                  <el-button class="project-icon-button" :icon="Connection" circle plain aria-label="模块图" @click="openModuleDiagramEditor(row)" />
                </el-tooltip>
                <el-tooltip content="论文初稿" placement="top">
                  <el-button class="project-icon-button" :icon="Document" circle plain aria-label="论文初稿" @click="openPaperDraft(row)" />
                </el-tooltip>
                <el-tooltip content="预览" placement="top">
                  <el-button class="project-icon-button" :icon="View" circle plain aria-label="预览" :disabled="row.previewStatus !== '1'" @click="router.push(`/project/${projectIdOf(row)}/preview`)" />
                </el-tooltip>
                <el-tooltip content="下载" placement="top">
                  <el-button class="project-icon-button" :icon="Download" circle plain aria-label="下载" :disabled="row.previewStatus !== '1'" :loading="downloadingProjectId === projectIdOf(row)" @click="downloadSource(row)" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button class="project-icon-button" :icon="Delete" circle plain type="danger" aria-label="删除" @click="removeProject(row)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-empty
          v-if="!loading && !projects.length"
          description="暂无项目，创建一个新的项目草稿吧"
        />
      </div>
    </div>
  </section>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Connection, DataAnalysis, Delete, Document, Download, EditPen, Plus, Refresh, View } from '@element-plus/icons-vue'
import { deleteProject, downloadProject, listProjects } from '@/api/project'
import { saveBlob, sourceZipName } from '@/utils/download'

const router = useRouter()
const loading = ref(false)
const downloadingProjectId = ref(null)
const projects = ref([])

function projectIdOf(project) {
  return project?.projectId || project?.id
}

function statusMeta(project) {
  if (project?.previewStatus === '1') {
    return { label: '已预览', type: 'success' }
  }
  if (project?.generateStatus === '1') {
    return { label: '已生成数据库', type: 'primary' }
  }
  return { label: '草稿', type: 'info' }
}

async function loadProjects() {
  loading.value = true
  try {
    const result = await listProjects()
    projects.value = Array.isArray(result) ? result : []
  } catch (error) {
    ElMessage.error(error.message || '加载项目列表失败')
  } finally {
    loading.value = false
  }
}

function continueProject(project) {
  const projectId = projectIdOf(project)
  if (!projectId) {
    ElMessage.warning('项目 ID 不存在，无法继续')
    return
  }
  router.push({ path: '/generate', query: { projectId, mode: 'expert' } })
}

function openDiagrams(project) {
  const projectId = projectIdOf(project)
  if (!projectId) {
    ElMessage.warning('项目 ID 不存在，无法打开图表中心')
    return
  }
  router.push(`/project/${projectId}/diagrams`)
}

function openModuleDiagramEditor(project) {
  const projectId = projectIdOf(project)
  if (!projectId) {
    ElMessage.warning('项目 ID 不存在，无法打开模块图')
    return
  }
  router.push(`/project/${projectId}/module-diagram`)
}

function openPaperDraft(project) {
  const projectId = projectIdOf(project)
  if (!projectId) {
    ElMessage.warning('项目 ID 不存在，无法打开论文初稿')
    return
  }
  router.push(`/project/${projectId}/paper-draft`)
}

async function downloadSource(project) {
  const projectId = projectIdOf(project)
  if (!projectId) return
  if (project.previewStatus !== '1') {
    ElMessage.warning('请先完成项目预览')
    return
  }

  downloadingProjectId.value = projectId
  try {
    const blob = await downloadProject(projectId)
    saveBlob(blob, sourceZipName(project))
    ElMessage.success('源码下载已开始')
  } catch (error) {
    ElMessage.error(error.message || '下载源码失败')
  } finally {
    downloadingProjectId.value = null
  }
}

async function removeProject(project) {
  const projectId = projectIdOf(project)
  if (!projectId) return

  try {
    await ElMessageBox.confirm(`确认删除项目“${project.projectName || projectId}”？`, '删除项目', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消'
    })
    await deleteProject(projectId)
    ElMessage.success('项目已删除')
    await loadProjects()
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error(error.message || '删除项目失败')
    }
  }
}

onMounted(loadProjects)
</script>

<style scoped lang="scss">
.projects-page {
  display: grid;
  gap: 18px;
}

.content {
  padding: 16px 20px 22px;
}

.project-table {
  width: 100%;
}

.project-name {
  color: #172033;
  font-weight: 700;
}

.project-desc {
  display: -webkit-box;
  max-width: 540px;
  margin-top: 4px;
  overflow: hidden;
  color: #667085;
  font-size: 13px;
  line-height: 1.6;
  overflow-wrap: anywhere;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.row-actions {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 8px;
}

.row-actions :deep(.el-button) {
  margin-left: 0;
}

.project-icon-button {
  width: 36px;
  height: 36px;
  padding: 0;
}

@media (max-width: 860px) {
  .panel-header {
    align-items: stretch;
    flex-direction: column;
  }
}
</style>
