<script setup>
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { downloadFile } from 'src/composables/downloadFile';
import FormModel from 'components/FormModel.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import FetchData from 'src/components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnDms from 'src/components/common/VnDms.vue';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
import axios from 'axios';

const { t } = useI18n();

const route = useRoute();
const quasar = useQuasar();
const editDownloadDisabled = ref(false);
const userConfig = ref(null);
const invoiceId = computed(() => +route.params.id);

const expenses = ref([]);
const currencies = ref([]);
const currenciesRef = ref();
const companies = ref([]);
const companiesRef = ref();
const dmsTypes = ref([]);
const dmsTypesRef = ref();
const warehouses = ref([]);
const warehousesRef = ref();
const allowTypesRef = ref();
const allowedContentTypes = ref([]);
const sageWithholdings = ref([]);
const documentDialogRef = ref({});
const invoiceInRef = ref({});

function deleteFile(dmsFk) {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                title: t('globals.confirmDeletion'),
                message: t('globals.confirmDeletionMessage'),
            },
        })
        .onOk(async () => {
            await axios.post(`dms/${dmsFk}/removeFile`);
            invoiceInRef.value.formData.dmsFk = null;
            invoiceInRef.value.formData.dms = undefined;
            invoiceInRef.value.hasChanges = true;
            invoiceInRef.value.save();
        });
}
</script>
<template>
    <FetchData
        ref="currenciesRef"
        url="Currencies"
        :filter="{ fields: ['id', 'code'] }"
        sort-by="code"
        @on-fetch="(data) => (currencies = data)"
        auto-load
    />
    <FetchData
        ref="companiesRef"
        url="Companies"
        :filter="{ fields: ['id', 'code'] }"
        sort-by="code"
        @on-fetch="(data) => (companies = data)"
        auto-load
    />
    <FetchData
        ref="dmsTypesRef"
        url="DmsTypes"
        :filter="{ fields: ['id', 'name'] }"
        sort-by="name"
        @on-fetch="(data) => (dmsTypes = data)"
        auto-load
    />
    <FetchData
        ref="warehousesRef"
        url="Warehouses"
        :filter="{ fields: ['id', 'name'] }"
        sort-by="name"
        @on-fetch="(data) => (warehouses = data)"
        auto-load
    />
    <FetchData
        ref="allowTypesRef"
        url="DmsContainers/allowedContentTypes"
        @on-fetch="(data) => (allowedContentTypes = data)"
        auto-load
    />
    <FetchData
        url="UserConfigs/getUserConfig"
        @on-fetch="(data) => (userConfig = data)"
        auto-load
    />
    <FetchData url="Expenses" auto-load @on-fetch="(data) => (expenses = data)" />
    <FetchData
        url="SageWithholdings"
        auto-load
        @on-fetch="(data) => (sageWithholdings = data)"
    />
    <FormModel
        ref="invoiceInRef"
        model="InvoiceIn"
        :go-to="`/invoice-in/${invoiceId}/vat`"
        :url-update="`InvoiceIns/${invoiceId}/updateInvoiceIn`"
        @on-fetch="(data) => (documentDialogRef.supplierName = data.supplier.nickname)"
        auto-load
    >
        <template #form="{ data }">
            <VnRow>
                <VnSelect
                    :required="true"
                    :label="t('supplierFk')"
                    v-model="data.supplierFk"
                    option-value="id"
                    option-label="nickname"
                    url="Suppliers"
                    :fields="['id', 'nickname']"
                    sort-by="nickname"
                    :is-clearable="false"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel>{{
                                    `${scope.opt.id} - ${scope.opt.nickname}`
                                }}</QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
                <VnInput
                    clearable
                    clear-icon="close"
                    :label="t('Supplier ref')"
                    v-model="data.supplierRef"
                />
            </VnRow>
            <VnRow>
                <VnInputDate :label="t('Expedition date')" v-model="data.issued" />
                <VnInputDate
                    :label="t('Operation date')"
                    v-model="data.operated"
                    autofocus
                />
            </VnRow>
            <VnRow>
                <VnInputDate :label="t('Entry date')" v-model="data.bookEntried" />
                <VnInputDate :label="t('Accounted date')" v-model="data.booked" />
            </VnRow>
            <VnRow>
                <VnSelect
                    :label="t('Undeductible VAT')"
                    v-model="data.deductibleExpenseFk"
                    :options="expenses"
                    option-value="id"
                    option-label="id"
                    :filter-options="['id', 'name']"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            {{ `${scope.opt.id}: ${scope.opt.name}` }}
                        </QItem>
                    </template>
                </VnSelect>

                <div class="row no-wrap">
                    <VnInput
                        :label="t('Document')"
                        v-model="data.dmsFk"
                        clearable
                        clear-icon="close"
                        class="full-width"
                        :disable="true"
                    />
                    <div
                        v-if="data.dmsFk"
                        class="row no-wrap q-pa-xs q-gutter-x-xs"
                        data-cy="dms-buttons"
                    >
                        <QBtn
                            :class="{
                                'no-pointer-events': editDownloadDisabled,
                            }"
                            :disable="editDownloadDisabled"
                            icon="cloud_download"
                            :title="t('Download file')"
                            padding="xs"
                            round
                            @click="downloadFile(data.dmsFk)"
                        />
                        <QBtn
                            :class="{
                                'no-pointer-events': editDownloadDisabled,
                            }"
                            :disable="editDownloadDisabled"
                            icon="edit"
                            round
                            padding="xs"
                            @click="
                                () => {
                                    documentDialogRef.show = true;
                                    documentDialogRef.dms = data.dms;
                                }
                            "
                        >
                            <QTooltip>{{ t('Edit document') }}</QTooltip>
                        </QBtn>
                        <QBtn
                            :class="{
                                'no-pointer-events': editDownloadDisabled,
                            }"
                            :disable="editDownloadDisabled"
                            icon="delete"
                            :title="t('Delete file')"
                            padding="xs"
                            round
                            @click="deleteFile(data.dmsFk)"
                        />
                    </div>
                    <QBtn
                        v-else
                        icon="add_circle"
                        round
                        shortcut="+"
                        padding="xs"
                        @click="
                            () => {
                                documentDialogRef.show = true;
                                delete documentDialogRef.dms;
                            }
                        "
                        data-cy="dms-create"
                    >
                        <QTooltip>{{ t('Create document') }}</QTooltip>
                    </QBtn>
                </div>
            </VnRow>
            <VnRow>
                <VnSelect
                    :required="true"
                    :is-clearable="false"
                    :label="t('Currency')"
                    v-model="data.currencyFk"
                    :options="currencies"
                    option-value="id"
                    option-label="code"
                    sort-by="id"
                />

                <VnSelect
                    :required="true"
                    :is-clearable="false"
                    v-if="companiesRef"
                    :label="t('Company')"
                    v-model="data.companyFk"
                    :options="companies"
                    option-value="id"
                    option-label="code"
                />
            </VnRow>
            <VnRow>
                <VnSelect
                    :label="t('InvoiceIn.summary.sage')"
                    v-model="data.withholdingSageFk"
                    :options="sageWithholdings"
                    option-value="id"
                    option-label="withholding"
                />
            </VnRow>
        </template>
    </FormModel>
    <QDialog v-model="documentDialogRef.show">
        <VnDms
            model="dms"
            default-dms-code="invoiceIn"
            :form-initial-data="documentDialogRef.dms"
            :url="
                documentDialogRef.dms
                    ? `Dms/${documentDialogRef.dms.id}/updateFile`
                    : 'Dms/uploadFile'
            "
            :description="documentDialogRef.supplierName"
            @on-data-saved="
                (_, { data }) => {
                    let dmsData = data;
                    if (Array.isArray(data)) dmsData = data[0];
                    invoiceInRef.formData.dmsFk = dmsData.id;
                    invoiceInRef.formData.dms = dmsData;
                    invoiceInRef.hasChanges = true;
                    invoiceInRef.save();
                }
            "
        />
    </QDialog>
</template>
<style lang="scss" scoped>
@media (max-width: $breakpoint-xs) {
    .column {
        .row:not(:last-child) {
            flex-direction: column;
        }
    }
    .q-dialog {
        .q-card {
            &__section:not(:first-child) {
                .q-item {
                    flex-direction: column;
                }
            }
        }
    }
}
</style>
<i18n>
    en:
        supplierFk: Supplier
    es:
        supplierFk: Proveedor
        Supplier ref: Ref. proveedor
        Expedition date: Fecha expedición
        Operation date: Fecha operación
        Undeductible VAT: Iva no deducible
        Document: Documento
        Download file: Descargar archivo
        Entry date: Fecha asiento
        Accounted date: Fecha contable
        Currency: Moneda
        Company: Empresa
        Edit document: Editar documento
        Reference: Referencia
        Type: Tipo
        Description: Descripción
        Generate identifier for original file: Generar identificador para archivo original
        File: Fichero
        Create document: Crear documento
        Allowed content types: Tipos de archivo permitidos
        The company can't be empty: La empresa no puede estar vacía
        The warehouse can't be empty: El almacén no puede estar vacío
        The DMS Type can't be empty: El dms no puede estar vacío
        The description can't be empty: La descripción no puede estar vacía
        The files can't be empty: Los archivos no pueden estar vacíos
</i18n>
