<script setup>
import {NButton, NDatePicker, NDivider, NFlex, NForm, NFormItem, NInput, NModal, NSpace, NSwitch, NSelect} from "naive-ui";
import {ref, watch} from "vue";
import {router} from "@inertiajs/vue3";
const open = defineModel('open')
const props = defineProps({
    archiveHistoryId: {
        type: Number
    },
    activeHistoryType: {
        type: String
    },
    isCreateNew: {
        type: Boolean
    }
})
const emits = defineEmits(['closeWithoutSave', 'historyUpdated'])

const loading = ref(false)
const archiveHistory = ref({
    historyable_id: props.archiveHistoryId,
    historyable_type: props.activeHistoryType,
    issue_at: null,
    org_id: null,
    return_at: null,
    employee_name: null,
    employee_post: null,
    comment: null,
    has_lost: false,
})
const orgs = ref([])

const onResetData = () => {
    archiveHistory.value = {
        historyable_id: props.archiveHistoryId,
        historyable_type: props.activeHistoryType,
        issue_at: null,
        org_id: null,
        return_at: null,
        employee_name: null,
        employee_post: null,
        comment: null,
        has_lost: false,
    }
}
const onCloseWithoutSave = () => {
    emits('closeWithoutSave')
    open.value = false
}

const loadArchiveHistoryData = async () => {
    try {
        await axios.get('/api/orgs').then(res => {
            orgs.value = res.data
        })

        if (!props.archiveHistoryId) return

        await axios.get(`/api/archive/histories/${props.archiveHistoryId}`).then(res => {
            archiveHistory.value = res.data
        })
    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}

const submit = () => {
    try {
        const url = props.isCreateNew
            ? '/api/archive/histories/move'
            : `/api/archive/histories/move/${archiveHistory.value.id}`

        axios.post(url, archiveHistory.value).then(res => {
            emits('historyUpdated', {
                type: props.isCreateNew ? 'created' : 'updated',
                data: res.data,
                historyId: archiveHistory.value.id
            })
            onCloseWithoutSave()
        })

    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}

// Наблюдаем за изменением archiveHistoryId
watch(() => props.archiveHistoryId, async (newId) => {
    if (!props.isCreateNew) {
        await loadArchiveHistoryData()
    } else {
        onResetData()
    }
}, { immediate: true })
</script>

<template>
    <NModal v-model:show="open" preset="card" class="max-w-2xl" closable @close="open = false">
        <template #header>
            {{ archiveHistoryId === null ? 'Добавить' : 'Редактировать' }} запись выдачи
        </template>
        <NForm>
            <NFormItem label="Дата выдачи">
                <NDatePicker v-model:value="archiveHistory.issue_at" format="dd.MM.yyyy" />
            </NFormItem>
            <NFormItem label="Дата возврата">
                <NDatePicker v-model:value="archiveHistory.return_at" format="dd.MM.yyyy" />
            </NFormItem>
            <NFormItem label="Организация">
                <NSelect v-model:value="archiveHistory.org_id" :options="orgs" label-field="name" value-field="id" filterable />
            </NFormItem>
            <NFormItem label="Имя сотрудника">
                <NInput v-model:value="archiveHistory.employee_name" />
            </NFormItem>
            <NFormItem label="Должность">
                <NInput v-model:value="archiveHistory.employee_post" />
            </NFormItem>
            <NFormItem label="Примечание">
                <NInput v-model:value="archiveHistory.comment" type="textarea" rows="3" :resizable="false" />
            </NFormItem>
        </NForm>

        <template #action>
            <NFlex justify="space-between" align="center">
                <NFormItem :show-feedback="false" label-placement="left" label="Карта утеряна">
                    <NSwitch v-model:value="archiveHistory.has_lost" />
                </NFormItem>
                <NSpace align="center" :size="0">
                    <NButton secondary @click="onCloseWithoutSave">
                        Закрыть без сохранения
                    </NButton>
                    <NDivider vertical />
                    <NButton secondary type="primary" @click="submit">
                        Сохранить
                    </NButton>
                </NSpace>
            </NFlex>
        </template>
    </NModal>
</template>

<style scoped>

</style>
