<template>
  <a-card title="继续配置预测">
    <template #extra><span class="hint">仅显示尚未生成预测报告的草稿项目</span></template>
    <a-table
      :columns="columns"
      :data-source="data.items"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      size="middle"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'city'">{{ record.province }}/{{ record.city }}</template>
        <template v-else-if="column.key === 'area'">{{ record.area }}m²</template>
        <template v-else-if="column.key === 'updatedAt'">{{ fmt(record.updatedAt) }}</template>
        <template v-else-if="column.key === 'op'">
          <a @click="goConfig(record)">继续配置</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该草稿？" @confirm="onDelete(record)">
            <a style="color: #b4232a">删除</a>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { listProjects, deleteProject, type ProjectRow } from '../api/projects';
import type { Paged } from '../api/materials';

const router = useRouter();
const loading = ref(false);
const data = ref<Paged<ProjectRow>>({ total: 0, page: 1, pageSize: 10, items: [] });
const page = ref(1);

const columns = [
  { title: '项目ID', dataIndex: 'id' },
  { title: '工程名称', dataIndex: 'name' },
  { title: '项目类型', dataIndex: 'type' },
  { title: '所在城市', key: 'city' },
  { title: '建筑面积', key: 'area' },
  { title: '空间数', dataIndex: 'spaceCount' },
  { title: '最近更新', key: 'updatedAt' },
  { title: '操作', key: 'op', width: 160 },
];

const pagination = computed(() => ({
  current: data.value.page,
  pageSize: data.value.pageSize,
  total: data.value.total,
  showTotal: (t: number) => `共 ${t} 条`,
}));

function fmt(s: string) { return new Date(s).toLocaleString(); }

async function reload() {
  loading.value = true;
  try {
    data.value = await listProjects({ unfinished: 'true', page: page.value, pageSize: 10 });
  } finally {
    loading.value = false;
  }
}

function onTableChange(pg: any) { page.value = pg.current; reload(); }
function goConfig(r: ProjectRow) { router.push({ name: 'predict', params: { id: r.id } }); }
async function onDelete(r: ProjectRow) { await deleteProject(r.id); message.success('已删除'); reload(); }

onMounted(reload);
</script>

<style scoped>
.hint { color: #999; font-size: 13px; }
</style>
