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

import { QBtn, QIcon } from 'quasar';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import CustomerExtendedListActions from './CustomerExtendedListActions.vue';
import CustomerExtendedListFilter from './CustomerExtendedListFilter.vue';
import TableVisibleColumns from 'src/components/common/TableVisibleColumns.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

import { useArrayData } from 'composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';
import { toDate } from 'src/filters';

const { t } = useI18n();
const router = useRouter();
const stateStore = useStateStore();

const arrayData = ref(null);

onBeforeMount(async () => {
    arrayData.value = useArrayData('CustomerExtendedList', {
        url: 'Clients/extendedListFilter',
        limit: 0,
    });
    await arrayData.value.fetch({ append: false });
    stateStore.rightDrawer = true;
});

onMounted(() => {
    const filteredColumns = columns.value.filter(
        (col) => col.name !== 'actions' && col.name !== 'customerStatus'
    );
    allColumnNames.value = filteredColumns.map((col) => col.name);
});

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

const selectedCustomerId = ref(0);
const selectedSalesPersonId = ref(0);
const allColumnNames = ref([]);
const visibleColumns = ref([]);

const tableColumnComponents = {
    customerStatus: {
        component: QIcon,
        props: (prop) => ({
            name: !prop.row.isActive
                ? 'vn:disabled'
                : prop.row.isActive && prop.row.isFreezed
                ? 'vn:frozen'
                : '',
            color: 'primary',
            size: 'sm',
        }),
        event: () => {},
    },
    id: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => {
            selectCustomerId(prop.row.id);
        },
    },
    name: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    fi: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    salesPersonFk: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => selectSalesPersonId(prop.row.salesPersonFk),
    },
    credit: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    creditInsurance: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    phone: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    mobile: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    street: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    countryFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    provinceFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    city: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    postcode: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    email: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    created: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    businessTypeFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    payMethodFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    sageTaxTypeFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    sageTransactionTypeFk: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    isActive: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isActive ? 'check' : 'close',
            color: prop.row.isActive ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    isVies: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isVies ? 'check' : 'close',
            color: prop.row.isVies ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    isTaxDataChecked: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isTaxDataChecked ? 'check' : 'close',
            color: prop.row.isTaxDataChecked ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    isEqualizated: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isEqualizated ? 'check' : 'close',
            color: prop.row.isEqualizated ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    isFreezed: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isFreezed ? 'check' : 'close',
            color: prop.row.isFreezed ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    hasToInvoice: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.hasToInvoice ? 'check' : 'close',
            color: prop.row.hasToInvoice ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    hasToInvoiceByAddress: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.hasToInvoiceByAddress ? 'check' : 'close',
            color: prop.row.hasToInvoiceByAddress ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    isToBeMailed: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.isToBeMailed ? 'check' : 'close',
            color: prop.row.isToBeMailed ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    hasLcr: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.hasLcr ? 'check' : 'close',
            color: prop.row.hasLcr ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    hasCoreVnl: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.hasCoreVnl ? 'check' : 'close',
            color: prop.row.hasCoreVnl ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    hasSepaVnl: {
        component: QIcon,
        props: (prop) => ({
            name: prop.row.hasSepaVnl ? 'check' : 'close',
            color: prop.row.hasSepaVnl ? 'positive' : 'negative',
            size: 'sm',
        }),
        event: () => {},
    },
    actions: {
        component: CustomerExtendedListActions,
        props: (prop) => ({
            id: prop.row.id,
        }),
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: '',
        label: '',
        name: 'customerStatus',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'id',
        label: t('customer.extendedList.tableVisibleColumns.id'),
        name: 'id',
    },
    {
        align: 'left',
        field: 'name',
        label: t('customer.extendedList.tableVisibleColumns.name'),
        name: 'name',
    },
    {
        align: 'left',
        field: 'fi',
        label: t('customer.extendedList.tableVisibleColumns.fi'),
        name: 'fi',
    },
    {
        align: 'left',
        field: 'salesPerson',
        label: t('customer.extendedList.tableVisibleColumns.salesPersonFk'),
        name: 'salesPersonFk',
    },
    {
        align: 'left',
        field: 'credit',
        label: t('customer.extendedList.tableVisibleColumns.credit'),
        name: 'credit',
    },
    {
        align: 'left',
        field: 'creditInsurance',
        label: t('customer.extendedList.tableVisibleColumns.creditInsurance'),
        name: 'creditInsurance',
    },
    {
        align: 'left',
        field: 'phone',
        label: t('customer.extendedList.tableVisibleColumns.phone'),
        name: 'phone',
    },
    {
        align: 'left',
        field: 'mobile',
        label: t('customer.extendedList.tableVisibleColumns.mobile'),
        name: 'mobile',
    },
    {
        align: 'left',
        field: 'street',
        label: t('customer.extendedList.tableVisibleColumns.street'),
        name: 'street',
    },
    {
        align: 'left',
        field: 'country',
        label: t('customer.extendedList.tableVisibleColumns.countryFk'),
        name: 'countryFk',
    },
    {
        align: 'left',
        field: 'province',
        label: t('customer.extendedList.tableVisibleColumns.provinceFk'),
        name: 'provinceFk',
    },
    {
        align: 'left',
        field: 'city',
        label: t('customer.extendedList.tableVisibleColumns.city'),
        name: 'city',
    },
    {
        align: 'left',
        field: 'postcode',
        label: t('customer.extendedList.tableVisibleColumns.postcode'),
        name: 'postcode',
    },
    {
        align: 'left',
        field: 'email',
        label: t('customer.extendedList.tableVisibleColumns.email'),
        name: 'email',
    },
    {
        align: 'left',
        field: 'created',
        label: t('customer.extendedList.tableVisibleColumns.created'),
        name: 'created',
        format: (value) => toDate(value),
    },
    {
        align: 'left',
        field: 'businessType',
        label: t('customer.extendedList.tableVisibleColumns.businessTypeFk'),
        name: 'businessTypeFk',
    },
    {
        align: 'left',
        field: 'payMethod',
        label: t('customer.extendedList.tableVisibleColumns.payMethodFk'),
        name: 'payMethodFk',
    },
    {
        align: 'left',
        field: 'sageTaxType',
        label: t('customer.extendedList.tableVisibleColumns.sageTaxTypeFk'),
        name: 'sageTaxTypeFk',
    },
    {
        align: 'left',
        field: 'sageTransactionType',
        label: t('customer.extendedList.tableVisibleColumns.sageTransactionTypeFk'),
        name: 'sageTransactionTypeFk',
    },
    {
        align: 'left',
        field: 'isActive',
        label: t('customer.extendedList.tableVisibleColumns.isActive'),
        name: 'isActive',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'isVies',
        label: t('customer.extendedList.tableVisibleColumns.isVies'),
        name: 'isVies',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'isTaxDataChecked',
        label: t('customer.extendedList.tableVisibleColumns.isTaxDataChecked'),
        name: 'isTaxDataChecked',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'isEqualizated',
        label: t('customer.extendedList.tableVisibleColumns.isEqualizated'),
        name: 'isEqualizated',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'isFreezed',
        label: t('customer.extendedList.tableVisibleColumns.isFreezed'),
        name: 'isFreezed',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'hasToInvoice',
        label: t('customer.extendedList.tableVisibleColumns.hasToInvoice'),
        name: 'hasToInvoice',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'hasToInvoiceByAddress',
        label: t('customer.extendedList.tableVisibleColumns.hasToInvoiceByAddress'),
        name: 'hasToInvoiceByAddress',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'isToBeMailed',
        label: t('customer.extendedList.tableVisibleColumns.isToBeMailed'),
        name: 'isToBeMailed',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'hasLcr',
        label: t('customer.extendedList.tableVisibleColumns.hasLcr'),
        name: 'hasLcr',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'hasCoreVnl',
        label: t('customer.extendedList.tableVisibleColumns.hasCoreVnl'),
        name: 'hasCoreVnl',
        format: () => ' ',
    },
    {
        align: 'left',
        field: 'hasSepaVnl',
        label: t('customer.extendedList.tableVisibleColumns.hasSepaVnl'),
        name: 'hasSepaVnl',
        format: () => ' ',
    },
    {
        align: 'right',
        field: 'actions',
        label: '',
        name: 'actions',
    },
]);

const stopEventPropagation = (event, col) => {
    if (!['id', 'salesPersonFk'].includes(col.name)) return;
    event.preventDefault();
    event.stopPropagation();
};

const navigateToTravelId = (id) => router.push({ path: `/customer/${id}` });

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

const selectSalesPersonId = (id) => (selectedSalesPersonId.value = id);
</script>

<template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <CustomerExtendedListFilter
                v-if="visibleColumns.length !== 0"
                data-key="CustomerExtendedList"
                :visible-columns="visibleColumns"
            />
        </QScrollArea>
    </QDrawer>
    <VnSubToolbar>
        <template #st-actions>
            <TableVisibleColumns
                :all-columns="allColumnNames"
                table-code="clientsDetail"
                labels-traductions-path="customer.extendedList.tableVisibleColumns"
                @on-config-saved="
                    visibleColumns = ['customerStatus', ...$event, 'actions']
                "
            />
        </template>
    </VnSubToolbar>

    <QPage class="column items-center q-pa-md">
        <QTable
            :columns="columns"
            :pagination="{ rowsPerPage: 12 }"
            :rows="rows"
            class="full-width q-mt-md"
            row-key="id"
            :visible-columns="visibleColumns"
            @row-click="(evt, row, id) => navigateToTravelId(row.id)"
        >
            <template #body-cell="{ col, value }">
                <QTd @click="stopEventPropagation($event, col)">
                    {{ value }}
                </QTd>
            </template>
            <template #body-cell-id="props">
                <QTd @click="stopEventPropagation($event, props.col)">
                    <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)"
                    >
                        <CustomerDescriptorProxy :id="props.row.id" />
                        {{ props.row.id }}
                    </component>
                </QTd>
            </template>
            <template #body-cell-salesPersonFk="props">
                <QTd @click="stopEventPropagation($event, props.col)">
                    <component
                        v-if="props.row.salesPerson"
                        class="col-content"
                        :is="tableColumnComponents[props.col.name].component"
                        v-bind="tableColumnComponents[props.col.name].props(props)"
                        @click="tableColumnComponents[props.col.name].event(props)"
                    >
                        <WorkerDescriptorProxy :id="props.row.salesPersonFk" />
                        {{ props.row.salesPerson }}
                    </component>
                    <span class="col-content" v-else>-</span>
                </QTd>
            </template>
            <template #body-cell-actions="props">
                <QTd @click="stopEventPropagation($event, props.col)">
                    <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)"
                    />
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>

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