<script setup>
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { toCurrency, toDate, dateRange } from 'filters/index';
import CustomerBalanceDueTotal from './CustomerBalanceDueTotal.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnInput from 'src/components/common/VnInput.vue';
import CustomerDefaulterAddObservation from './CustomerDefaulterAddObservation.vue';
import DepartmentDescriptorProxy from 'src/pages/Department/Card/DepartmentDescriptorProxy.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';

const { t } = useI18n();
const quasar = useQuasar();
const dataRef = ref(null);

const balanceDueTotal = ref(0);
const selected = ref([]);

const columns = computed(() => [
    {
        align: 'left',
        name: 'clientFk',
        label: t('Client'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Clients',
                fields: ['id', 'name'],
            },
        },
    },
    {
        align: 'left',
        name: 'isWorker',
        label: t('Is worker'),
    },
    {
        align: 'left',
        name: 'salesPersonFk',
        label: t('Salesperson'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Workers/activeWithInheritedRole',
                fields: ['id', 'name'],
                where: { role: 'salesPerson' },
                useLike: false,
                optionValue: 'id',
                optionLabel: 'name',
                optionFilter: 'firstName',
            },
        },
    },
    {
        align: 'left',
        name: 'departmentFk',
        label: t('Department'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Departments',
                fields: ['id', 'name'],
            },
        },
    },
    {
        align: 'left',
        name: 'countryFk',
        label: t('Country'),
        format: ({ country }) => country,
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Countries',
                fields: ['id', 'name'],
            },
        },
    },
    {
        align: 'left',
        name: 'payMethod',
        label: t('P. Method'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Paymethods',
            },
        },
    },
    {
        align: 'left',
        name: 'amount',
        label: t('Balance D.'),
        format: ({ amount }) => toCurrency(amount),
    },
    {
        align: 'left',
        name: 'workerFk',
        label: t('Author'),
        tooltip: t('Worker who made the last observation'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Workers/activeWithInheritedRole',
                fields: ['id', 'name'],
                useLike: false,
                optionValue: 'id',
                optionLabel: 'name',
                optionFilter: 'firstName',
            },
        },
    },
    {
        align: 'left',
        name: 'observation',
        label: t('Last observation'),
        columnClass: 'expand',
    },
    {
        align: 'left',
        name: 'created',
        label: t('L. O. Date'),
        format: ({ created }) => toDate(created),
        tooltip: t('Last observation date'),
        columnFilter: {
            component: 'date',
        },
    },
    {
        align: 'left',
        name: 'creditInsurance',
        format: ({ creditInsurance }) => toCurrency(creditInsurance),
        label: t('Credit I.'),
        tooltip: t('Credit insurance'),
        columnFilter: {
            component: 'number',
        },
    },
    {
        align: 'left',
        name: 'defaulterSinced',
        format: ({ defaulterSinced }) => toDate(defaulterSinced),
        label: t('From'),
        columnFilter: {
            component: 'date',
        },
    },
    {
        align: 'left',
        label: t('Has recovery'),
        name: 'hasRecovery',
    },
]);

const viewAddObservation = (rowsSelected) => {
    quasar.dialog({
        component: CustomerDefaulterAddObservation,
        componentProps: {
            clients: rowsSelected,
            promise: async () => await dataRef.value.reload(),
        },
    });
};

const onFetch = async (data) => {
    balanceDueTotal.value = data.reduce((acc, { amount = 0 }) => acc + amount, 0);
};

function exprBuilder(param, value) {
    switch (param) {
        case 'clientFk':
            return { [`d.${param}`]: value };
        case 'creditInsurance':
        case 'amount':
        case 'workerFk':
        case 'departmentFk':
        case 'countryFk':
        case 'payMethod':
        case 'salesPersonFk':
            return { [`d.${param}`]: value };
        case 'created':
            return { 'd.created': { between: dateRange(value) } };
        case 'defaulterSinced':
            return { 'd.defaulterSinced': { between: dateRange(value) } };
    }
}
</script>

<template>
    <VnSubToolbar>
        <template #st-data>
            <CustomerBalanceDueTotal :amount="balanceDueTotal" />
        </template>
        <template #st-actions>
            <QBtn
                color="primary"
                icon="vn:notes"
                :disabled="!selected.length"
                @click.stop="viewAddObservation(selected)"
            >
                <QTooltip>{{ t('Add observation') }}</QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <VnTable
        ref="dataRef"
        data-key="CustomerDefaulter"
        url="Defaulters/filter"
        :expr-builder="exprBuilder"
        :columns="columns"
        @on-fetch="onFetch"
        :use-model="true"
        :table="{
            'row-key': 'clientFk',
            selection: 'multiple',
        }"
        v-model:selected="selected"
        :disable-option="{ card: true }"
        auto-load
        :order="['amount DESC']"
    >
        <template #column-clientFk="{ row }">
            <span class="link" @click.stop>
                {{ row.clientName }}
                <CustomerDescriptorProxy :id="row.clientFk" />
            </span>
        </template>
        <template #column-observation="{ row }">
            <VnInput type="textarea" v-model="row.observation" readonly dense rows="2" />
        </template>
        <template #column-salesPersonFk="{ row }">
            <span class="link" @click.stop>
                {{ row.salesPersonName }}
                <WorkerDescriptorProxy :id="row.salesPersonFk" />
            </span>
        </template>
        <template #column-departmentFk="{ row }">
            <span class="link" @click.stop>
                {{ row.departmentName }}
                <DepartmentDescriptorProxy :id="row.departmentFk" />
            </span>
        </template>
        <template #column-workerFk="{ row }">
            <span class="link" @click.stop>
                {{ row.workerName }}
                <WorkerDescriptorProxy :id="row.workerFk" />
            </span>
        </template>
    </VnTable>
</template>
<i18n>
es:
    Add observation:  Añadir observación
    Client: Cliente
    Is worker: Es trabajador
    Salesperson: Comercial
    Department: Departamento
    Country: País
    P. Method: F. Pago
    Pay method: Forma de pago
    Balance D.: Saldo V.
    Balance due: Saldo vencido
    Author: Autor
    Worker who made the last observation: Trabajador que ha realizado la última observación
    Last observation: Última observación
    L. O. Date: Fecha Ú. O.
    Last observation date: Fecha última observación
    Credit I.: Crédito A.
    Credit insurance: Crédito asegurado
    From: Desde
    Has recovery: Tiene recobro
</i18n>
