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

import FetchData from 'components/FetchData.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnRow from 'components/ui/VnRow.vue';
import CrudModel from 'components/CrudModel.vue';
import VnSelect from 'src/components/common/VnSelect.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

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

const taxesFilter = {
    fields: ['id', 'countryFk', 'taxClassFk'],
    include: [
        {
            relation: 'country',
            scope: {
                fields: ['name'],
            },
        },
    ],
};

const ItemTaxRef = ref(null);
const taxesOptions = ref([]);

const submitTaxes = async (data) => {
    try {
        let payload = data.map((tax) => ({
            id: tax.id,
            taxClassFk: tax.taxClassFk,
        }));

        await axios.post(`Items/updateTaxes`, payload);
        notify(t('globals.dataSaved'), 'positive');
    } catch (err) {
        console.error('Error saving taxes', err);
    }
};
</script>
<template>
    <FetchData
        url="TaxClasses"
        :filter="{
            fields: ['id', 'description', 'code'],
        }"
        @on-fetch="(data) => (taxesOptions = data)"
        auto-load
    />
    <CrudModel
        :url="`items/${route.params.id}/taxes`"
        :save-fn="submitTaxes"
        :filter="taxesFilter"
        :default-remove="false"
        data-key="ItemTax"
        model="ItemTax"
        ref="ItemTaxRef"
        auto-load
    >
        <template #body="{ rows }">
            <QCard class="q-px-lg q-py-md">
                <VnRow
                    v-for="(row, index) in rows"
                    :key="index"
                    class="row q-gutter-md q-mb-md"
                >
                    <VnInput
                        :label="t('tax.country')"
                        v-model="row.country.name"
                        disable
                    />
                    <VnSelect
                        :label="t('tax.class')"
                        v-model="row.taxClassFk"
                        :options="taxesOptions"
                        option-label="description"
                        option-value="id"
                        hide-selected
                    />
                </VnRow>
            </QCard>
        </template>
    </CrudModel>
</template>
