<script setup>
import VnPaginate from 'components/ui/VnPaginate.vue';
import { useStateStore } from 'stores/useStateStore';
import { useI18n } from 'vue-i18n';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { dashIfEmpty, toCurrency, toDate } from 'src/filters';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import RouteDescriptorProxy from 'pages/Route/Card/RouteDescriptorProxy.vue';
import InvoiceInDescriptorProxy from 'pages/InvoiceIn/Card/InvoiceInDescriptorProxy.vue';
import SupplierDescriptorProxy from 'pages/Supplier/Card/SupplierDescriptorProxy.vue';
import VnLv from 'components/ui/VnLv.vue';
import useNotify from 'composables/useNotify';
import RouteAutonomousFilter from 'pages/Route/Card/RouteAutonomousFilter.vue';
import { useRouter } from 'vue-router';
import RouteSummary from 'pages/Route/Card/RouteSummary.vue';
import { useSummaryDialog } from 'composables/useSummaryDialog';
import VnDms from 'components/common/VnDms.vue';
import { useState } from 'composables/useState';
import axios from 'axios';

const stateStore = useStateStore();
const { t } = useI18n();
const { notify } = useNotify();
const router = useRouter();
const { viewSummary } = useSummaryDialog();

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

const state = useState();
const user = state.getUser();
const dmsDialog = ref({
    show: false,
    initialForm: {},
    rowsToCreateInvoiceIn: [],
});
const selectedRows = ref([]);
const columns = computed(() => [
    {
        name: 'ID',
        label: t('ID'),
        field: (row) => row.routeFk,
        sortable: true,
        align: 'left',
    },
    {
        name: 'date',
        label: t('Date'),
        field: (row) => toDate(row.created),
        sortable: true,
        align: 'left',
    },
    {
        name: 'agency-route',
        label: t('Agency route'),
        field: (row) => row?.agencyModeName,
        sortable: true,
        align: 'left',
    },
    {
        name: 'agency-agreement',
        label: t('Agency agreement'),
        field: (row) => row?.agencyAgreement,
        sortable: true,
        align: 'left',
    },
    {
        name: 'packages',
        label: t('Packages'),
        field: (row) => dashIfEmpty(row.packages),
        sortable: true,
        align: 'left',
    },
    {
        name: 'volume',
        label: 'm³',
        field: (row) => dashIfEmpty(row.m3),
        sortable: true,
        align: 'left',
    },
    {
        name: 'km',
        label: t('Km'),
        field: (row) => dashIfEmpty(row?.kmTotal),
        sortable: true,
        align: 'left',
    },
    {
        name: 'price',
        label: t('Price'),
        field: (row) => (row?.price ? toCurrency(row.price) : '-'),
        sortable: true,
        align: 'left',
    },
    {
        name: 'received',
        label: t('Received'),
        field: (row) => row?.invoiceInFk,
        sortable: true,
        align: 'left',
    },
    {
        name: 'autonomous',
        label: t('Autonomous'),
        field: (row) => row?.supplierName,
        sortable: true,
        align: 'left',
    },
    {
        name: 'actions',
        label: '',
        sortable: false,
        align: 'right',
    },
]);

const refreshKey = ref(0);

const total = computed(() => selectedRows.value.reduce((item) => item?.price || 0, 0));

const openDmsUploadDialog = async () => {
    dmsDialog.value.rowsToCreateInvoiceIn = selectedRows.value
        .filter(
            (agencyTerm) => agencyTerm.supplierFk === selectedRows.value?.[0].supplierFk
        )
        .map((agencyTerm) => ({
            routeFk: agencyTerm.routeFk,
            supplierFk: agencyTerm.supplierFk,
            created: agencyTerm.created,
            totalPrice: total.value,
        }));

    if (dmsDialog.value.rowsToCreateInvoiceIn.length !== selectedRows.value.length) {
        dmsDialog.value.rowsToCreateInvoiceIn = [];
        dmsDialog.value.initialForm = null;
        return notify(t('Two autonomous cannot be counted at the same time'), 'negative');
    }

    const dmsType = await axios
        .get('DmsTypes/findOne', {
            filter: {
                where: { code: 'invoiceIn' },
            },
        })
        .then((res) => res.data);

    dmsDialog.value.initialForm = {
        description: selectedRows.value?.[0].supplierName,
        companyFk: user.value.companyFk,
        warehouseFk: user.value.warehouseFk,
        dmsTypeFk: dmsType?.id,
    };
    dmsDialog.value.show = true;
};

const onDmsSaved = async (dms, response) => {
    if (response) {
        await axios.post('AgencyTerms/createInvoiceIn', {
            rows: dmsDialog.value.rowsToCreateInvoiceIn,
            dms: response.data,
        });
    }
    dmsDialog.value.show = false;
    dmsDialog.value.initialForm = null;
    dmsDialog.value.rowsToCreateInvoiceIn = [];
    refreshKey.value++;
};

function navigateToRouteSummary(event, row) {
    router.push({ name: 'RouteSummary', params: { id: row.routeFk } });
}
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                data-key="RouteAutonomousList"
                :label="t('Search autonomous')"
                :info="t('You can search by autonomous reference')"
            />
        </Teleport>
        <Teleport to="#actions-append">
            <div class="row q-gutter-x-sm">
                <QBtn
                    flat
                    @click="stateStore.toggleRightDrawer()"
                    round
                    dense
                    icon="menu"
                >
                    <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">
            <RouteAutonomousFilter data-key="RouteAutonomousList" />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center">
        <div class="route-list">
            <div class="q-pa-md">
                <QCard class="vn-one q-py-sm q-px-lg flex justify-between">
                    <VnLv class="flex">
                        <template #label>
                            <span class="text-h6">{{ t('Total') }}</span>
                        </template>
                        <template #value>
                            <span class="text-h6 q-ml-md">{{ toCurrency(total) }}</span>
                        </template>
                    </VnLv>
                    <QBtn
                        icon="vn:invoice-in-create"
                        color="primary"
                        :disable="!selectedRows?.length"
                        @click="openDmsUploadDialog"
                    >
                        <QTooltip>
                            {{ t('Create invoiceIn') }}
                        </QTooltip>
                    </QBtn>
                </QCard>
            </div>
            <VnPaginate
                :key="refreshKey"
                data-key="RouteAutonomousList"
                url="AgencyTerms/filter"
                :limit="20"
                auto-load
            >
                <template #body="{ rows }">
                    <div class="q-pa-md">
                        <QTable
                            v-model:selected="selectedRows"
                            :columns="columns"
                            :rows="rows"
                            flat
                            row-key="routeFk"
                            selection="multiple"
                            :rows-per-page-options="[0]"
                            hide-pagination
                            @row-click="navigateToRouteSummary"
                        >
                            <template #body-cell-ID="props">
                                <QTd :props="props">
                                    <span class="link" @click.stop>
                                        {{ props.value }}
                                        <RouteDescriptorProxy :id="props.value" />
                                    </span>
                                </QTd>
                            </template>
                            <template #body-cell-received="props">
                                <QTd :props="props">
                                    <span :class="props.value && 'link'" @click.stop>
                                        {{ dashIfEmpty(props.value) }}
                                        <InvoiceInDescriptorProxy
                                            v-if="props.value"
                                            :id="props.value"
                                        />
                                    </span>
                                </QTd>
                            </template>
                            <template #body-cell-autonomous="props">
                                <QTd :props="props">
                                    <span class="link" @click.stop>
                                        {{ props.value }}
                                        <SupplierDescriptorProxy
                                            v-if="props.row?.supplierFk"
                                            :id="props.row?.supplierFk"
                                        />
                                    </span>
                                </QTd>
                            </template>
                            <template #body-cell-actions="props">
                                <QTd :props="props">
                                    <div class="table-actions">
                                        <QIcon
                                            name="preview"
                                            size="sm"
                                            color="primary"
                                            @click.stop="
                                                viewSummary(
                                                    props?.row?.routeFk,
                                                    RouteSummary
                                                )
                                            "
                                        >
                                            <QTooltip>{{ t('Preview') }}</QTooltip>
                                        </QIcon>
                                    </div>
                                </QTd>
                            </template>
                        </QTable>
                    </div>
                </template>
            </VnPaginate>
        </div>
    </QPage>
    <QDialog v-model="dmsDialog.show">
        <VnDms
            url="dms/uploadFile"
            model="AgencyTerms"
            :form-initial-data="dmsDialog.initialForm"
            @on-data-saved="onDmsSaved"
        />
    </QDialog>
</template>

<style lang="scss" scoped>
.route-list {
    width: 100%;
}

.table-actions {
    display: flex;
    align-items: center;
    gap: 12px;

    i {
        cursor: pointer;
    }
}
</style>
<i18n>
es:
    Search autonomous: Buscar autónomos
    You can search by autonomous reference: Puedes buscar por referencia del autónomo
    Create invoiceIn: Crear factura recibida
    Two autonomous cannot be counted at the same time: Dos autonónomos no pueden ser contabilizados al mismo tiempo
    Date: Fecha
    Agency route: Agencia Ruta
    Agency agreement: Agencia Acuerdo
    Packages: Bultos
    Price: Precio
    Received: Recibida
    Autonomous: Autónomos
    Preview: Vista previa
</i18n>
