<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 externalCategory = ref()
const externalCategories = ref<ApiTypeExternalPartners[]>([])

const externalElement = 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 loadElements = async () => {
    loading.value = true
    const { data } = await useFetch<ApiTypeExternalPartners[]>(`${apiBase}/element/external/${externalCategory.value}`)
    if (data.value) {
        externalElements.value = data.value
    }
    loading.value = false
}
onMounted(async () => {
    await loadPartners()

    const { data } = await useFetch<ApiTypeExternalPartners[]>(`${apiBase}/element/external_categories/`)
    externalCategories.value = data.value
})
watch(externalCategory, loadElements)
</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">
                    <USelectMenu v-model="externalCategory" :options="externalCategories" value-attribute="Ref_Key"
                        option-attribute="Description" :searchable="true" :loading="loading" />
                    <USelectMenu v-model="externalElement" :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>