<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';

import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue';

import { toDateString } from 'src/filters';
import useCardDescription from 'src/composables/useCardDescription';
import { getUrl } from 'src/composables/getUrl';
import { useState } from 'src/composables/useState';

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const route = useRoute();
const { t } = useI18n();
const url = ref();
const state = useState();

const filter = {
    fields: [
        'id',
        'name',
        'nickname',
        'nif',
        'payMethodFk',
        'payDemFk',
        'payDay',
        'isActive',
        'isSerious',
        'isTrucker',
        'account',
    ],
    include: [
        {
            relation: 'payMethod',
            scope: {
                fields: ['id', 'name'],
            },
        },
        {
            relation: 'payDem',
            scope: {
                fields: ['id', 'payDem'],
            },
        },
        {
            relation: 'client',
            scope: {
                fields: ['id', 'fi'],
            },
        },
    ],
};

onMounted(async () => {
    url.value = await getUrl('');
});

const entityId = computed(() => {
    return $props.id || route.params.id;
});

const data = ref(useCardDescription());
const setData = (entity) => {
    data.value = useCardDescription(entity.ref, entity.id);
};

const supplier = computed(() => state.get('supplier'));

const getEntryQueryParams = (supplier) => {
    if (!supplier) return null;

    const date = Date.vnNew();
    date.setHours(0, 0, 0, 0);

    const from = new Date(date.getTime());
    from.setDate(from.getDate() - 10);

    const to = new Date(date.getTime());
    to.setDate(to.getDate() + 10);

    const params = {
        supplierFk: supplier.id,
        from: toDateString(from),
        to: toDateString(to),
    };

    return params;
};
</script>

<template>
    <CardDescriptor
        module="Supplier"
        :url="`Suppliers/${entityId}`"
        :title="data.title"
        :subtitle="data.subtitle"
        :filter="filter"
        @on-fetch="setData"
        data-key="supplier"
    >
        <template #header-extra-action>
            <QBtn
                round
                flat
                dense
                size="md"
                icon="vn:supplier"
                color="white"
                class="link"
                :to="{ name: 'SupplierList' }"
            >
                <QTooltip>
                    {{ t('Go to module index') }}
                </QTooltip>
            </QBtn>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('supplier.summary.taxNumber')" :value="entity.nif" />
            <VnLv label="Alias" :value="entity.nickname" />
            <VnLv
                :label="t('supplier.summary.payMethod')"
                :value="entity?.payMethod?.name"
            />
            <VnLv
                :label="t('supplier.summary.payDeadline')"
                :value="entity?.payDem?.payDem"
            />
            <VnLv :label="t('supplier.summary.payDay')" :value="entity.payDay" />
            <VnLv :label="t('supplier.summary.account')" :value="entity.account" />
        </template>
        <template #icons>
            <QCardActions v-if="supplier" class="q-gutter-x-md">
                <QIcon
                    v-if="!supplier.isActive"
                    name="vn:disabled"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Inactive supplier') }}</QTooltip>
                </QIcon>
                <QIcon
                    v-if="!supplier.isSerious"
                    name="vn:supplierfalse"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Unverified supplier') }}</QTooltip>
                </QIcon>
            </QCardActions>
        </template>
        <template #actions="{ entity }">
            <QCardActions>
                <QBtn
                    :to="{
                        name: 'EntryList',
                        query: { params: JSON.stringify(getEntryQueryParams(entity)) },
                    }"
                    size="md"
                    icon="vn:entry"
                    color="primary"
                >
                    <QTooltip>{{ t('All entries with current supplier') }}</QTooltip>
                </QBtn>
                <QBtn
                    v-if="entity.client?.fi"
                    :to="{
                        name: 'CustomerCard',
                        params: { id: entity.client?.id },
                    }"
                    size="md"
                    icon="vn:Person"
                    color="primary"
                >
                    <QTooltip>{{ t('Go to client') }}</QTooltip>
                </QBtn>
                <QBtn
                    :href="`${url}invoice-in/create?supplierFk=${entity.id}`"
                    size="md"
                    icon="vn:invoice-in-create"
                    color="primary"
                >
                    <QTooltip>{{ t('Create invoiceIn') }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </CardDescriptor>
</template>

<i18n>
es:
    All entries with current supplier: Todas las entradas con proveedor actual
    Go to client: Ir a cliente
    Create invoiceIn: Crear factura recibida
    Go to module index: Ir al índice del módulo
    Inactive supplier: Proveedor inactivo
    Unverified supplier: Proveedor no verificado
</i18n>
