<template>
    <v-autocomplete
        ref="Autocomplete"
        :id="id"
        dense
        outlined
        clearable
        :items="items"
        :label="__('Utilizator')"
        append-outer-icon="mdi-plus"
        :error-messages="errors"

        v-model="account.user_id"

        @focus="$emit('focus')"
        @blur="$emit('blur')"
        @click:append-outer="OnClickInsertUser"
    >
    </v-autocomplete>
</template>

<script>
    import JQApply from '@Cs/jquery/Apply';
    import RandomString from '@CsFunc/global/RandomString';

    export default {
        model: { 
            prop: "account", 
            event: "input" 
        }, 

        props: {
            account: {required: true},
            users: {default: () => []},
            errors: {default: null},
        },

        data: () => ({
            id: null,
        }),

        computed: {
            items() {
                let r = _.map(this.users, item => ({
                    text: item.full_name + ' (' + item.email + ')',
                    value: item.id,
                }));
                return _.orderBy(r, [item => item.text], ['asc']);
            }
        },

        methods: {
            OnClickInsertUser(e) {

                JQApply(this.id, [
                    j => {
                        /**
                         * Asa se deactiveaza un meniu de la v-autocomplete
                         */
                        this.$refs.Autocomplete.$refs.menu.callDeactivate();

                        setTimeout( () => {
                            this.$emit('show-user-insert-form', {
                                x: e.clientX,
                                y: e.clientY,
                            })
                        }, 100)
                    }
                ]);
            }
        },

        created() {
            this.id = 'account-input-' + RandomString(64);
        },

        name: 'AccountUserControl',
    }
</script>