<script setup>
import { ref, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import axios from 'axios';

import CrudModel from 'src/components/CrudModel.vue';
import VnInput from 'src/components/common/VnInput.vue';
import useNotify from 'src/composables/useNotify.js';

const route = useRoute();
const { t } = useI18n();
const { notify } = useNotify();

const itemBarcodeRef = ref(null);

const insertRow = () => {
    itemBarcodeRef.value.insert();
    focusLastInput();
};

const focusLastInput = () => {
    nextTick(() => {
        const inputs = document.querySelectorAll('[focusable-input]');
        const lastInput = inputs[inputs.length - 1];
        if (lastInput) lastInput.focus();
    });
};

const removeRow = (row) => {
    itemBarcodeRef.value.remove([row]);
};

const submit = async (rows) => {
    const params = rows[rows.length - 1];
    let { data } = await axios.get('ItemBarcodes');
    const code = params.code;

    if (data.some((codes) => codes.code === code)) {
        notify(t('Codes can not be repeated'), 'negative');
        itemBarcodeRef.value.reset();
        return;
    }
    await axios.patch(`ItemBarcodes`, params);
    notify(t('globals.dataSaved'), 'positive');
};
</script>
<template>
    <div class="full-width flex justify-center">
        <QPage class="card-width q-pa-lg">
            <CrudModel
                :data-required="{ itemFk: route.params.id }"
                :default-remove="false"
                :insert-on-load="true"
                :filter="{
                    fields: ['id', 'itemFk', 'code'],
                    where: { itemFk: route.params.id },
                }"
                data-key="ItemBarcodes"
                model="ItemBarcodes"
                ref="itemBarcodeRef"
                url="ItemBarcodes"
                auto-load
                :save-fn="submit"
            >
                <template #body="{ rows }">
                    <QCard class="q-px-lg q-py-md">
                        <div
                            v-for="(row, index) in rows"
                            :key="index"
                            class="q-mb-md full-width row items-center no-wrap"
                        >
                            <VnInput
                                :label="t('Code')"
                                v-model="row.code"
                                class="full-width"
                                focusable-input
                            />
                            <QIcon
                                @click="removeRow(row)"
                                class="cursor-pointer q-ml-md"
                                color="primary"
                                name="delete"
                                size="sm"
                            >
                                <QTooltip class="text-no-wrap">
                                    {{ t('Remove barcode') }}
                                </QTooltip>
                            </QIcon>
                        </div>
                        <QBtn
                            @click="insertRow()"
                            class="cursor-pointer fill-icon-on-hover"
                            color="primary"
                            icon="add_circle"
                            v-shortcut="'+'"
                            flat
                            data-cy="addBarcode_input"
                        >
                            <QTooltip>
                                {{ t('Add barcode') }}
                            </QTooltip>
                        </QBtn>
                    </QCard>
                </template>
            </CrudModel>
        </QPage>
    </div>
</template>

<i18n>
es:
    Code: Código
    Remove barcode: Quitar código de barras
    Add barcode: Añadir código de barras
    Codes can not be repeated: Los códigos no puden ser repetidos
</i18n>
