<script setup>
import { computed, useAttrs } from 'vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnAvatar from 'src/components/ui/VnAvatar.vue';

const emit = defineEmits(['update:modelValue']);
const $props = defineProps({
    hasAvatar: {
        type: Boolean,
        default: false,
    },
    hasInfo: {
        type: Boolean,
        default: false,
    },
    modelValue: {
        type: [String, Number, Object],
        default: null,
    },
});

const $attrs = useAttrs();

const value = computed({
    get() {
        return $props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    },
});

const url = computed(() => {
    let url = 'Workers/search';
    const { departmentCodes } = $attrs.params ?? {};
    if (!departmentCodes) return url;
    const params = new URLSearchParams({
        departmentCodes: JSON.stringify(departmentCodes),
    });

    return url.concat(`?${params.toString()}`);
});
</script>

<template>
    <VnSelect
        :label="$t('globals.worker')"
        v-bind="$attrs"
        v-model="value"
        :url="url"
        option-value="id"
        option-label="nickname"
        :fields="['id', 'name', 'nickname', 'code']"
        sort-by="nickname ASC"
    >
        <template #prepend v-if="$props.hasAvatar">
            <VnAvatar :worker-id="value" color="primary" :title="title" />
        </template>
        <template #append v-if="$props.hasInfo">
            <QIcon name="info" class="cursor-pointer">
                <QTooltip>{{ $t($props.hasInfo) }}</QTooltip>
            </QIcon>
        </template>
        <template #option="scope">
            <QItem v-bind="scope.itemProps">
                <QItemSection>
                    <QItemLabel>
                        {{ scope.opt.name }}
                    </QItemLabel>
                    <QItemLabel v-if="!scope.opt.id">
                        {{ scope.opt.nickname }}
                    </QItemLabel>
                    <QItemLabel caption v-else>
                        {{ scope.opt.nickname }}, {{ scope.opt.code }}
                    </QItemLabel>
                </QItemSection>
            </QItem>
        </template>
    </VnSelect>
</template>

<i18n>
es:
    Responsible for approving invoices: Responsable de aprobar las facturas
</i18n>
