<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-input v-model="filters.site_id" placeholder="中心ID" clearable @change="load" style="width: 200px" />
        <el-select v-model="filters.product_id" placeholder="产品" clearable @change="load">
          <el-option v-for="p in products" :key="p.id" :label="p.name" :value="p.id" />
        </el-select>
        <div class="spacer" />
        <el-button @click="load">刷新</el-button>
      </div>
    </el-card>
    <el-card>
      <el-table :data="rows" v-loading="loading" style="width: 100%">
        <el-table-column prop="site_id" label="中心" />
        <el-table-column prop="batch_id" label="批次" />
        <el-table-column prop="quantity_on_hand" label="当前结余" width="120" align="right" />
        <el-table-column prop="updated_at" label="更新时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { fetchImpInventory } from "../api/impInventory";
import { fetchImpProducts } from "../api/impProducts";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";

const study = useStudyStore();
const auth = useAuthStore();

const filters = ref({ site_id: "", product_id: "" });
const rows = ref<any[]>([]);
const loading = ref(false);
const products = ref<any[]>([]);

const loadProducts = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchImpProducts(study.currentStudy.id);
    products.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    /* ignore */
  }
};

const load = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = {};
    if (filters.value.site_id) params.site_id = filters.value.site_id;
    if (filters.value.product_id) params.product_id = filters.value.product_id;
    const { data } = await fetchImpInventory(study.currentStudy.id, params);
    if (Array.isArray(data)) {
      rows.value = data;
    } else {
      rows.value = data.items || [];
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "库存加载失败");
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await loadProducts();
  load();
});
</script>

<style scoped>
.page {
  padding: 16px;
}
.filters {
  display: flex;
  gap: 8px;
  align-items: center;
}
.spacer {
  flex: 1;
}
.mb-12 {
  margin-bottom: 12px;
}
</style>
