<template>
    <AutoComplete v-model="data[filter.code]" :placeholder="filter.label" @on-change="handleSearch" @on-focus = "handleFocus" :style="style" clearable>
        <Option v-for = "(item, index) in queryData"
            :key = "item.guid + '&' + index"
            :value = "item.guid">{{ item.text }}</Option>
    </AutoComplete>
</template>
<script>
import Data from '../../../../data/web-form'
import Emitter from '../../../../mixins/emitter'

export default {
    name: 'FAutoComplete',
    data() {
        return {
            queryData: null,
            timer: null,
            originData: null
        }
    },
    mixins: [Emitter],
    props: {
        filter: {
            type: Object
        },
        data: {
            type: Object
        }
    },
    computed: {
        style() {
            return {
                'width': (this.filter.width || 100) + 'px'
            }
        }
    },
    methods: {
        handleSearch(value) {
            if (this.originData) {
                this.judgeAndSetData(this.originData, value)
            } else {
                Data.queryConfigSelectDataWithFilter(this.filter.ds, value).then((res) => {
                    this.originData = res
                    this.judgeAndSetData(res, value)
                });
            }
        },

        handleFocus (e) {
            let target = e.srcElement || e.target
            let value = target.value
            Data.queryConfigSelectDataWithFilter(this.filter.ds, value).then((res) => {
                this.originData = res
                this.judgeAndSetData(res, value)
            });
        },

        judgeAndSetData (res, value) {
            var obj = {}
            res = res.reduce((cur, next) => {
                obj[next.guid] ? "" : obj[next.guid] = true && cur.push(next)
                return cur
            }, []) 
            if (value) {
                this.setData(res)
            } else {
                this.queryData = res
            }
        },

        setData(source) {
            this.queryData = source.filter((item, index) => { 
                return item.text.includes(this.data[this.filter.code]) 
            })
        }
    },
    mounted() {}
};
</script>
<style lang="less">
.ivu-auto-complete {
    left: 0!important;
    max-height: 200px!important;
    overflow-y: auto;
}
</style>