<script setup lang="ts">
import { apiBase } from '~/helpers';
import type { ApiTypeExternalPartners } from '~/helpers';

const loading = ref(false)
const state = reactive({
    organization: undefined,
})
async function onSubmit(event: FormSubmitEvent<Schema>) {
    // Do something with event.data
    console.log(event.data)
}
const externalPartners = ref<ApiTypeExternalPartners[]>([])
const searchInExternal = (q: string) => {
    if (!q.length) {
        return externalPartners.value.splice(0, 10)
    }
    return externalPartners.value.filter(el => {
        return el.Description.toLowerCase().indexOf(q.toLowerCase()) !== -1
    }).slice(0, 10)
}
const externalCategoryValue = ref([])
const externalCategories = ref<ApiTypeExternalPartners[][]>([])

const externalElementValue = ref()
const externalElements = ref<ApiTypeExternalPartners[]>([])

const loadPartners = async () => {
    loading.value = true
    const { data } = await useFetch<ApiTypeExternalPartners[]>(`${apiBase}/partner/external/`)
    if (data.value) {
        externalPartners.value = data.value
    }
    loading.value = false
}
const loadCategories = async () => {
    const lastCat = externalCategoryValue.value.at(-1) || ''
    const { data } = await useFetch<ApiTypeExternalPartners[]>(`${apiBase}/element/external_categories/${lastCat}`)
    if (data.value?.length) {
        externalCategories.value.push(data.value)
    } else {
        await loadElements()
    }
}
const loadElements = async () => {
    const lastCat = externalCategoryValue.value.at(-1) || ''
    const { data } = await useFetch<ApiTypeExternalPartners[]>(`${apiBase}/element/external/${lastCat}`)
    if (data.value) {
        externalElements.value = data.value
    }
}
const loadDeepCategories = async (i: number) => {
    if ((i + 1) < externalCategoryValue.value.length) {
        externalCategoryValue.value = externalCategoryValue.value.slice(0, i + 1)
        externalCategories.value = externalCategories.value.slice(0, i + 1)
    }
    loadCategories()
}
onMounted(async () => {
    await loadPartners()
    await loadCategories()
})
</script>
<template>
    <div class="grid grid-cols-10">
        <div class="col-span-3">
            <UForm :state="state" class="flex flex-col gap-4" @submit="onSubmit">
                <UFormGroup label="Выбрать организацию" name="organization">
                    <USelectMenu v-model="state.organization" :options="externalPartners" value-attribute="Ref_Key"
                        option-attribute="Description" :searchable="searchInExternal"
                        searchable-placeholder="Выберите организацию из списка контрагентов" :loading="loading" />
                </UFormGroup>
                <UFormGroup label="Добавить элемент инвентаризации" v-if="state.organization">
                    <template v-for="(item, i) in externalCategories">
                        <USelectMenu v-model="externalCategoryValue[i]" :options="item" value-attribute="Ref_Key"
                            option-attribute="Description" :searchable="true" :loading="loading"
                            :placeholder="`Категории (${item.length})`" @change="loadDeepCategories(i)" />
                    </template>
                    <USelectMenu v-if="externalElements.length" v-model="externalElementValue"
                        :options="externalElements" value-attribute="Ref_Key" option-attribute="Description"
                        :searchable="true" :loading="loading" :placeholder="`Элементы (${externalElements.length})`" />
                </UFormGroup>

                <UButton type="submit">
                    Сохранить
                </UButton>
            </UForm>
        </div>
    </div>
</template>