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

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

import { toCurrency } from 'src/filters';
import { useStateStore } from 'stores/useStateStore';

import FetchData from 'components/FetchData.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';
import CustomerNewPayment from 'src/pages/Customer/components/CustomerNewPayment.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';

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

const clientRisks = ref(null);
const companiesOptions = ref([]);
const companyId = ref(442);
const rows = ref(null);
const workerId = ref(0);
const receiptsRef = ref(null);
const clientRisksRef = ref(null);

const filterCompanies = { order: ['code'] };
const params = {
    clientId: `${route.params.id}`,
    companyId: companyId.value,
    filter: { limit: 20 },
};
const filter = {
    include: { relation: 'company', scope: { fields: ['code'] } },
    where: { clientFk: `${route.params.id}`, companyFk: companyId.value },
};

const tableColumnComponents = {
    payed: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    created: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    userName: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => {
            workerId.value = prop.row.clientFk;
        },
    },
    description: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    bankFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    debit: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    credit: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    balance: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    isConciliate: {
        component: QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: 'payed',
        format: (value) => date.formatDate(value, 'DD/MM/YYYY'),
        label: t('Date'),
        name: 'payed',
    },
    {
        align: 'left',
        field: 'created',
        format: (value) => date.formatDate(value, 'DD/MM/YYYY hh:mm'),
        label: t('Creation date'),
        name: 'created',
    },
    {
        align: 'left',
        field: 'userName',
        label: t('Employee'),
        name: 'userName',
    },
    {
        align: 'left',
        field: 'description',
        label: t('Reference'),
        name: 'description',
    },
    {
        align: 'left',
        field: 'bankFk',
        label: t('Bank'),
        name: 'bankFk',
    },
    {
        align: 'left',
        field: 'debit',
        label: t('Debit'),
        name: 'debit',
    },
    {
        align: 'left',
        field: 'credit',
        format: (value) => toCurrency(value),
        label: t('Havings'),
        name: 'credit',
    },
    {
        align: 'left',
        field: (value) => value.debit - value.credit,
        format: (value) => toCurrency(value),
        label: t('Balance'),
        name: 'balance',
    },
    {
        align: 'left',
        field: 'isConciliate',
        label: t('Conciliated'),
        name: 'isConciliate',
    },
]);

const getData = () => {
    stateStore.rightDrawer = true;
    receiptsRef.value?.fetch();
    clientRisksRef.value?.fetch();
};

const showNewPaymentDialog = () => {
    quasar.dialog({
        component: CustomerNewPayment,
        componentProps: {
            companyId: companyId.value,
            totalCredit: clientRisks.value[0]?.amount,
            promise: getData,
        },
    });
};

const updateCompanyId = (id) => {
    if (id) companyId.value = id;
    getData();
};
</script>

<template>
    <FetchData
        :filter="filterCompanies"
        @on-fetch="(data) => (companiesOptions = data)"
        auto-load
        url="Companies"
    />
    <FetchData
        :params="params"
        @on-fetch="(data) => (rows = data)"
        auto-load
        ref="receiptsRef"
        url="Receipts/filter"
    />
    <FetchData
        :filter="filter"
        @on-fetch="(data) => (clientRisks = data)"
        auto-load
        ref="clientRisksRef"
        url="ClientRisks"
    />

    <QTable
        :columns="columns"
        :pagination="{ rowsPerPage: 12 }"
        :rows="rows"
        class="full-width q-mt-md"
        row-key="id"
        v-if="rows?.length"
    >
        <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)"
                    >
                        <template v-if="props.col.name !== 'isConciliate'">
                            {{ props.value }}
                        </template>
                        <WorkerDescriptorProxy :id="workerId" />
                    </component>
                </QTr>
            </QTd>
        </template>
    </QTable>

    <h5 class="flex justify-center label-color" v-else>
        {{ t('globals.noResults') }}
    </h5>

    <QDrawer :width="256" show-if-above side="right" v-model="stateStore.rightDrawer">
        <div class="q-mt-xl q-px-md">
            <VnSelectFilter
                :label="t('Company')"
                :options="companiesOptions"
                @update:model-value="updateCompanyId($event)"
                hide-selected
                option-label="code"
                option-value="id"
                v-model="companyId"
            />
        </div>

        <QCard class="q-ma-md q-pa-md q-mt-lg" v-if="rows?.length">
            <QCardSection>
                <div class="flex justify-center text-subtitle1 text-bold">
                    {{ t('Total by company') }}
                </div>
                <div class="flex justify-center">
                    <div class="q-mr-sm" v-if="clientRisks?.length">
                        {{ clientRisks[0].company.code }}:
                    </div>
                    <div v-if="clientRisks?.length">
                        {{ toCurrency(clientRisks[0].amount) }}
                    </div>
                </div>
            </QCardSection>
        </QCard>
    </QDrawer>

    <QPageSticky :offset="[18, 18]">
        <QBtn @click.stop="showNewPaymentDialog()" color="primary" fab icon="add" />
        <QTooltip>
            {{ t('New payment') }}
        </QTooltip>
    </QPageSticky>
</template>

<i18n>
es:
    Company: Empresa
    Total by company: Total por empresa
    New payment: Añadir pago
    Date: Fecha
    Creation date: Fecha de creación
    Employee: Empleado
    Reference: Referencia
    Bank: Caja
    Debit: Debe
    Havings: Haber
    Balance: Balance
    Conciliated: Conciliado
</i18n>
