<template>
  <el-card shadow="never">
    <template #header>
      <div class="toolbar">
        <span class="title">交付管理</span>
        <div class="actions">
          <el-select
            v-model="filterProjectId"
            clearable
            filterable
            placeholder="按项目筛选"
            class="filter"
            style="width: 200px"
          >
            <el-option v-for="p in projectOptions" :key="p.id" :label="p.name || String(p.id)" :value="p.id" />
          </el-select>
          <el-input
            v-model="keyword"
            clearable
            placeholder="按批次编码搜索"
            class="search"
            @keyup.enter="load"
          />
          <el-button type="primary" :loading="loading" @click="load">查询</el-button>
          <el-button v-permission="'delivery:rw'" type="success" @click="goNew">新建交付批次</el-button>
        </div>
      </div>
    </template>

    <el-table v-loading="loading" :data="rows" stripe style="width: 100%">
      <el-table-column prop="batchCode" label="批次编码" min-width="140" show-overflow-tooltip />
      <el-table-column label="项目" min-width="160" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.projectName ?? projectNameById(row.projectId) }}
        </template>
      </el-table-column>
      <el-table-column label="合同 ID" width="100">
        <template #default="{ row }">{{ row.contractId ?? "—" }}</template>
      </el-table-column>
      <el-table-column label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="batchStatusTagType(row.status)" size="small">{{ batchStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划交付日" width="130">
        <template #default="{ row }">{{ formatDate(row.plannedDeliveryDate) }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="goDetail(row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="load"
        @size-change="onSizeChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useAuthStore } from "../stores/auth";
import { listDeliveryBatches, listProjects } from "../api/platform";
import { apiErrorMessage } from "../utils/apiErrorMessage";

const auth = useAuthStore();
const router = useRouter();

const loading = ref(false);
const rows = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const keyword = ref("");
const filterProjectId = ref(undefined);
const projectOptions = ref([]);
/** @type {import('vue').Ref<Map<string | number, string>>} */
const projectMap = ref(new Map());

onMounted(async () => {
  auth.restoreAxiosAuth();
  await loadProjects();
  await load();
});

function onSizeChange() {
  page.value = 1;
  load();
}

function projectNameById(id) {
  if (id == null) return "—";
  return projectMap.value.get(id) ?? String(id);
}

function batchStatusLabel(s) {
  const u = String(s ?? "").toUpperCase();
  const map = { PENDING: "待交付", DELIVERED: "已交付", CANCELLED: "已取消" };
  return map[u] ?? String(s ?? "—");
}

function batchStatusTagType(s) {
  const u = String(s ?? "").toUpperCase();
  if (u === "PENDING") return "warning";
  if (u === "DELIVERED") return "success";
  if (u === "CANCELLED") return "info";
  return "";
}

function formatDate(v) {
  if (v == null || v === "") return "—";
  if (typeof v === "string") return v.slice(0, 10);
  return String(v);
}

function formatDateTime(v) {
  if (v == null || v === "") return "—";
  if (typeof v === "string") return v.replace("T", " ").slice(0, 19);
  return String(v);
}

async function loadProjects() {
  try {
    const { data } = await listProjects({ page: 0, size: 200 });
    const body = data && typeof data === "object" ? data : {};
    const list = Array.isArray(body.content) ? body.content : [];
    projectOptions.value = list;
    const m = new Map();
    for (const p of list) {
      if (p?.id != null) m.set(p.id, p.name ?? String(p.id));
    }
    projectMap.value = m;
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载项目失败"));
    projectOptions.value = [];
    projectMap.value = new Map();
  }
}

async function load() {
  loading.value = true;
  try {
    const { data } = await listDeliveryBatches({
      page: page.value - 1,
      size: pageSize.value,
      keyword: keyword.value?.trim() || undefined,
      projectId: filterProjectId.value ?? undefined,
    });
    const body = data && typeof data === "object" ? data : {};
    rows.value = Array.isArray(body.content) ? body.content : [];
    total.value = Number(body.totalElements ?? body.total ?? 0);
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载交付批次失败"));
    rows.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

function goNew() {
  router.push({ name: "delivery-new" });
}

function goDetail(id) {
  router.push({ name: "delivery-detail", params: { id: String(id) } });
}
</script>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.search {
  width: 200px;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
