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

import VnPaginate from 'components/ui/VnPaginate.vue';
import FetchData from 'components/FetchData.vue';
import VnLv from 'components/ui/VnLv.vue';
import CardList from 'components/ui/CardList.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';

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

const route = useRoute();
const { t } = useI18n();
const { getTokenMultimedia } = useSession();
const quasar = useQuasar();
const token = getTokenMultimedia();
const orderSummary = ref({
    total: null,
    vat: null,
});
const componentKey = ref(0);
const order = ref(0);

const refresh = () => {
    componentKey.value += 1;
};

function confirmRemove(item) {
    quasar.dialog({
        component: VnConfirm,
        componentProps: {
            title: t('confirmDeletion'),
            message: t('confirmDeletionMessage'),
            promise: async () => remove(item),
        },
    });
}

async function remove(item) {
    await axios.post('OrderRows/removes', {
        actualOrderId: route.params.id,
        rows: [item.id],
    });
    quasar.notify({
        message: t('globals.dataDeleted'),
        type: 'positive',
    });
    refresh();
}

async function confirmOrder() {
    await axios.post(`Orders/${route.params.id}/confirm`);
    quasar.notify({
        message: t('globals.confirm'),
        type: 'positive',
    });
}
</script>

<template>
    <FetchData
        :key="componentKey"
        :url="`Orders/${route.params.id}`"
        @on-fetch="(data) => (order = data)"
        auto-load
    />
    <FetchData
        :key="componentKey"
        :url="`Orders/${route.params.id}/getTotal`"
        @on-fetch="(data) => (orderSummary.total = data)"
        auto-load
    />
    <FetchData
        :key="componentKey"
        :url="`Orders/${route.params.id}/getVAT`"
        @on-fetch="(data) => (orderSummary.vat = data)"
        auto-load
    />
    <QPage :key="componentKey" class="column items-center q-pa-md">
        <div class="vn-card-list">
            <div v-if="!orderSummary.total" class="no-result">
                {{ t('globals.noResults') }}
            </div>
            <QCard v-else class="order-lines-summary q-pa-lg">
                <p class="header text-right block">
                    {{ t('summary') }}
                </p>
                <VnLv
                    v-if="orderSummary.vat && orderSummary.total"
                    :label="t('subtotal')"
                    :value="toCurrency(orderSummary.total - orderSummary.vat)"
                />
                <VnLv
                    v-if="orderSummary.vat"
                    :label="t('VAT')"
                    :value="toCurrency(orderSummary?.vat)"
                />
                <VnLv
                    v-if="orderSummary.total"
                    :label="t('total')"
                    :value="toCurrency(orderSummary?.total)"
                />
            </QCard>
            <VnPaginate
                data-key="OrderLines"
                url="OrderRows"
                :limit="20"
                auto-load
                :filter="{
                    include: [
                        {
                            relation: 'item',
                        },
                        {
                            relation: 'warehouse',
                        },
                    ],
                    where: { orderFk: route.params.id },
                }"
            >
                <template #body="{ rows }">
                    <div class="catalog-list q-mt-xl">
                        <CardList
                            v-for="row in rows"
                            :key="row.id"
                            :id="row.id"
                            :title="row?.item?.name"
                            class="cursor-inherit"
                        >
                            <template #title>
                                <div class="flex items-center">
                                    <div class="image-wrapper q-mr-md">
                                        <QImg
                                            :src="`/api/Images/catalog/50x50/${row?.item?.id}/download?access_token=${token}`"
                                            spinner-color="primary"
                                            :ratio="1"
                                            height="50"
                                            width="50"
                                            class="image"
                                        />
                                    </div>
                                    <div
                                        class="title text-primary text-weight-bold text-h5"
                                    >
                                        {{ row?.item?.name }}
                                    </div>
                                    <QChip class="q-chip-color" outline size="sm">
                                        {{ t('ID') }}: {{ row.id }}
                                    </QChip>
                                </div>
                            </template>
                            <template #list-items>
                                <div class="q-mb-sm">
                                    <span class="text-uppercase subname">
                                        {{ row.item.subName }}
                                    </span>
                                    <fetched-tags :item="row.item" :max-length="5" />
                                </div>
                                <VnLv :label="t('item')" :value="String(row.item.id)" />
                                <VnLv
                                    :label="t('warehouse')"
                                    :value="row.warehouse.name"
                                />
                                <VnLv
                                    :label="t('shipped')"
                                    :value="toDate(row.shipped)"
                                />
                                <VnLv
                                    :label="t('quantity')"
                                    :value="String(row.quantity)"
                                />
                                <VnLv
                                    :label="t('price')"
                                    :value="toCurrency(row.price)"
                                />
                                <VnLv
                                    :label="t('amount')"
                                    :value="toCurrency(row.price * row.quantity)"
                                />
                            </template>
                            <template #actions v-if="!order?.isConfirmed">
                                <QBtn
                                    :label="t('remove')"
                                    @click.stop="confirmRemove(row)"
                                    color="primary"
                                    style="margin-top: 15px"
                                />
                            </template>
                        </CardList>
                    </div>
                </template>
            </VnPaginate>
        </div>
        <QPageSticky :offset="[20, 20]" v-if="!order?.isConfirmed">
            <QBtn fab icon="check" color="primary" @click="confirmOrder()" />
            <QTooltip>
                {{ t('confirm') }}
            </QTooltip>
        </QPageSticky>
    </QPage>
</template>
<style lang="scss">
.order-lines-summary {
    .vn-label-value {
        display: flex;
        justify-content: flex-end;
        gap: 2%;

        .label {
            color: var(--vn-label-color);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .value {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>
<style lang="scss" scoped>
.header {
    color: $primary;
    font-weight: bold;
    margin-bottom: 25px;
    font-size: 20px;
    display: inline-block;
}

.image-wrapper {
    height: 50px;
    width: 50px;

    .image {
        border-radius: 50%;
    }
}

.subname {
    color: var(--vn-label-color);
}

.no-result {
    font-size: 24px;
    font-weight: bold;
    color: var(--vn-label-color);
    text-align: center;
}
</style>
<i18n>
en:
    summary: Summary
    subtotal: Subtotal
    VAT: VAT
    total: Total
    item: Item
    warehouse: Warehouse
    shipped: Shipped
    quantity: Quantity
    price: Price
    amount: Amount
    remove: Remove
    confirmDeletion: Confirm deletion,
    confirmDeletionMessage: Are you sure you want to delete this item?
    confirm: Confirm
es:
    summary: Resumen
    subtotal: Subtotal
    VAT: IVA
    total: Total
    item: Artículo
    warehouse: Almacén
    shipped: F. envío
    quantity: Cantidad
    price: Precio
    amount: Importe
    remove: Eliminar
    confirmDeletion: Confirmar eliminación,
    confirmDeletionMessage: Seguro que quieres eliminar este artículo?
    confirm: Confirmar
</i18n>
