<script setup>
import { ref, computed } from 'vue';
import { useQuasar, useDialogPluginComponent } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import FetchData from 'components/FetchData.vue';
import { toDate, toCurrency, toPercentage } from 'filters/index';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import axios from 'axios';

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const route = useRoute();
const quasar = useQuasar();
const { t } = useI18n();

const $props = defineProps({
    ticketId: {
        type: Number,
        required: true,
    },
});

const columns = computed(() => [
    {
        name: 'delivered',
        label: t('Delivered'),
        field: (row) => row.landed,
        format: (value) => toDate(value),
        sortable: true,
    },
    {
        name: 'quantity',
        label: t('Quantity'),
        field: (row) => row.quantity,
        sortable: true,
        default: 0,
    },
    {
        name: 'description',
        label: t('Description'),
        field: (row) => row.concept,
    },
    {
        name: 'price',
        label: t('Price'),
        field: (row) => row.price,
        format: (value) => toCurrency(value),
        sortable: true,
    },
    {
        name: 'discount',
        label: t('Discount'),
        field: (row) => row.discount,
        format: (value) => toPercentage(value),
        sortable: true,
    },
]);

const selected = ref([]);
const claimableSales = ref([]);
const isLoading = ref(false);
let canceller;

async function importLines() {
    const sales = selected.value;

    if (!sales.length) {
        return quasar.notify({
            message: 'You must select at least one',
            type: 'warning',
        });
    }

    const body = sales.map((row) => ({
        claimFk: route.params.id,
        saleFk: row.saleFk,
    }));

    canceller = new AbortController();
    isLoading.value = true;

    const { data } = await axios.post('ClaimBeginnings', body, {
        signal: canceller.signal,
    });

    quasar.notify({
        message: 'Lines added to claim',
        type: 'positive',
    });

    onDialogOK(data);

    canceller = null;
    isLoading.value = false;
}

function cancel() {
    if (canceller) {
        canceller.abort();
        canceller = null;
    }

    onDialogCancel();
}
</script>
<template>
    <FetchData
        :url="`Sales/getClaimableFromTicket?ticketFk=${$props.ticketId}`"
        @on-fetch="(data) => (claimableSales = data)"
        auto-load
    />
    <QDialog ref="dialogRef">
        <QCard>
            <QCardSection class="row items-center">
                <span class="text-h6 text-grey">{{ t('Available sales lines') }}</span>
                <QSpace />
                <QBtn icon="close" flat round dense v-close-popup />
            </QCardSection>
            <QTable
                :columns="columns"
                :rows="claimableSales"
                row-key="saleFk"
                selection="multiple"
                v-model:selected="selected"
                square
                flat
            >
                <template #body-cell-description="{ row, value }">
                    <QTd auto-width align="right" class="link">
                        {{ value }}
                        <ItemDescriptorProxy :id="row.itemFk"></ItemDescriptorProxy>
                    </QTd>
                </template>
            </QTable>
            <QSeparator />
            <QCardActions align="right">
                <QBtn :label="t('globals.cancel')" color="primary" flat @click="cancel" />
                <QBtn
                    :label="t('globals.confirm')"
                    color="primary"
                    :loading="isLoading"
                    @click="importLines"
                    unelevated
                />
            </QCardActions>
        </QCard>
    </QDialog>
</template>

<style lang="scss" scoped>
.q-card {
    max-width: 800px;
}
</style>

<i18n>
es:
    Available sales lines: Líneas de venta disponibles
    Delivered: Entrega
    Quantity: Cantidad
    Description: Descripción
    Price: Precio
    Discount: Descuento
    Lines added to claim: Lineas añadidas a la reclamación
    You must select at least one: Debes seleccionar al menos una
</i18n>
