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

import { QBtn, QCheckbox, useQuasar } from 'quasar';

import { toCurrency, toDate } from 'filters/index';
import { useArrayData } from 'composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';

import CustomerNotificationsFilter from './CustomerDefaulterFilter.vue';
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 CustomerDefaulterAddObservation from './CustomerDefaulterAddObservation.vue';

const { t } = useI18n();
const stateStore = useStateStore();
const quasar = useQuasar();

const arrayData = ref(null);
const balanceDueTotal = ref(0);
const customerId = ref(0);
const selected = ref([]);
const workerId = ref(0);

const rows = computed(() => arrayData.value.store.data);

const tableColumnComponents = {
    client: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: ({ row }) => selectCustomerId(row.clientFk),
    },
    isWorker: {
        component: QCheckbox,
        props: ({ row }) => ({
            disable: true,
            'model-value': Boolean(row.selected),
        }),
    },
    salesperson: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: ({ row }) => selectWorkerId(row.salesPersonFk),
    },
    country: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    paymentMethod: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    balance: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    author: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: ({ row }) => selectWorkerId(row.workerFk),
    },
    lastObservation: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    date: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    credit: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    from: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: 'clientName',
        label: t('Client'),
        name: 'client',
    },
    {
        align: 'left',
        field: 'isWorker',
        label: t('Is worker'),
        name: 'isWorker',
    },
    {
        align: 'left',
        field: 'salesPersonName',
        label: t('Salesperson'),
        name: 'salesperson',
    },
    {
        align: 'left',
        field: 'country',
        label: t('Country'),
        name: 'country',
    },
    {
        align: 'left',
        field: 'payMethod',
        label: t('P. Method'),
        name: 'paymentMethod',
    },
    {
        align: 'left',
        field: ({ amount }) => toCurrency(amount),
        label: t('Balance D.'),
        name: 'balance',
    },
    {
        align: 'left',
        field: 'workerName',
        label: t('Author'),
        name: 'author',
    },
    {
        align: 'left',
        field: 'observation',
        label: t('Last observation'),
        name: 'lastObservation',
    },
    {
        align: 'left',
        field: ({ created }) => toDate(created),
        label: t('L. O. Date'),
        name: 'date',
    },
    {
        align: 'left',
        field: ({ creditInsurance }) => toCurrency(creditInsurance),
        label: t('Credit I.'),
        name: 'credit',
    },
    {
        align: 'left',
        field: ({ defaulterSinced }) => toDate(defaulterSinced),
        label: t('From'),
        name: 'from',
    },
]);

onBeforeMount(() => {
    getArrayData();
});

const getArrayData = async () => {
    arrayData.value = useArrayData('CustomerDefaulter', {
        url: 'Defaulters/filter',
        limit: 0,
    });
    await arrayData.value.fetch({ append: false });
    balanceDueTotal.value = arrayData.value.store.data.reduce(
        (accumulator, currentValue) => {
            return accumulator + (currentValue['amount'] || 0);
        },
        0
    );
    stateStore.rightDrawer = true;
};

const selectCustomerId = (id) => {
    workerId.value = 0;
    customerId.value = id;
};

const selectWorkerId = (id) => {
    customerId.value = 0;
    workerId.value = id;
};

const viewAddObservation = (rowsSelected) => {
    quasar.dialog({
        component: CustomerDefaulterAddObservation,
        componentProps: {
            clients: rowsSelected,
            promise: refreshData,
        },
    });
};

const refreshData = () => {
    getArrayData();
};
</script>

<template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <CustomerNotificationsFilter data-key="CustomerDefaulter" />
        </QScrollArea>
    </QDrawer>

    <VnSubToolbar class="bg-vn-dark">
        <template #st-data>
            <CustomerBalanceDueTotal :amount="balanceDueTotal" />
            <div class="flex items-center q-ml-lg">
                <QBtn
                    color="primary"
                    icon="vn:notes"
                    :disabled="!selected.length"
                    @click.stop="viewAddObservation(selected)"
                />
            </div>
        </template>
    </VnSubToolbar>

    <QPage class="column items-center q-pa-md">
        <QTable
            :columns="columns"
            :pagination="{ rowsPerPage: 0 }"
            :rows="rows"
            class="full-width q-mt-md"
            hide-bottom
            row-key="clientFk"
            selection="multiple"
            v-model:selected="selected"
        >
            <template #body-cell="props">
                <QTd :props="props">
                    <QTr :props="props" class="cursor-pointer">
                        <component
                            :is="tableColumnComponents[props.col.name].component"
                            class="col-content"
                            v-bind="tableColumnComponents[props.col.name].props(props)"
                            @click="tableColumnComponents[props.col.name].event(props)"
                        >
                            {{ props.value }}

                            <WorkerDescriptorProxy v-if="workerId" :id="workerId" />
                            <CustomerDescriptorProxy v-else :id="customerId" />
                        </component>
                    </QTr>
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>

<style lang="scss" scoped>
.col-content {
    border-radius: 4px;
    padding: 6px;
}
</style>

<i18n>
es:
    Client: Cliente
    Is worker: Es trabajador
    Salesperson: Comercial
    Country: País
    P. Method: F. Pago
    Balance D.: Saldo V.
    Author: Autor
    Last observation: Última observación
    L. O. Date: Fecha Ú. O.
    Credit I.: Crédito A.
    From: Desde
</i18n>
