<template>
    <div>
       <autocomplete-selector 
            :value="value"
            :errors="errors"
            label="Departamentul"
            :dataprovider="dataprovider"
            :disabled="disabled"
            :noLoadData="true"
            :hasInsert="!! departmentForm"

            @focus="$emit('focus')"
            @blur="$emit('blur')"
            @click:append-outer="OnClickAppendOuter"
            
            @input="$emit('input', $event)"
        />

        <departament-form-menu 
            v-if="departmentForm"
            :app="app"
            :form="app.forms.Departamente"
            @insert="OnInsertDepartment"
        />
    </div>
</template>

<script>

    import DataProvider from 'APPS/Dataproviders/Customer/Departamente/Departamente';

    export default {
        props: {
            value: {required: true},
            errors: {default: null},
            disabled: {default: false},
            customer_id: {default: null},
            departmentForm: {default: null},
            app: {default: null},
        },

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

        watch: {
            customer_id: function(customer_id) {
                if(customer_id)
                {
                    this.dataprovider.GetByCustomerId(customer_id);
                }
                else
                {
                    this.$emit('input', null);
                }
            }
        },

        methods: {
            OnClickAppendOuter(e) {
                this.ShowActionForm(e, 'insert', null);
            },

            OnInsertDepartment(record) {
                this.dataprovider.GetByCustomerId(this.customer_id);
                this.$emit('input', record.id);
            },

            ShowActionForm(e, action, record) {
                if(! this.departmentForm )
                {
                    return false;
                }
                this.departmentForm.menu.visible = false;
                this.departmentForm.Show(null, action, record);
                this.departmentForm.formprovider.activeRecord.customer_id = this.customer_id;

                this.$nextTick( () => {
                    this.departmentForm.menu.visible = true;
                    this.departmentForm.menu.x = e.clientX;
                    this.departmentForm.menu.y = e.clientY;

                });                
            }
        },

        created() {
            this.dataprovider = new DataProvider(null);

            if(this.customer_id)
            {
                this.dataprovider.GetByCustomerId(this.customer_id)
            }
        },

        components: {
            AutocompleteSelector: require('./../AutocompleteSelector').default,
        },

        name: 'DepartamentAutocompleteSelector',
    }
</script>