<template>
    <div class="selectInput" :ref="currentRef">
        <el-input
                ref="inputRef"
                :placeholder="placeholder"
                v-model="inputValue"
                @focus="handleOnFocus"
                :readonly="false"
                @keyup.native="killKeyFun"
                @clear="handleOnClear"
                clearable
        >
            <template slot="suffix">
                <!--<i class="el-select__caret el-input__icon el-icon-arrow-up" :class="suffixStyle"
                   @click.stop="inputSuffixClick"></i>-->
                <i class="el-select__caret el-input__icon el-icon-arrow-up"
                   :class="{'isReverse':suffixStyle, 'showIcon':!showIcon}"
                   @click.stop="inputSuffixClick"></i>
            </template>
        </el-input>

        <div class="tree-wrap-box show-Tree">

            <!--<el-scrollbar class="selectInputRef-scroll" wrap-class="scrollbar-wrapper">-->
            <perfect-scrollbar>
                <collapse-transition>
                    <el-tree
                            class="filter-tree"
                            :data="originalTreeData"
                            :props="treeDefaultProps"
                            default-expand-all
                            v-if="showTree"
                            @node-click="handleNodeClick"
                            ref="tree">
                    </el-tree>
                </collapse-transition>
            </perfect-scrollbar>
            <!--</el-scrollbar>-->

        </div>

    </div>
</template>

<script>
    /**
     * 使用须知:
     * input下拉树 需要指定currentRef
     * stClassifyId --- currentRef 内含shiti
     * stLevelId --- currentRef 内含Difficulty
     * stKnowledgeId --- currentRef 内含Knowledge
     */

    import { PerfectScrollbar } from 'vue2-perfect-scrollbar';
    import CollapseTransition   from 'element-ui/lib/transitions/collapse-transition';

    export default {
        name:       'SelectInputTree',
        props:      {
            placeholder:       {
                type:    String,
                default: '请选择',
            },
            selectDate:        { // 双向绑定的选中数据
                type:    Object,
                default: () => {
                    return {};
                },
                require: true,
            },
            defaultSelectData: { // 默认选中的数据
                type:    Object,
                default: () => {
                    return {};
                },
            },
            originalTreeData:  { // 树的数据
                type:    Array,
                default: () => {
                    return [];
                },
                require: true,
            },
            treeDefaultProps:  { // 树的结构数据例子
                type:    Object,
                default: () => {
                    return {};
                },
                require: true,
            },
            currentRef:        { // 当前dom索引
                type:    String,
                require: true,
            },
        },
        computed:   {
            suffixStyle: function () {
                /*return {
                    isReverse: this.suffixIsReverse,
                };*/
                return this.suffixIsReverse;
            },
            showIcon() {
                if (this.inputValue) {
                    return false;
                } else {
                    return true;
                }
            },
        },
        data() {
            return {
                inputValue:      '',
                showTree:        false,
                // selectInputIcon: 'el-icon-arrow-up',
                suffixIsReverse: true,
            };
        },
        components: {
            CollapseTransition,
            PerfectScrollbar,
        },
        watch:      {
            defaultSelectData:          {
                handler(val) {
                    // input框赋值
                    this.inputValue = val.lable;
                    // 同步外侧selectData
                    this.$emit('update:selectDate', val);
                },
                immediate: true,
            },
            'selectDate.stClassifyId':  {
                handler(newV, oldV) {
                    this.handleId(newV, oldV);
                },
            },
            'selectDate.stLevelId':     {
                handler(newV, oldV) {
                    this.handleId(newV, oldV);
                },
            },
            'selectDate.id':     {
                handler(newV, oldV) {
                    this.handleId(newV, oldV);
                },
            },
        },
        methods:    {
            handleId(newV, oldV) {
                // console.log(this.currentRef);
                if (this.currentRef.indexOf('shiti') > -1 && this.currentRef.indexOf('Type') > -1) {
                    if (newV === undefined) {
                        this.inputValue = '';
                        return;
                    }
                    this.setTreeVal(newV);
                } else if (this.currentRef.indexOf('Difficulty') > -1) {
                    if (newV === undefined) {
                        this.inputValue = '';
                        return;
                    }
                    this.setTreeVal(newV);
                }  else {
                    // throw new Error('currentRef命名不符合规范');
                    this.setTreeVal(newV);
                }
            },
            handleOnClear() {
                this.$emit('update:selectDate', {});
            },
            killKeyFun(event) {
                this.inputValue = '';
                return false;
            },
            // 清理缓存数据
            clearInputData() {
                this.inputValue = '';
            },
            // 获取焦点时触发事件
            handleOnFocus() {
                this.showTree = true;
                this.suffixIsReverse = false;
                // this.selectInputIcon = 'el-icon-arrow-down';
            },
            // 失去焦点时触发事件
            handleOnBlur(e) {
                if (this.$refs[this.currentRef].contains(e.target) === false) {
                    this.showTree = false;
                    this.suffixIsReverse = true;
                    // this.selectInputIcon = 'el-icon-arrow-up';
                }
            },
            /**
             * Tree 节点点击后触发事件
             * @param data
             * @param node
             * @param self
             */
            handleNodeClick(data, node, self) {

                // 同步input显示
                this.inputValue = data.lable;
                // input图标改变
                this.suffixIsReverse = true;
                // this.selectInputIcon = 'el-icon-arrow-up';
                // tree 组件隐藏
                this.showTree = false;
                // 同步外侧selectData && 业务查看返回数据 同步vuex
                this.$emit('update:selectDate', data);
                this.$emit('changeSelectData', data);
                this.$nextTick(() => {
                    this.$emit('callDepartmentValidate', data);
                });
            },

            findNodeObj(children, idName, id) {
                for (const node of children) {
                    if (parseInt(node[idName]) === parseInt(id)) {
                        return node;
                    }
                    if (node.children instanceof Array) {
                        let _node = this.findNodeObj(node.children, idName, id);
                        if (_node) {
                            return _node;
                        }
                    }
                }
                return null;

            },
            setTreeVal(id) {
                /**
                 * {id: 7,
                 * lable: "二级 3-1"}
                 */
                let idName = '';
                if (this.currentRef.indexOf('shiti') > -1 && this.currentRef.indexOf('Type') > -1) {
                    // idName = 'stClassifyId';
                    idName = 'id';
                } else if (this.currentRef.indexOf('Difficulty') > -1) {
                    // idName = 'stLevelId';
                    idName = 'id';
                } else {
                    idName = 'id';
                    // throw new Error('currentRef命名不符合规范');
                }
                let node = this.findNodeObj(this.originalTreeData, idName, id);
                if (node === null) {
                    throw new Error('id不存在');
                }
                this.inputValue = node.lable;
                this.$emit('update:selectDate', node);
            },
            inputSuffixClick() {
                this.suffixIsReverse = !this.suffixIsReverse;
                this.showTree = !this.showTree;
            },
        },

        beforeMount() {
            document.addEventListener('click', this.handleOnBlur);
        },
        beforeDestroy() {
            document.removeEventListener('click', this.handleOnBlur);
        },
    };
</script>
