<script setup lang="ts">
import { onMounted, ref } from 'vue'
import CategoryTree from '../components/CategoryTree.vue'
import { fetchCategoryTree } from '../api/category'
import { fetchDemandGrade } from '../api/demand'
import type { CategoryNode, WeightDimMeta } from '../types/category'
import type { DemandsByCategory } from '../types/demand'
import { groupDemandsByCategory } from '../types/demand'

const nodes = ref<CategoryNode[]>([])
const dims = ref<WeightDimMeta[]>([])
const bizDt = ref<string | null>(null)
const demandsByCategory = ref<DemandsByCategory>({})
const loading = ref(true)
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    const [tree, demands] = await Promise.all([
      fetchCategoryTree(),
      fetchDemandGrade(),
    ])
    nodes.value = tree.nodes ?? []
    dims.value = tree.dims ?? []
    bizDt.value = tree.biz_dt ?? null
    demandsByCategory.value = groupDemandsByCategory(demands.items ?? [])
  } catch (e) {
    error.value = e instanceof Error ? e.message : String(e)
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="view">
    <div v-if="loading" class="state">正在加载分类树…</div>
    <div v-else-if="error" class="state error">{{ error }}</div>
    <CategoryTree
      v-else
      :nodes="nodes"
      :dims="dims"
      :biz-dt="bizDt"
      :demands-by-category="demandsByCategory"
    />
  </div>
</template>

<style scoped>
.view {
  height: 100%;
  min-height: 0;
}

.state {
  padding: 64px 24px;
  text-align: center;
  color: #64748b;
  font-size: 15px;
}

.state.error {
  color: #b91c1c;
}
</style>
