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

import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import VnRow from 'components/ui/VnRow.vue';
import TravelDescriptorProxy from 'src/pages/Travel/Card/TravelDescriptorProxy.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';

import { toDate, toCurrency } from 'src/filters';
import { getUrl } from 'src/composables/getUrl';
import axios from 'axios';

onUpdated(() => summaryRef.value.fetch());

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

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const entityId = computed(() => $props.id || route.params.id);
const summaryRef = ref();
const entry = ref();
const entryBuys = ref([]);
const entryUrl = ref();

onMounted(async () => {
    entryUrl.value = (await getUrl('entry/')) + entityId.value;
});

const tableColumnComponents = {
    quantity: {
        component: () => 'span',
        props: () => {},
    },
    stickers: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    packagingFk: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    weight: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    packing: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    grouping: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    buyingValue: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    amount: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
    pvp: {
        component: () => 'span',
        props: () => {},
        event: () => {},
    },
};

const entriesTableColumns = computed(() => {
    return [
        {
            label: t('entry.summary.quantity'),
            field: 'quantity',
            name: 'quantity',
            align: 'left',
        },
        {
            label: t('entry.summary.stickers'),
            field: 'stickers',
            name: 'stickers',
            align: 'left',
        },
        {
            label: t('entry.summary.package'),
            field: 'packagingFk',
            name: 'packagingFk',
            align: 'left',
        },
        {
            label: t('entry.summary.weight'),
            field: 'weight',
            name: 'weight',
            align: 'left',
        },
        {
            label: t('entry.summary.packing'),
            field: 'packing',
            name: 'packing',
            align: 'left',
        },
        {
            label: t('entry.summary.grouping'),
            field: 'grouping',
            name: 'grouping',
            align: 'left',
        },
        {
            label: t('entry.summary.buyingValue'),
            field: 'buyingValue',
            name: 'buyingValue',
            align: 'left',
            format: (value) => toCurrency(value),
        },
        {
            label: t('entry.summary.import'),
            name: 'amount',
            align: 'left',
            format: (_, row) => toCurrency(row.buyingValue * row.quantity),
        },
        {
            label: t('entry.summary.pvp'),
            name: 'pvp',
            align: 'left',
            format: (_, row) => toCurrency(row.price2) + ' / ' + toCurrency(row.price3),
        },
    ];
});

async function setEntryData(data) {
    if (data) entry.value = data;
    await fetchEntryBuys();
}

const fetchEntryBuys = async () => {
    try {
        const { data } = await axios.get(`Entries/${entry.value.id}/getBuys`);
        if (data) entryBuys.value = data;
    } catch (err) {
        console.error('Error fetching entry buys');
    }
};
</script>

<template>
    <CardSummary
        ref="summaryRef"
        :url="`Entries/${entityId}/getEntry`"
        @on-fetch="(data) => setEntryData(data)"
    >
        <template #header-left>
            <router-link
                v-if="route.name !== 'EntrySummary'"
                :to="{ name: 'EntrySummary', params: { id: entityId } }"
                class="header link"
                :href="entryUrl"
            >
                <QIcon name="open_in_new" color="white" size="sm" />
            </router-link>
        </template>
        <template #header>
            <span>{{ entry.id }} - {{ entry.supplier.nickname }}</span>
        </template>
        <template #body>
            <QCard class="vn-one">
                <router-link
                    :to="{ name: 'EntryBasicData', params: { id: entityId } }"
                    class="header header-link"
                >
                    {{ t('globals.summary.basicData') }}
                    <QIcon name="open_in_new" />
                </router-link>

                <VnLv :label="t('entry.summary.commission')" :value="entry.commission" />

                <VnLv :label="t('entry.summary.currency')" :value="entry.currency.name" />

                <VnLv :label="t('entry.summary.company')" :value="entry.company.code" />

                <VnLv :label="t('entry.summary.reference')" :value="entry.reference" />

                <VnLv
                    :label="t('entry.summary.invoiceNumber')"
                    :value="entry.invoiceNumber"
                />
            </QCard>
            <QCard class="vn-one">
                <router-link
                    :to="{ name: 'EntryBasicData', params: { id: entityId } }"
                    class="header header-link"
                >
                    {{ t('globals.summary.basicData') }}
                    <QIcon name="open_in_new" />
                </router-link>

                <VnLv :label="t('entry.summary.travelReference')">
                    <template #value>
                        <span class="link">
                            {{ entry.travel.ref }}
                            <TravelDescriptorProxy :id="entry.travel.id" />
                        </span>
                    </template>
                </VnLv>

                <VnLv
                    :label="t('entry.summary.travelAgency')"
                    :value="entry.travel.agency.name"
                />

                <VnLv
                    :label="t('entry.summary.travelShipped')"
                    :value="toDate(entry.travel.shipped)"
                />

                <VnLv
                    :label="t('entry.summary.travelWarehouseOut')"
                    :value="entry.travel.warehouseOut.name"
                />

                <QCheckbox
                    :label="t('entry.summary.travelDelivered')"
                    v-model="entry.travel.isDelivered"
                    :disable="true"
                />
                <VnLv
                    :label="t('entry.summary.travelLanded')"
                    :value="toDate(entry.travel.landed)"
                />

                <VnLv
                    :label="t('entry.summary.travelWarehouseIn')"
                    :value="entry.travel.warehouseIn.name"
                />

                <QCheckbox
                    :label="t('entry.summary.travelReceived')"
                    v-model="entry.travel.isReceived"
                    :disable="true"
                />
            </QCard>
            <QCard class="vn-one">
                <router-link
                    :to="{ name: 'TravelSummary', params: { id: entry.travel.id } }"
                    class="header header-link"
                >
                    {{ t('Travel data') }}
                    <QIcon name="open_in_new" />
                </router-link>
                <QCheckbox
                    :label="t('entry.summary.ordered')"
                    v-model="entry.isOrdered"
                    :disable="true"
                />
                <QCheckbox
                    :label="t('entry.summary.confirmed')"
                    v-model="entry.isConfirmed"
                    :disable="true"
                />
                <QCheckbox
                    :label="t('entry.summary.booked')"
                    v-model="entry.isBooked"
                    :disable="true"
                />
                <QCheckbox
                    :label="t('entry.summary.raid')"
                    v-model="entry.isRaid"
                    :disable="true"
                />
                <QCheckbox
                    :label="t('entry.summary.excludedFromAvailable')"
                    v-model="entry.isExcludedFromAvailable"
                    :disable="true"
                />
            </QCard>
            <QCard class="vn-two" style="min-width: 100%">
                <a class="header header-link">
                    {{ t('entry.summary.buys') }}
                    <QIcon name="open_in_new" />
                </a>
                <QTable
                    :rows="entryBuys"
                    :columns="entriesTableColumns"
                    row-key="index"
                    class="full-width q-mt-md"
                    :no-data-label="t('globals.noResults')"
                >
                    <template #body="{ cols, row, rowIndex }">
                        <QTr no-hover>
                            <QTd v-for="col in cols" :key="col.name">
                                <component
                                    :is="tableColumnComponents[col.name].component(props)"
                                    v-bind="tableColumnComponents[col.name].props(props)"
                                    @click="tableColumnComponents[col.name].event(props)"
                                    class="col-content"
                                >
                                    <template
                                        v-if="
                                            col.name !== 'observation' &&
                                            col.name !== 'isConfirmed'
                                        "
                                        >{{ col.value }}</template
                                    >
                                    <QTooltip v-if="col.toolTip">{{
                                        col.toolTip
                                    }}</QTooltip>
                                </component>
                            </QTd>
                        </QTr>
                        <QTr no-hover>
                            <QTd>
                                <span>{{ row.item.itemType.code }}</span>
                            </QTd>
                            <QTd>
                                <span>{{ row.item.id }}</span>
                            </QTd>
                            <QTd>
                                <span>{{ row.item.size }}</span>
                            </QTd>
                            <QTd>
                                <span>{{ toCurrency(row.item.minPrice) }}</span>
                            </QTd>
                            <QTd colspan="6">
                                <span>{{ row.item.concept }}</span>
                                <span v-if="row.item.subName" class="subName">
                                    {{ row.item.subName }}
                                </span>
                                <fetched-tags :item="row.item" :max-length="5" />
                            </QTd>
                        </QTr>
                        <!-- Esta última row es utilizada para agregar un espaciado y así marcar una diferencia visual entre los diferentes buys -->
                        <QTr v-if="rowIndex !== entryBuys.length - 1">
                            <QTd colspan="10" class="vn-table-separation-row" />
                        </QTr>
                    </template>
                </QTable>
            </QCard>
        </template>
    </CardSummary>
</template>

<i18n>
es:
    Travel data: Datos envío
</i18n>
