<script setup>
import { useStateStore } from 'stores/useStateStore';
import { useI18n } from 'vue-i18n';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { toCurrency, toDate } from 'src/filters';
import { useSummaryDialog } from 'composables/useSummaryDialog';
import { useState } from 'composables/useState';

import useNotify from 'composables/useNotify';
import axios from 'axios';
import RouteSummary from 'pages/Route/Card/RouteSummary.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 VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnDms from 'components/common/VnDms.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import VnLv from 'components/ui/VnLv.vue';

const { viewSummary } = useSummaryDialog();
const { notify } = useNotify();
const { t } = useI18n();

const stateStore = useStateStore();
const refreshKey = ref(0);
const state = useState();
const user = state.getUser();
const dmsDialog = ref({
    show: false,
    initialForm: {},
    rowsToCreateInvoiceIn: [],
});
const selectedRows = ref([]);
const tableRef = ref();
const columns = computed(() => [
    {
        align: 'left',
        name: 'routeFk',
        label: 'Id',
        chip: {
            condition: () => true,
        },
        isId: true,
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'created',
        label: t('Date'),
        columnFilter: false,
        format: ({ created }) => toDate(created),
    },
    {
        align: 'left',
        name: 'agencyModeName',
        label: t('Agency route'),
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'agencyAgreement',
        label: t('Agency agreement'),
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'to',
        label: t('To'),
        visible: false,
        cardVisible: true,
        create: true,
        component: 'date',
        format: ({ date }) => toDate(date),
    },
    {
        align: 'left',
        name: 'from',
        label: t('From'),
        visible: false,
        cardVisible: true,
        create: true,
        component: 'date',
        format: ({ date }) => toDate(date),
    },
    {
        align: 'left',
        name: 'packages',
        label: t('Packages'),
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'm3',
        label: 'm³',
        cardVisible: true,
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'kmTotal',
        label: t('Km'),
        cardVisible: true,
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'price',
        label: t('Price'),
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'invoiceInFk',
        label: t('Received'),
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'supplierName',
        label: t('Autonomous'),
        columnFilter: false,
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('components.smartCard.viewSummary'),
                icon: 'preview',
                isPrimary: true,
                action: (row) => viewSummary(row?.routeFk, RouteSummary),
            },
        ],
    },
]);

const total = computed(() => {
    return selectedRows.value.reduce((sum, item) => sum + item.price, 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++;
};

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

<template>
    <VnSearchbar
        data-key="RouteAutonomousList"
        :label="t('Search autonomous')"
        :info="t('You can search by autonomous reference')"
    />
    <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('globals.createInvoiceIn') }}
                </QTooltip>
            </QBtn>
        </QCard>
    </div>
    <VnTable
        ref="tableRef"
        data-key="RouteAutonomousList"
        url="AgencyTerms/filter"
        :columns="columns"
        :right-search="true"
        default-mode="table"
        v-model:selected="selectedRows"
        table-height="85vh"
        redirect="route"
        :row-click="({ routeFk }) => tableRef.redirect(routeFk)"
        :table="{
            'row-key': '$index',
            selection: 'multiple',
        }"
    >
        <template #column-id="{ row }">
            <span class="link" @click.stop>
                {{ row.routeFk }}
                <RouteDescriptorProxy :id="row.route.id" />
            </span>
        </template>
        <template #column-invoiceInFk="{ row }">
            <span class="link" @click.stop>
                {{ row.invoiceInFk }}
                <InvoiceInDescriptorProxy v-if="row.invoiceInFk" :id="row.invoiceInFk" />
            </span>
        </template>
        <template #column-supplierName="{ row }">
            <span class="link" @click.stop>
                {{ row.supplierName }}
                <SupplierDescriptorProxy :id="row.supplierFk" />
            </span>
        </template>
    </VnTable>
    <QDialog v-model="dmsDialog.show">
        <VnDms
            url="dms/uploadFile"
            model="AgencyTerms"
            :form-initial-data="dmsDialog.initialForm"
            @on-data-saved="onDmsSaved"
        />
    </QDialog>
</template>
<i18n>
es:
    Search autonomous: Buscar autónomos
    You can search by autonomous reference: Puedes buscar por referencia del autónomo
    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>
