<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.id = items_data.id
    state.name = items_data.name
    state.location = items_data.location.id
    state.tmc = items_data.tmc.map(el => {
        return {
            name: el.tmc.name,
            id: el.id,
            fields: el.field.map(item => {
                return {
                    name: item.field.name,
                    comment: item.field.comment,
                    id: item.id,
                    text: item.text,
                    file_id: item.file_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()
})
const patchField = async (field) => {
    await apiCall(`tgbot/items/${field.id}/`, 'PATCH', { text: field.text })
}
const patchItem = async () => {
    await apiCall(`tgbot/${state.id}/`, 'PATCH', { name: state.name, location: state.location })
}
</script>
<template>
    <UForm :state="state" v-if="item">
        <UFormGroup label="Название">
            <UInput v-model="state.name" />
        </UFormGroup>
        <UButton @click="patchItem">Сохранить</UButton>
        <UFormGroup label="Локация">
            <USelectMenu v-model="state.location" :options="terdeep" :searchable="search" value-attribute="id"
                option-attribute="name" />
        </UFormGroup>
        <UFormGroup label="ТМЦ" v-if="state.tmc">
            <div v-for="el in state.tmc">
                <strong>{{ el.name }}</strong>
                <ul>
                    <li v-for="field in el.fields" class="grid grid-cols-3 gap-4">
                        <span class="col-span-1 flex flex-col gap-2 items-start">
                            {{ field.name }}
                            <UInput v-model="field.text" :placeholder="`Введите ${field.comment || 'с изображения'}`" />
                            <UButton @click="patchField(field)">Сохранить</UButton>
                        </span>
                        <span class="col-span-2">
                            <GetImage :file_id="field.file_id" type="img" />
                        </span>
                    </li>
                </ul>
            </div>
        </UFormGroup>
    </UForm>
</template>