<template>
  <el-card shadow="never">
    <template #header>
      <div class="toolbar">
        <span class="title">产品线</span>
        <el-button type="primary" :loading="loading" @click="load">刷新</el-button>
      </div>
    </template>

    <el-table v-loading="loading" :data="rows" stripe style="width: 100%">
      <el-table-column prop="code" label="编码" width="160" show-overflow-tooltip />
      <el-table-column prop="name" label="名称" min-width="180" show-overflow-tooltip />
      <el-table-column label="描述" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.description ?? "—" }}</template>
      </el-table-column>
      <el-table-column label="启用" width="90">
        <template #default="{ row }">
          <el-tag v-if="row.enabled === false || row.active === false" type="info" size="small">否</el-tag>
          <el-tag v-else type="success" size="small">是</el-tag>
        </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 { ElMessage } from "element-plus";
import { useAuthStore } from "../stores/auth";
import { listProductLines } from "../api/platform";
import { apiErrorMessage } from "../utils/apiErrorMessage";

const auth = useAuthStore();
const loading = ref(false);
const rows = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);

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

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

async function load() {
  loading.value = true;
  try {
    const { data } = await listProductLines({
      page: page.value - 1,
      size: pageSize.value,
    });
    const body = data && typeof data === "object" ? data : {};
    rows.value = Array.isArray(body.content) ? body.content : Array.isArray(data) ? data : [];
    total.value = Number(body.totalElements ?? body.total ?? rows.value.length);
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载产品线失败"));
    rows.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}
</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;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
