<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/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';
import { useArrayData } from 'src/composables/useArrayData';

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

const selected = ref([]);
const arrayData = useArrayData('CustomerDefaulter');
const columns = computed(() => [
    {
        align: 'left',
        name: 'clientFk',
        label: t('Client'),
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Clients',
                fields: ['id', 'name'],
            },
        },
    },
    {
        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: 'userFk',
        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',
    },
    {
        align: 'left',
        name: 'isWorker',
        label: t('customer.params.isWorker'),
    },
]);

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

function exprBuilder(param, value) {
    switch (param) {
        case 'creditInsurance':
        case 'countryFk':
            return { [`c.${param}`]: value };
        case 'payMethod':
            return { [`c.payMethodFk`]: value };
        case 'userFk':
            return { [`co.${param}`]: value };
        case 'departmentFk':
            return { [`c.${param}`]: value };
        case 'amount':
        case 'clientFk':
            return { [`d.${param}`]: value };
        case 'created':
            return { 'd.created': { between: dateRange(value) } };
        case 'defaulterSinced':
            return { 'd.defaulterSinced': { between: dateRange(value) } };
        case 'isWorker': {
            if (value == undefined) return;
            const search = value ? 'worker' : { neq: 'worker' };
            return { 'c.businessTypeFk': search };
        }
        case 'hasRecovery': {
            if (value == undefined) return;
            const search = value ? null : { neq: null };
            return { 'r.finished': search };
        }
        case 'observation':
            return { 'co.text': { like: `%${value}%` } };
    }
}
</script>

<template>
    <VnSubToolbar>
        <template #st-data>
            <CustomerBalanceDueTotal :amount="arrayData.store.data?.amount" />
        </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"
        :table="{
            'row-key': 'clientFk',
            selection: 'multiple',
        }"
        v-model:selected="selected"
        :disable-option="{ card: true }"
        auto-load
        :order="['amount DESC']"
        key-data="defaulters"
    >
        <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-departmentFk="{ row }">
            <span class="link" @click.stop>
                {{ row.departmentName }}
                <DepartmentDescriptorProxy :id="row.departmentFk" />
            </span>
        </template>
        <template #column-userFk="{ row }">
            <span class="link" @click.stop>
                {{ row.workerName }}
                <WorkerDescriptorProxy :id="row.userFk" />
            </span>
        </template>
    </VnTable>
</template>
<i18n>
es:
    Add observation:  Añadir observación
    Client: Cliente
    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: Recobro
</i18n>
