<script setup>
import { ref } from 'vue';
import VnCheckbox from './VnCheckbox.vue';
import axios from 'axios';
import { toRaw } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
const route = useRoute();
const { t } = useI18n();
const model = defineModel({ type: [Boolean] });
const props = defineProps({
    expand: {
        type: Boolean,
        default: false,
    },
    url: {
        type: String,
        default: null,
        required: true,
    },
    searchUrl: {
        type: [String, Boolean],
        default: 'table',
    },
});
const value = ref(false);
const rows = ref(0);
const onClick = () => {
    if (value.value) {
        const { filter } = JSON.parse(route.query[props.searchUrl]);
        filter.limit = 0;
        const params = {
            params: { filter: JSON.stringify(filter) },
        };
        axios
            .get(props.url, params)
            .then(({ data }) => {
                rows.value = data;
            })
            .catch(console.error);
    }
};
defineEmits(['update:selected', 'select:all']);
</script>

<template>
    <div style="display: flex">
        <VnCheckbox v-model="value" @click="$emit('update:selected', value)" />
        <QBtn
            v-if="value && $props.expand"
            flat
            dense
            icon="expand_more"
            @click="onClick"
        >
            <QMenu anchor="bottom right" self="top right">
                <QList>
                    <QItem v-ripple clickable @click="$emit('select:all', toRaw(rows))">
                        {{ t('Select all', { rows: rows.length }) }}
                    </QItem>
                    <slot name="more-options"></slot>
                </QList>
            </QMenu>
        </QBtn>
    </div>
</template>
<i18n lang="yml">
en:
    Select all: 'Select all ({rows})'
fr:
    Select all: 'Sélectionner tout ({rows})'
es:
    Select all: 'Seleccionar todo ({rows})'
de:
    Select all: 'Alle auswählen ({rows})'
it:
    Select all: 'Seleziona tutto ({rows})'
pt:
    Select all: 'Selecionar tudo ({rows})'
</i18n>
