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

import { useStateStore } from 'stores/useStateStore';

import FetchData from 'components/FetchData.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';

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

const clientLogs = ref(null);
const urlClientLogsEditors = ref(null);
const urlClientLogsModels = ref(null);
const clientLogsModelsOptions = ref([]);
const clientLogsOptions = ref([]);
const clientLogsEditorsOptions = ref([]);
const radioButtonValue = ref('all');
const insert = ref(false);
const update = ref(false);
const deletes = ref(false);
const select = ref(false);
const neq = ref(null);
const inq = ref([]);

const filterClientLogs = {
    fields: [
        'id',
        'originFk',
        'userFk',
        'action',
        'changedModel',
        'oldInstance',
        'newInstance',
        'creationDate',
        'changedModel',
        'changedModelId',
        'changedModelValue',
        'description',
    ],
    include: [
        {
            relation: 'user',
            scope: {
                fields: ['nickname', 'name', 'image'],
                include: { relation: 'worker', scope: { fields: ['id'] } },
            },
        },
    ],
    order: ['creationDate DESC', 'id DESC'],
    limit: 20,
};
const filterClientLogsEditors = {
    fields: ['id', 'nickname', 'name', 'image'],
    order: 'nickname',
    limit: 30,
};
const filterClientLogsModels = { order: ['changedModel'] };
const urlBase = `ClientLogs/${route.params.id}`;

onBeforeMount(() => {
    stateStore.rightDrawer = true;
    filterClientLogs.where = {
        and: [
            { originFk: `${route.params.id}` },
            { userFk: { neq: radioButtonValue.value } },
            { action: { inq: inq.value } },
        ],
    };
    urlClientLogsEditors.value = `${urlBase}/editors`;
    urlClientLogsModels.value = `${urlBase}/models`;
});

const getClientLogs = async (value, status) => {
    if (status === 'neq') {
        neq.value = value;
    } else {
        setInq(value, status);
    }
    filterClientLogs.where = {
        and: [
            { originFk: `${route.params.id}` },
            { userFk: { neq: neq.value } },
            { action: { inq: inq.value } },
        ],
    };
    clientLogs.value?.fetch();
};

const setInq = (value, status) => {
    if (status) {
        if (!inq.value.includes(value)) {
            inq.value.push(value);
        }
    } else {
        inq.value = inq.value.filter((item) => item !== value);
    }
};
</script>

<template>
    <FetchData
        :filter="filterClientLogs"
        @on-fetch="(data) => (clientLogsOptions = data)"
        auto-load
        url="ClientLogs"
        ref="clientLogs"
    />
    <FetchData
        :filter="filterClientLogsEditors"
        @on-fetch="(data) => (clientLogsEditorsOptions = data)"
        auto-load
        :url="urlClientLogsEditors"
    />
    <FetchData
        :filter="filterClientLogsModels"
        @on-fetch="(data) => (clientLogsModelsOptions = data)"
        auto-load
        :url="urlClientLogsModels"
    />

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

    <QDrawer :width="256" show-if-above side="right" v-model="stateStore.rightDrawer">
        <div class="q-mt-sm q-px-md">
            <VnInput :label="t('Search')">
                <template #append>
                    <QIcon name="info" class="cursor-pointer">
                        <QTooltip>
                            {{ t('Search by id or concept') }}
                        </QTooltip>
                    </QIcon>
                </template>
            </VnInput>
            <VnSelectFilter
                :label="t('Entity')"
                :options="[]"
                class="q-mt-md"
                hide-selected
                option-label="name"
                option-value="id"
            />

            <div class="q-mt-lg">
                <QRadio
                    :dark="true"
                    :label="t('All')"
                    @update:model-value="getClientLogs($event, 'neq')"
                    dense
                    v-model="radioButtonValue"
                    val="all"
                />
            </div>
            <div class="q-mt-md">
                <QRadio
                    :dark="true"
                    :label="t('User')"
                    @update:model-value="getClientLogs($event, 'neq')"
                    dense
                    v-model="radioButtonValue"
                    val="user"
                />
            </div>
            <div class="q-mt-md">
                <QRadio
                    :dark="true"
                    :label="t('System')"
                    @update:model-value="getClientLogs($event, 'neq')"
                    dense
                    v-model="radioButtonValue"
                    val="system"
                />
            </div>

            <VnSelectFilter
                :label="t('User')"
                :options="[]"
                class="q-mt-sm"
                hide-selected
                option-label="name"
                option-value="id"
            />
            <VnInput :label="t('Changes')" class="q-mt-sm">
                <template #append>
                    <QIcon name="info" class="cursor-pointer">
                        <QTooltip>
                            {{ t('Search by changes') }}
                        </QTooltip>
                    </QIcon>
                </template>
            </VnInput>

            <div class="q-mt-md">
                <QCheckbox
                    :label="t('Creates')"
                    @update:model-value="getClientLogs('insert', $event)"
                    v-model="insert"
                />
            </div>
            <div>
                <QCheckbox
                    :label="t('Edits')"
                    @update:model-value="getClientLogs('update', $event)"
                    v-model="update"
                />
            </div>
            <div>
                <QCheckbox
                    :label="t('Deletes')"
                    @update:model-value="getClientLogs('delete', $event)"
                    v-model="deletes"
                />
            </div>
            <div>
                <QCheckbox
                    :label="t('Accesses')"
                    @update:model-value="getClientLogs('select', $event)"
                    v-model="select"
                />
            </div>

            <VnInputDate :label="t('Date')" class="q-mt-sm" />
            <VnInput :label="t('To')" class="q-mt-md" />
        </div>
    </QDrawer>

    <QPageSticky
        :offset="[18, 18]"
        v-if="radioButtonValue !== 'all' || insert || update || deletes || select"
    >
        <QBtn color="primary" fab icon="filter_alt_off" />
        <QTooltip>
            {{ t('Quit filter') }}
        </QTooltip>
    </QPageSticky>
</template>

<i18n>
es:
    Search: Buscar
    Search by id or concept: xxx
    Entity: Entidad
    All: Todo
    User: Usuario
    System: Sistema
    Changes: Cambios
    Search by changes: xxx
    Creates: Crea
    Edits: Modifica
    Deletes: Elimina
    Accesses: Accede
    Date: Fecha
    To: Hasta
    Quit filter: Quitar filtro
</i18n>
