<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 FetchedTags from 'components/ui/FetchedTags.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import VnImg from 'components/ui/VnImg.vue';

import { toCurrency, toDate } from 'src/filters';
import axios from 'axios';
import ItemDescriptorProxy from '../Item/Card/ItemDescriptorProxy.vue';

const route = useRoute();
const { t } = useI18n();
const quasar = useQuasar();
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',
    });
}

const detailsColumns = ref([
    {
        name: 'img',
        label: '',
        field: (row) => row?.item?.id,
    },
    {
        name: 'item',
        label: t('order.summary.item'),
        field: (row) => row?.item?.id,
        sortable: true,
    },
    {
        name: 'description',
        label: t('globals.description'),
        field: (row) => row?.item?.name,
    },
    {
        name: 'warehouse',
        label: t('warehouse'),
        field: (row) => row?.warehouse?.name,
        sortable: true,
    },
    {
        name: 'shipped',
        label: t('shipped'),
        field: (row) => toDate(row?.shipped),
    },
    {
        name: 'quantity',
        label: t('order.summary.quantity'),
        field: (row) => row?.quantity,
    },
    {
        name: 'price',
        label: t('order.summary.price'),
        field: (row) => toCurrency(row?.price),
    },
    {
        name: 'amount',
        label: t('order.summary.amount'),
        field: (row) => toCurrency(row?.quantity * row?.price),
    },
    {
        name: 'actions',
        label: '',
        field: (row) => row?.id,
    },
]);
</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="order-list full-width">
            <div v-if="!orderSummary.total" class="no-result">
                {{ t('globals.noResults') }}
            </div>

            <QDrawer side="right" :width="270" show-if-above>
                <QCard 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>
            </QDrawer>
            <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="q-pa-md">
                        <QTable
                            :columns="detailsColumns"
                            :rows="rows"
                            flat
                            class="full-width"
                            style="text-align: center"
                        >
                            <template #header="props">
                                <QTr class="tr-header" :props="props">
                                    <QTh
                                        v-for="col in props.cols"
                                        :key="col.name"
                                        :props="props"
                                        style="text-align: center"
                                    >
                                        {{ t(col.label) }}
                                    </QTh>
                                </QTr>
                            </template>
                            <template #body-cell-img="{ value }">
                                <QTd>
                                    <div class="image-wrapper">
                                        <VnImg :id="value" class="rounded" />
                                    </div>
                                </QTd>
                            </template>
                            <template #body-cell-item="{ value }">
                                <QTd class="item">
                                    <span class="link">
                                        <QBtn flat>
                                            {{ value }}
                                        </QBtn>
                                        <ItemDescriptorProxy :id="value" />
                                    </span>
                                </QTd>
                            </template>
                            <template #body-cell-description="{ row, value }">
                                <QTd>
                                    <div
                                        class="row column full-width justify-between items-start"
                                    >
                                        {{ value }}
                                        <div v-if="value" class="subName">
                                            {{ value.toUpperCase() }}
                                        </div>
                                    </div>
                                    <FetchedTags :item="row.item" :max-length="6" />
                                </QTd>
                            </template>

                            <template #body-cell-actions="{ value }">
                                <QTd>
                                    <QIcon
                                        name="delete"
                                        color="primary"
                                        size="sm"
                                        class="cursor-pointer"
                                        @click.stop="confirmRemove(value)"
                                    >
                                        <QTooltip>{{ t('Remove thermograph') }}</QTooltip>
                                    </QIcon>
                                </QTd>
                            </template>
                        </QTable>
                    </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;
    margin-left: 30%;
}

.no-result {
    font-size: 24px;
    font-weight: bold;
    color: var(--vn-label-color);
    text-align: center;
}

.subName {
    text-transform: uppercase;
    color: var(--vn-label-color);
}
</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>
