<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { exportFile, useQuasar } from 'quasar';
import { useStateStore } from 'stores/useStateStore';
import VnPaginate from 'src/components/ui/VnPaginate.vue';
import InvoiceOutSummaryDialog from './Card/InvoiceOutSummaryDialog.vue';
import { toDate, toCurrency } from 'src/filters/index';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import InvoiceOutFilter from './InvoiceOutFilter.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import CardList from 'src/components/ui/CardList.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

const { t } = useI18n();
const selectedCards = ref(new Map());
const quasar = useQuasar();
const router = useRouter();
const stateStore = useStateStore();

onMounted(() => (stateStore.rightDrawer = true));
onUnmounted(() => (stateStore.rightDrawer = false));

function navigate(id) {
    router.push({ path: `/invoice-out/${id}` });
}

function viewSummary(id) {
    quasar.dialog({
        component: InvoiceOutSummaryDialog,
        componentProps: {
            id,
        },
    });
}

const toggleIndividualCard = (cardData) => {
    if (selectedCards.value.has(cardData.id)) {
        selectedCards.value.delete(cardData.id);
        return;
    }
    selectedCards.value.set(cardData.id, cardData);
};

const toggleAllCards = (cardsData) => {
    const allSelected = selectedCards.value.size === cardsData.length;

    if (!allSelected) {
        // Si no todas las tarjetas están seleccionadas, selecciónalas todas
        cardsData.forEach((data) => {
            if (!selectedCards.value.has(data.id)) {
                selectedCards.value.set(data.id, data);
            }
        });
    } else {
        // Si todas las tarjetas están seleccionadas, deselecciónalas todas
        selectedCards.value.clear();
    }
};

const downloadCsv = () => {
    if (selectedCards.value.size === 0) return;
    const selectedCardsArray = Array.from(selectedCards.value.values());
    let file;
    for (var i = 0; i < selectedCardsArray.length; i++) {
        if (i == 0) file += Object.keys(selectedCardsArray[i]).join(';') + '\n';
        file +=
            Object.keys(selectedCardsArray[i])
                .map(function (key) {
                    return selectedCardsArray[i][key];
                })
                .join(';') + '\n';
    }
    const status = exportFile('file.csv', file, {
        encoding: 'windows-1252',
        mimeType: 'text/csv;charset=windows-1252;',
    });
    if (status === true) {
        quasar.notify({
            message: t('fileAllowed'),
            color: 'positive',
            icon: 'check',
        });
    } else {
        quasar.notify({
            message: t('fileDenied'),
            color: 'negative',
            icon: 'warning',
        });
    }
};
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                :info="t('youCanSearchByInvoiceReference')"
                :label="t('searchInvoice')"
                data-key="InvoiceOutList"
            />
        </Teleport>
        <Teleport to="#actions-append">
            <div class="row q-gutter-x-sm">
                <QBtn
                    @click="stateStore.toggleRightDrawer()"
                    dense
                    flat
                    icon="menu"
                    round
                >
                    <QTooltip bottom anchor="bottom right">
                        {{ t('globals.collapseMenu') }}
                    </QTooltip>
                </QBtn>
            </div>
        </Teleport>
    </template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <InvoiceOutFilter data-key="InvoiceOutList" />
        </QScrollArea>
    </QDrawer>
    <QPage>
        <VnPaginate
            auto-load
            data-key="InvoiceOutList"
            order="issued DESC, id DESC"
            url="InvoiceOuts/filter"
        >
            <template #body="{ rows }">
                <VnSubToolbar class="bg-vn-dark justify-end">
                    <template #st-actions>
                        <QBtn
                            @click="downloadCsv()"
                            class="q-mr-xl"
                            color="primary"
                            :disable="selectedCards.size === 0"
                            :label="t('globals.download')"
                        />
                        <!-- <QBtnDropdown
                            class="q-mr-xl"
                            color="primary"
                            :disable="!manageCheckboxes && arrayElements.length < 1"
                            :label="t('globals.download')"
                            v-else
                        >
                            <QList>
                                <QItem clickable v-close-popup @click="downloadCsv(rows)">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{
                                                t('globals.allRows', {
                                                    numberRows: rows.length,
                                                })
                                            }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>

                                <QItem clickable v-close-popup @click="downloadCsv(rows)">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{
                                                t('globals.selectRows', {
                                                    numberRows: rows.length,
                                                })
                                            }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>
                            </QList>
                        </QBtnDropdown> -->
                        <QCheckbox
                            left-label
                            :label="t('globals.markAll')"
                            @click="toggleAllCards(rows)"
                            :model-value="selectedCards.size === rows.length"
                            class="q-mr-md"
                        />
                    </template>
                </VnSubToolbar>
                <div class="flex flex-center q-pa-md">
                    <div class="vn-card-list">
                        <CardList
                            :element="row"
                            :id="row.id"
                            :show-checkbox="true"
                            :is-selected="selectedCards.has(row.id)"
                            :key="row.id"
                            :title="row.ref"
                            @click="navigate(row.id)"
                            @toggle-card-check="toggleIndividualCard(row)"
                            v-for="row of rows"
                        >
                            <template #list-items>
                                <VnLv
                                    :label="t('invoiceOut.list.shortIssued')"
                                    :title-label="t('invoiceOut.list.issued')"
                                    :value="toDate(row.issued)"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.amount')"
                                    :value="toCurrency(row.amount)"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.client')"
                                    :value="row.clientSocialName"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.shortCreated')"
                                    :title-label="t('invoiceOut.list.created')"
                                    :value="toDate(row.created)"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.company')"
                                    :value="row.companyCode"
                                />
                                <VnLv
                                    :label="t('invoiceOut.list.shortDued')"
                                    :title-label="t('invoiceOut.list.dued')"
                                    :value="toDate(row.dued)"
                                />
                            </template>
                            <template #actions>
                                <QBtn
                                    :label="t('components.smartCard.openCard')"
                                    @click.stop="navigate(row.id)"
                                    class="bg-vn-dark"
                                    outline
                                    type="reset"
                                />
                                <QBtn
                                    :label="t('components.smartCard.openSummary')"
                                    @click.stop="viewSummary(row.id)"
                                    color="primary"
                                    style="margin-top: 15px"
                                    type="submit"
                                />
                            </template>
                        </CardList>
                    </div>
                </div>
            </template>
        </VnPaginate>
    </QPage>
</template>

<i18n>
en:
    searchInvoice: Search issued invoice
    fileDenied: Browser denied file download...
    fileAllowed: Successful download of CSV file
    youCanSearchByInvoiceReference: You can search by invoice reference
es:
    searchInvoice: Buscar factura emitida
    fileDenied: El navegador denegó la descarga de archivos...
    fileAllowed: Descarga exitosa de archivo CSV
    youCanSearchByInvoiceReference: Puedes buscar por referencia de la factura
</i18n>
