<script setup>
import { onMounted, ref, computed } 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 TravelDescriptorProxy from 'src/pages/Travel/Card/TravelDescriptorProxy.vue';

import { toDate, toCurrency } from 'src/filters';
import { getUrl } from 'src/composables/getUrl';
import axios from 'axios';
import FetchedTags from 'src/components/ui/FetchedTags.vue';
import VnToSummary from 'src/components/ui/VnToSummary.vue';

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('globals.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('globals.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 () => {
        const { data } = await axios.get(`Entries/${entry.value.id}/getBuys`);
        if (data) entryBuys.value = data;

};
</script>

<template>
    <CardSummary
        ref="summaryRef"
        :url="`Entries/${entityId}/getEntry`"
        @on-fetch="(data) => setEntryData(data)"
        data-key="EntrySummary"
    >
        <template #header-left>
            <VnToSummary
                v-if="route?.name !== 'EntrySummary'"
                :route-name="'EntrySummary'"
                :entity-id="entityId"
                :url="entryUrl"
            />
        </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('globals.company')" :value="entry.company.code" />
                <VnLv :label="t('globals.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('shipped')" :value="toDate(entry.travel.shipped)" />
                <VnLv
                    :label="t('globals.warehouseOut')"
                    :value="entry.travel.warehouseOut?.name"
                />
                <QCheckbox
                    :label="t('entry.summary.travelDelivered')"
                    v-model="entry.travel.isDelivered"
                    :disable="true"
                />
                <VnLv :label="t('landed')" :value="toDate(entry.travel.landed)" />
                <VnLv
                    :label="t('globals.warehouseIn')"
                    :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('globals.confirmed')"
                    v-model="entry.isConfirmed"
                    :disable="true"
                />
                <QCheckbox
                    :label="t('entry.summary.booked')"
                    v-model="entry.isBooked"
                    :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()"
                                    v-bind="tableColumnComponents[col?.name].props()"
                                    @click="tableColumnComponents[col?.name].event()"
                                    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>
                                <FetchedTags :item="row.item" />
                            </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>

<style lang="scss" scoped>
.separation-row {
    background-color: var(--vn-section-color) !important;
}
</style>

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