<script setup>
import { onMounted, ref, computed } from 'vue';
import { QBtn, QField, QPopupEdit } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import SupplierDescriptorProxy from 'src/pages/Supplier/Card/SupplierDescriptorProxy.vue';
import TravelDescriptorProxy from 'src/pages/Travel/Card/TravelDescriptorProxy.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import ExtraCommunityFilter from './ExtraCommunityFilter.vue';
import VnInput from 'src/components/common/VnInput.vue';
import EntryDescriptorProxy from '../Entry/Card/EntryDescriptorProxy.vue';

import { useStateStore } from 'stores/useStateStore';
import { toCurrency } from 'src/filters';
import { useArrayData } from 'composables/useArrayData';
import { toDate } from 'src/filters';
import { usePrintService } from 'composables/usePrintService';
import travelService from 'src/services/travel.service';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

const router = useRouter();
const stateStore = useStateStore();
const { t } = useI18n();
const { openReport } = usePrintService();

const shippedFrom = ref(Date.vnNew());
const landedTo = ref(Date.vnNew());

const arrayData = useArrayData('ExtraCommunity', {
    url: 'Travels/extraCommunityFilter',
    limit: 0,
    order: [
        'landed ASC',
        'shipped ASC',
        'travelFk',
        'loadPriority',
        'agencyModeFk',
        'supplierName',
        'evaNotes',
    ],
    userParams: {
        continent: 'AM',
        shippedFrom: shippedFrom.value,
        landedTo: landedTo.value,
    },
});

const rows = computed(() => arrayData.store.data || []);

const tableColumnComponents = {
    id: {
        component: QBtn,
        attrs: () => ({ flat: true, color: 'blue', class: 'col-content' }),
    },
    cargoSupplierNickname: {
        component: QBtn,
        attrs: () => ({ flat: true, color: 'blue', class: 'col-content' }),
    },
    agencyModeName: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    invoiceAmount: {
        component: 'span',
        attrs: () => ({
            class: 'col-content',
        }),
    },
    ref: {
        component: QField,
        attrs: () => ({ readonly: true, dense: true }),
    },
    stickers: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    kg: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    loadedKg: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    volumeKg: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    warehouseOutName: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    shipped: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    warehouseInName: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
    landed: {
        component: 'span',
        attrs: () => ({ class: 'col-content' }),
    },
};

const columns = computed(() => [
    {
        label: 'id',
        field: 'id',
        name: 'id',
        align: 'left',
        showValue: true,
    },
    {
        label: t('supplier.pageTitles.supplier'),
        field: 'cargoSupplierNickname',
        name: 'cargoSupplierNickname',
        align: 'left',
        showValue: true,
    },
    {
        label: t('globals.agency'),
        field: 'agencyModeName',
        name: 'agencyModeName',
        align: 'left',
        showValue: true,
    },
    {
        label: t('globals.amount'),
        name: 'invoiceAmount',
        field: 'entries',
        align: 'left',
        showValue: true,
        format: (value) =>
            toCurrency(
                value
                    ? value.reduce((sum, entry) => {
                          return sum + (entry.invoiceAmount || 0);
                      }, 0)
                    : 0
            ),
    },
    {
        label: t('globals.reference'),
        field: 'ref',
        name: 'ref',
        align: 'left',
        showValue: false,
    },
    {
        label: t('globals.packages'),
        field: 'stickers',
        name: 'stickers',
        align: 'left',
        showValue: true,
    },
    {
        label: t('kg'),
        field: 'kg',
        name: 'kg',
        align: 'left',
        showValue: true,
    },
    {
        label: t('physicKg'),
        field: 'loadedKg',
        name: 'loadedKg',
        align: 'left',
        showValue: true,
    },
    {
        label: 'KG Vol.',
        field: 'volumeKg',
        name: 'volumeKg',
        align: 'left',
        showValue: true,
    },
    {
        label: t('globals.wareHouseOut'),
        field: 'warehouseOutName',
        name: 'warehouseOutName',
        align: 'left',
        showValue: true,
    },
    {
        label: t('shipped'),
        field: 'shipped',
        name: 'shipped',
        align: 'left',
        format: (value) => toDate(value.substring(0, 10)),
        showValue: true,
    },
    {
        label: t('globals.wareHouseIn'),
        field: 'warehouseInName',
        name: 'warehouseInName',
        align: 'left',
        showValue: true,
    },
    {
        label: t('landed'),
        field: 'landed',
        name: 'landed',
        align: 'left',
        format: (value) => toDate(value.substring(0, 10)),
        showValue: true,
    },
]);

async function getData() {
    await arrayData.fetch({ append: false });
}

const openReportPdf = () => {
    const params = {
        ...arrayData.store.userParams,
        limit: arrayData.store.limit,
    };

    openReport('Travels/extra-community-pdf', params);
};

const saveFieldValue = async (val, field, index) => {
    const id = rows.value[index].id;
    const params = { [field]: val };
    await travelService.updateTravel(id, params);
};

const navigateToTravelId = (id) => {
    router.push({ path: `/travel/${id}` });
};

const stopEventPropagation = (event, col) => {
    if (!['ref', 'id', 'cargoSupplierNickname'].includes(col.name)) return;
    event.preventDefault();
    event.stopPropagation();
};

onMounted(async () => {
    stateStore.rightDrawer = true;

    shippedFrom.value.setDate(shippedFrom.value.getDate() - 2);
    shippedFrom.value.setHours(0, 0, 0, 0);

    landedTo.value.setDate(landedTo.value.getDate() + 7);
    landedTo.value.setHours(23, 59, 59, 59);
    await getData();
});
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                data-key="ExtraCommunity"
                :limit="20"
                :label="t('searchExtraCommunity')"
            />
        </Teleport>
    </template>
    <VnSubToolbar class="bg-vn-dark justify-end">
        <template #st-actions>
            <QBtn
                color="primary"
                icon-right="picture_as_pdf"
                no-caps
                @click="openReportPdf()"
            >
                <QTooltip>
                    {{ t('Open as PDF') }}
                </QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <ExtraCommunityFilter data-key="ExtraCommunity" />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center q-pa-md">
        <QTable
            :rows="rows"
            :columns="columns"
            hide-bottom
            row-key="clientId"
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
        >
            <template #body="props">
                <QTr
                    :props="props"
                    @click="navigateToTravelId(props.row.id)"
                    class="cursor-pointer"
                >
                    <QTd
                        v-for="col in props.cols"
                        :key="col.name"
                        :props="props"
                        @click="stopEventPropagation($event, col)"
                    >
                        <component
                            :is="tableColumnComponents[col.name].component"
                            class="col-content"
                            v-bind="tableColumnComponents[col.name].attrs(props)"
                        >
                            <!-- Editable 'ref' and 'kg' QField slot -->
                            <template
                                v-if="col.name === 'ref' || col.name === 'kg'"
                                #control
                            >
                                <div
                                    class="self-center full-width no-outline"
                                    tabindex="0"
                                >
                                    {{ col.value }}
                                </div>
                                <QPopupEdit
                                    :key="col.name"
                                    v-model="col.value"
                                    label-set="Save"
                                    label-cancel="Close"
                                >
                                    <VnInput
                                        v-model="rows[props.pageIndex][col.field]"
                                        dense
                                        autofocus
                                        @keyup.enter="
                                            saveFieldValue(
                                                rows[props.pageIndex][col.field],
                                                col.field,
                                                props.rowIndex
                                            )
                                        "
                                    />
                                </QPopupEdit>
                            </template>

                            <template v-if="col.showValue">
                                {{ col.value }}
                            </template>

                            <!-- Main Row Descriptors -->
                            <TravelDescriptorProxy
                                v-if="col.name === 'id'"
                                :id="props.row.id"
                            />
                            <SupplierDescriptorProxy
                                v-if="col.name === 'cargoSupplierNickname'"
                                :id="props.row.cargoSupplierFk"
                            />
                        </component>
                    </QTd>
                </QTr>
                <QTr
                    v-for="entry in props.row.entries"
                    :key="entry.id"
                    :props="props"
                    class="secondary-row"
                >
                    <QTd>
                        <QBtn flat color="blue" class="col-content">{{ entry.id }} </QBtn>
                        <EntryDescriptorProxy :id="entry.id" />
                    </QTd>
                    <QTd
                        ><QBtn flat color="blue" class="col-content">{{
                            entry.supplierName
                        }}</QBtn>
                        <SupplierDescriptorProxy :id="entry.supplierFk" />
                    </QTd>
                    <QTd></QTd>
                    <QTd
                        ><span class="col-content">{{
                            toCurrency(entry.invoiceAmount)
                        }}</span></QTd
                    >
                    <QTd
                        ><span class="col-content">{{ entry.reference }}</span></QTd
                    >
                    <QTd
                        ><span class="col-content">{{ entry.stickers }}</span></QTd
                    >
                    <QTd></QTd>
                    <QTd
                        ><span class="col-content">{{ entry.loadedkg }}</span></QTd
                    >
                    <QTd
                        ><span class="col-content">{{ entry.volumeKg }}</span></QTd
                    >
                    <QTd></QTd>
                    <QTd></QTd>
                    <QTd></QTd>
                    <QTd></QTd>
                </QTr>
            </template>
        </QTable>
    </QPage>
</template>

<style lang="scss" scoped>
.col-content {
    border-radius: 4px;
    padding: 6px;
}

.secondary-row {
    background-color: var(--vn-gray);
}
</style>

<i18n>
en:
    searchExtraCommunity: Search for extra community shipping
    kg: BI. KG
    physicKg: Phy. KG
    shipped: W. shipped
    landed: W. landed

es:
    searchExtraCommunity: Buscar por envío extra comunitario
    kg: KG Bloq.
    physicKg: KG físico
    shipped: F. envío
    landed: F. llegada
    Open as PDF: Abrir como PDF
</i18n>
