<script setup lang="ts">
const route = useRoute()
const item = ref()
const ter = ref()
const terdeep = ref()
const state = reactive({} as { name?: string, location?: { id: number, name: string } })

const loadData = async () => {
    const items_data = await apiCall<any>(`tgbot/${route.params.id}/`)
    item.value = items_data
    state.name = items_data.name
    state.location = items_data.location.id
}
const loadTer = async () => {
    const terdeep_data = await apiCall<ApiPaged<{ id: number, name: string }>>(`tmc/terdeep/?size=1000`)
    terdeep.value = terdeep_data.results
}
const search = (q: string) => {
    if (q) {
        return terdeep.value.filter((el:any) => el.name.toLowerCase().indexOf(q.toLowerCase()) !== -1).slice(0, 10)
    } else {
        return terdeep.value.slice(0, 10)
    }
}
onMounted(async () => {
    await loadData()
    loadTer()
})
</script>
<template>
    <UForm :state="state" v-if="item">
        <UFormGroup label="Название">
            <UInput v-model="state.name" />
        </UFormGroup>
        <UFormGroup label="Локация">
            <USelectMenu v-model="state.location" :options="terdeep" :searchable="search" value-attribute="id"
                option-attribute="name" />
        </UFormGroup>
        <UFormGroup label="ТМЦ" v-if="item.tmc.length">
            <div v-for="el in item.tmc">
                <strong>{{ el.tmc.name }}</strong>
                <ul>
                    <li v-for="i in el.field" class="grid grid-cols-3 gap-4">
                        <span class="col-span-1">
                            {{ i.field.name }}
                            <UInput v-model="i.field.text" :placeholder="`Введите ${i.field.comment || 'с изображения'}`" />
                        </span>
                        <span class="col-span-2">
                            <GetImage :file_id="i.file_id" type="img" />
                        </span>
                    </li>
                </ul>
            </div>
        </UFormGroup>
    </UForm>
</template>