<template>
    <Select ref="select" :value="currVal" class="ivu-auto-complete" :placeholder="placeholder" :clearable="true" @on-clear="onClear" transfer>
        <slot>
            <Tree :class="{'ivu-select-not-found':!treeData}" :data="treeData" @on-select-change="selectData"></Tree>
        </slot>
    </Select>
</template>
<script>
export default {
    name: 'XSelectTree',
    data() {
        return {
            currVal: this.value,
            treeData: undefined
        }
    },
    watch: {
        data(newVal) {
            this.treeData = this.convertToTree(newVal);
        },
        currVal(newVal) {
            this.$emit('input', newVal);
            this.$emit('on-change', newVal);
        }
    },
    props: {
        data: {
            type: Array,
            default: () => []
        },
        placeholder: {
            type: String
        },
        value: {
            type: [String, Number],
            default: ''
        }
    },
    computed: {},
    mounted() {

    },
    methods: {
        /*convert flat data to tree data*/
        convertToTree(data) {
            let tree = [];
            let temp = {};

            data.forEach((d) => {
                let item = Object.assign({}, d, { "title": d.NAME });
                if (item.PARENT_GUID) {
                    let parent = temp[item.PARENT_GUID];
                    if (parent) {
                        if (!parent["children"]) {
                            parent["children"] = [];
                        }

                        parent["children"].push(item);
                    } else {
                        tree.push(item);
                    }
                } else {
                    tree.push(item);
                }

                temp[item.GUID] = item;
            });

            return tree;
        },
        selectData(node) {
            if (node && node.length > 0) {
                const select = node[0];

                const guid = select.GUID || select.title;
                const label = select.title;

                this.currVal = guid;
                this.$refs.select.$emit('on-select-selected', {
                    value: guid,
                    label: label,
                });
            }
        },

        onClear() {
            this.currVal = null;
        }
    }
};

</script>
<style scoped>
</style>
