<script setup lang="ts">
const config = useRuntimeConfig()
const route = useRoute()
interface APIBody {
    data: any[],
    status: 'success' | 'error'
}

const { data, pending, error, status } = await useLazyFetch<APIBody>(`${config.public.apiBase}/api/nomen`, { server: false })
const selected_nomen = ref()
const selected_item = ref()

const loading = ref(true)

const child_cat_data = ref<any[]>([])
const child_cat_pending = ref()

const item_data = ref()
const item_pending = ref()

const onCategoryChange = async () => {
    const { data, pending } = await useFetch<APIBody>(`${config.public.apiBase}/api/nomen/${selected_nomen.value.id}`, { server: false })
    child_cat_data.value = data.value.data
    child_cat_pending.value = pending.value

    item_data.value = undefined
    selected_item.value = undefined
}

const onItemChange = async () => {
    const { data, pending } = await useFetch<APIBody>(`${config.public.apiBase}/api/nomen_item/${selected_item.value.id}`, { server: false })
    item_data.value = data.value.data
    item_pending.value = pending.value
}

watch([pending, child_cat_pending], () => {
    loading.value = pending.value
})
onMounted(() => {
})
</script>
<template>
    <div>
        <USelectMenu clear-search-on-close class="w-full my-2" placeholder="Категории номенклатуры" searchable
            searchable-placeholder="Искать..." :options="data?.data" size="lg" v-model="selected_nomen"
            @change="onCategoryChange" :loading="loading" />

        <USelectMenu clear-search-on-close class="w-full my-2" :placeholder="`Элементы (${child_cat_data.length})`"
            searchable searchable-placeholder="Искать..." :options="child_cat_data" size="lg" v-model="selected_item"
            @change="onItemChange" :loading="loading" :disabled="!child_cat_data.length" />

        <template v-if="item_data && Object.keys(item_data).length">
            <dl class="text-sm">
                <template v-for="item in ['Code', 'Description', 'Комментарий']">
                    <dt>{{item}}</dt>
                    <dd class="mb-2">{{ item_data[item] }}</dd>
                </template>
            </dl>
        </template>
    </div>
</template>