Vue.component("ibiz-autocomplete", {
    template: `
    <el-autocomplete size="small" :value="field.value" value-key="text" clearable :fetch-suggestions="onSearch" @select="onSelect" @blur="onBlur" @clear="onClear" :disabled="field.disabled" :trigger-on-focus="false" style="width: 100%;"></el-autocomplete>
    `,
    props: ['field', 'name', 'width'],
    data: function () {
        let data: any = {
            http: IBizHttp.getInstance()
        };
        Object.assign(data, this.field.editorParams);
        Object.assign(data, { form: this.field.getForm() })
        return data;
    },
    methods: {
        onClear() {
            if (this.form) {
                let valueField = this.form.findField(this.valueItem);
                if (valueField) {
                    valueField.setValue('');
                }
                let itemField = this.form.findField(this.name);
                if (itemField) {
                    itemField.setValue('');
                }
            }
        },
        onBlur(e) {
            let val: string = e.target.value;
            if (!Object.is(val, this.field.value)) {
                this.onSelect({ text: val, value: '' });
            }
        },
        onSelect(item) {
            if (this.form) {
                let valueField = this.form.findField(this.valueItem);
                if (valueField) {
                    valueField.setValue(item.value);
                }
                let itemField = this.form.findField(this.name);
                if (itemField) {
                    itemField.setValue(item.text);
                }
            }
        },
        onSearch(query, callback) {
            const _this = this;
            let param: any = {
                srfaction: 'itemfetch',
                query: query,
            };
            if (_this.form) {
                Object.assign(param, { srfreferdata: JSON.stringify(_this.form.getActiveData()) });
            }
            _this.http.post(_this.url, param).subscribe((response) => {
                let items = [];
                if (response.ret == 0) {
                    items = response.items;
                }
                callback(items)
            }, () => {
                callback([]);
            });
        }
    }
});