<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,
    },
    info: {
        type: String,
        default: undefined,
    },
    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']"
        :filter-options="['id', 'name', 'nickname', 'code']"
        sort-by="nickname ASC"
        data-cy="vnWorkerSelect"
    >
        <template #prepend v-if="$props.hasAvatar">
            <VnAvatar :worker-id="value" color="primary" v-bind="$attrs" />
        </template>
        <template #append v-if="$props.info">
            <QIcon name="info" class="cursor-pointer">
                <QTooltip>{{ $t($props.info) }}</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.id }}, {{ scope.opt.nickname }},
                        {{ scope.opt.code }}
                    </QItemLabel>
                </QItemSection>
            </QItem>
        </template>
    </VnSelect>
</template>

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