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

import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import InvoiceOutNegativeFilter from './InvoiceOutNegativeBasesFilter.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

import { toCurrency } from 'src/filters';
import { useInvoiceOutGlobalStore } from 'src/stores/invoiceOutGlobal.js';
import { useStateStore } from 'stores/useStateStore';
import { useArrayData } from 'composables/useArrayData';
import VnUserLink from 'src/components/ui/VnUserLink.vue';

const invoiceOutGlobalStore = useInvoiceOutGlobalStore();
const stateStore = useStateStore();
const { t } = useI18n();

const arrayData = ref(null);

function exprBuilder(param, value) {
    switch (param) {
        case 'from':
        case 'to':
            return;
        default:
            return { [param]: value };
    }
}

onBeforeMount(async () => {
    const defaultParams = {
        from: Date.vnFirstDayOfMonth().toISOString(),
        to: Date.vnLastDayOfMonth().toISOString(),
    };
    arrayData.value = useArrayData('InvoiceOutNegative', {
        url: 'InvoiceOuts/negativeBases',
        limit: 0,
        userParams: defaultParams,
        exprBuilder: exprBuilder,
    });
    await arrayData.value.fetch({ append: false });

    stateStore.rightDrawer = true;
});

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

const selectedCustomerId = ref(0);
const selectedWorkerId = ref(0);

const tableColumnComponents = {
    company: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    country: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    clientId: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => selectCustomerId(prop.value),
    },
    client: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    amount: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    base: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    ticketId: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    active: {
        component: QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
        event: () => {},
    },
    hasToInvoice: {
        component: QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
        event: () => {},
    },
    verifiedData: {
        component: QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
        event: () => {},
    },
    comercial: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => selectWorkerId(prop.row.comercialId),
    },
};

const columns = computed(() => [
    {
        label: t('invoiceOut.negativeBases.company'),
        field: 'company',
        name: 'company',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.country'),
        field: 'country',
        name: 'country',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.clientId'),
        field: 'clientId',
        name: 'clientId',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.client'),
        field: 'clientSocialName',
        name: 'client',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.amount'),
        field: 'amount',
        name: 'amount',
        align: 'left',
        format: (value) => toCurrency(value),
    },
    {
        label: t('invoiceOut.negativeBases.base'),
        field: 'taxableBase',
        name: 'base',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.ticketId'),
        field: 'ticketFk',
        name: 'ticketId',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.active'),
        field: 'isActive',
        name: 'active',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.hasToInvoice'),
        field: 'hasToInvoice',
        name: 'hasToInvoice',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.verifiedData'),
        field: 'isTaxDataChecked',
        name: 'verifiedData',
        align: 'left',
    },
    {
        label: t('invoiceOut.negativeBases.comercial'),
        field: 'comercialName',
        name: 'comercial',
        align: 'left',
    },
]);

const downloadCSV = async () => {
    const params = {}; // filter.value;
    const filterParams = {
        limit: 20,
        where: {
            and: [],
        },
    };
    for (const param in params) {
        if (params[param]) filterParams.where.and.push({ [param]: params[param] });
    }

    await invoiceOutGlobalStore.getNegativeBasesCsv(
        arrayData.value.store.userParams.from,
        arrayData.value.store.userParams.to,
        params
    );
};

const selectCustomerId = (id) => {
    selectedCustomerId.value = id;
};

const selectWorkerId = (id) => {
    selectedWorkerId.value = id;
};
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#st-actions" v-if="stateStore?.isSubToolbarShown()">
            <QBtn color="primary" icon-right="archive" no-caps @click="downloadCSV()" />
        </Teleport>
    </template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <InvoiceOutNegativeFilter data-key="InvoiceOutNegative" />
        </QScrollArea>
    </QDrawer>
    <VnSubToolbar />
    <QPage class="column items-center q-pa-md">
        <QTable
            :columns="columns"
            :rows="rows"
            hide-bottom
            row-key="clientId"
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
        >
            <template #body-cell="props">
                <QTd :props="props">
                    <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 !== 'active' &&
                                props.col.name !== 'hasToInvoice' &&
                                props.col.name !== 'verifiedData'
                            "
                            >{{ props.value }}
                        </template>
                        <CustomerDescriptorProxy
                            v-if="props.col.name === 'clientId'"
                            :id="selectedCustomerId"
                        />
                        <VnUserLink
                            v-if="props.col.name === 'comercial'"
                            :worker-id="selectedWorkerId"
                        />
                    </component>
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>

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

<i18n></i18n>
