<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-select
          v-model="filters.site_id"
          placeholder="中心"
          clearable
          filterable
          @change="load"
          style="width: 220px"
        >
          <el-option v-for="s in sites" :key="s.id" :label="s.name" :value="s.id" />
        </el-select>
        <el-select v-model="filters.product_id" placeholder="产品" clearable @change="load" filterable>
          <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="中心">
          <template #default="scope">{{ siteName(scope.row.site_id) }}</template>
        </el-table-column>
        <el-table-column prop="batch_id" label="批次">
          <template #default="scope">{{ batchName(scope.row.batch_id) }}</template>
        </el-table-column>
        <el-table-column prop="quantity_on_hand" label="当前结余" width="120" align="right" />
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="scope">{{ displayDateTime(scope.row.updated_at) }}</template>
        </el-table-column>
      </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 { fetchImpBatches } from "../api/impBatches";
import { fetchSites } from "../api/sites";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import { displayDateTime } from "../utils/display";

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 batches = ref<any[]>([]);
const sites = 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 loadBatches = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchImpBatches(study.currentStudy.id, { limit: 500 });
    batches.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    batches.value = [];
  }
};

const loadSites = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchSites(study.currentStudy.id, { limit: 500 });
    sites.value = (data as any).items || data || [];
  } catch {
    sites.value = [];
  }
};

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;
  }
};

const siteName = (id?: string) => {
  if (!id) return "-";
  const found = sites.value.find((s: any) => s.id === id);
  return found?.name || id;
};

const batchName = (id?: string) => {
  if (!id) return "-";
  const found = batches.value.find((b: any) => b.id === id);
  return found?.batch_no || found?.code || id;
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await Promise.all([loadProducts(), loadBatches(), loadSites()]);
  load();
});
</script>

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