<script setup>
import { onMounted, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectCache from 'src/components/common/VnSelectCache.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import TicketDescriptorProxy from 'src/pages/Ticket/Card/TicketDescriptorProxy.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import { useStateStore } from 'stores/useStateStore';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useArrayData } from 'composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import VnTable from 'src/components/VnTable/VnTable.vue';

const stateStore = useStateStore();
const { t } = useI18n();
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();
const allColumnNames = ref([]);

const arrayData = useArrayData('WeeklyTickets');
const { store } = arrayData;
const tableRef = ref();
const weekdays = [
    { id: 0, name: t('weekdays.mon') },
    { id: 1, name: t('weekdays.tue') },
    { id: 2, name: t('weekdays.wed') },
    { id: 3, name: t('weekdays.thu') },
    { id: 4, name: t('weekdays.fri') },
    { id: 5, name: t('weekdays.sat') },
    { id: 6, name: t('weekdays.sun') },
];

const columns = computed(() => [
    {
        align: 'left',
        name: 'ticketFk',
        label: t('weeklyTickets.id'),
        chip: {
            condition: () => true,
        },
        isId: true,
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'clientFk',
        label: t('ticketList.client'),
        isTitle: true,
        cardVisible: true,
        component: 'select',
        attrs: {
            url: 'Clients',
            optionLabel: 'name',
            optionValue: 'id',
            isWhere: true,
        },
        columnField: {
            component: null,
        },
        format: (row) => row.clientName,
    },
    {
        align: 'left',
        name: 'weekDay',
        label: t('weeklyTickets.shipment'),
        cardVisible: true,
        columnFilter: {
            component: 'select',
            attrs: {
                options: weekdays,
                optionLabel: weekdays.name,
                optionValue: weekdays.id,
            },
            inWhere: true,
        },
    },
    {
        align: 'left',
        label: t('basicData.agency'),
        name: 'agencyModeFk',
        cardVisible: true,
        columnFilter: {
            component: 'select',
            alias: 'tw',
            attrs: {
                url: 'AgencyModes',
                fields: ['id', 'name'],
            },
            inWhere: true,
        },
    },
    {
        align: 'left',
        name: 'warehouseFk',
        label: t('ticketList.warehouse'),
        cardVisible: true,
        columnFilter: {
            component: 'select',
            attrs: {
                url: 'Warehouses',
                fields: ['id', 'name'],
            },
            inWhere: true,
        },
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(row.warehouseName),
    },
    {
        align: 'left',
        name: 'departmentFk',
        label: t('customer.summary.team'),
        component: 'select',
        attrs: {
            url: 'Departments',
        },
        create: true,
        columnField: {
            component: null,
        },
        format: (row, dashIfEmpty) => dashIfEmpty(row.departmentName),
    },
    {
        align: 'right',
        label: '',
        name: 'tableActions',
        actions: [
            {
                title: t('ticketWeekly.delete'),
                icon: 'delete',
                action: (row) =>
                    openConfirmationModal(
                        t('You are going to delete this weekly ticket'),
                        t(
                            'This ticket will be removed from weekly tickets! Continue anyway?',
                        ),
                        () => deleteWeekly(row.ticketFk),
                    ),
                isPrimary: true,
            },
        ],
    },
]);

const deleteWeekly = async (ticketFk) => {
    await axios.delete(`TicketWeeklies/${ticketFk}`);
    notify(t('globals.dataSaved'), 'positive');
    const ticketIndex = store.data.findIndex((e) => e.ticketFk == ticketFk);
    store.data.splice(ticketIndex, 1);
    location.reload();
};

const onUpdate = async (ticketFk, field, value) => {
    const params = { ticketFk, [field]: value };
    await axios.patch('TicketWeeklies', params);
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    const filteredColumns = columns.value.filter((col) => col.name !== 'actions');
    allColumnNames.value = filteredColumns.map((col) => col.name);
});
</script>

<template>
    <VnSearchbar
        data-key="WeeklyTickets"
        :label="t('weeklyTickets.search')"
        :info="t('weeklyTickets.searchInfo')"
    />
    <VnTable
        ref="tableRef"
        data-key="WeeklyTickets"
        url="TicketWeeklies/filter"
        :columns="columns"
        default-mode="table"
        :use-model="true"
        :disable-option="{ card: true }"
        auto-load
    >
        <template #column-ticketFk="{ row }">
            <span class="link" @click.stop>
                {{ row.ticketFk }}
                <TicketDescriptorProxy :id="row.ticketFk" />
            </span>
        </template>
        <template #column-weekDay="{ row }">
            <VnSelect
                :options="weekdays"
                hide-selected
                option-label="name"
                option-value="id"
                v-model="row.weekDay"
                @update:model-value="onUpdate(row.ticketFk, 'weekDay', $event)"
            />
        </template>
        <template #column-agencyModeFk="{ row }">
            <VnSelectCache
                url="AgencyModes/isActive"
                :row="row"
                :find="['agencyModeFk', 'agencyModeName']"
                v-model="row.agencyModeFk"
                @update:model-value="onUpdate(row.ticketFk, 'agencyModeFk', $event)"
            />
        </template>
        <template #column-clientFk="{ row }">
            <span class="link" @click.stop>
                {{ row.clientName }}
                <CustomerDescriptorProxy :id="row.clientFk" />
            </span>
        </template>
        <template #column-departmentFk="{ row }">
            <span class="link" @click.stop>
                {{ row.departmentName }}
                <DepartmentDescriptorProxy :id="row.departmentFk" />
            </span>
        </template>
    </VnTable>
</template>

<i18n>
es:
    You are going to delete this weekly ticket: Vas a eliminar este ticket programado
    This ticket will be removed from weekly tickets! Continue anyway?: Este ticket se eliminará de tickets programados! ¿Continuar de todas formas?
</i18n>
