<template>
    <StSelectInputTreeSlot>
        <template slot="input">
            <el-input
                    :placeholder="placeholder"
                    :readonly="false"
                    :ref="currentRef"
                    @clear="handleOnClear"
                    @focus="handleOnFocus"
                    @keyup.native="killKeyFun"
                    clearable
                    v-model="inputValue"
            >
                <template slot="suffix">
                    <!--<i class="el-select__caret el-input__icon el-icon-arrow-up" :class="suffixStyle"
                       @click.stop="inputSuffixClick"></i>-->
                    <i :class="{'isReverse':suffixStyle, 'showIcon':!showIcon}"
                       @click.stop="inputSuffixClick"
                       class="el-select__caret el-input__icon el-icon-arrow-up"></i>
                </template>
            </el-input>
        </template>
        <template slot="tree">
            <div class="st-picker-panel" v-if="showTree">
                <el-tree
                        :data="originalTreeData"
                        :props="treeDefaultProps"
                        @node-click="handleNodeClick"
                        class="filter-tree"
                        default-expand-all
                        ref="tree">
                </el-tree>
            </div>
        </template>
    </StSelectInputTreeSlot>
</template>

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


    import StSelectInputTreeSlot   from '@/components/management/Layout/SelectInput/StSelectInputTreeSlot.vue';

    export default {
        name:       'SelectInputTree',
        props:      {
            type:              {
                type:    String,
                require: true,
            },
            selectDate:        { // 双向绑定的选中数据
                type:    Object,
                default: () => {
                    return {};
                },
                require: true,
            },
            defaultSelectData: { // 默认选中的数据
                type:    Object,
                default: () => {
                    return {};
                },
            },
            originalTreeData:  { // 树的数据
                type:    Array,
                default: () => {
                    return [];
                },
                require: true,
            },
            mapping:  { // 映射
                type:    Object,
                default: () => {
                    return {};
                },
                require: true,
            },
        },
        computed:   {
            suffixStyle: function () {
                /*return {
                    isReverse: this.suffixIsReverse,
                };*/
                return this.suffixIsReverse;
            },
            showIcon() {
                if (this.inputValue) {
                    return false;
                } else {
                    return true;
                }
            },
        },
        data() {
            return {
                placeholder:     '请选择',
                inputValue:      '',
                showTree:        false,
                // selectInputIcon: 'el-icon-arrow-up',
                suffixIsReverse: true,
                currentRef: '',
                treeDefaultProps: {},
            };
        },
        components: {
            StSelectInputTreeSlot,
        },
        watch:      {
            selectDate:                {
                handler(val) {
                    // input框赋值
                    this.inputValue = val[this.mapping['label'] ? this.mapping['label'] : 'label'];
                    let id = '';
                    if (val.id) {
                        id = val.id;
                    } else if (val.stClassifyId) {
                        id = val.stClassifyId;
                    } else if (val.stLevelId) {
                        id = val.stLevelId;
                    } else {
                        // throw new Error('Id找不到 或者 不符合规范');
                        // return;
                    }

                    this.handleId(id);
                },
                immediate: true,
                deep:      true,
            },
        },
        created() {
            if (this.type === 'department') {
                this.placeholder = '请选择部门';
            } else if (this.type === 'curse') {
                this.placeholder = '请选择课程分类';
            } else if (this.type === 'exam') {
                this.placeholder = '请选择考试分类';
            } else if (this.type === 'kejian') {
                this.placeholder = '请选择课件分类';
            } else if (this.type === 'shitiType') {
                this.placeholder = '请选择试题分类';
            } else if (this.type === 'shitiDifficulty') {
                this.placeholder = '请选择难度';
            }
            this.currentRef = 'selectInput' + Math.floor(Math.random() * 100000);
            this.treeDefaultProps = {
                label: this.mapping['label'] ? this.mapping['label'] : 'label',
                data:  'children',
            }
        },
        methods:    {
            handleId(newV, oldV) {
                if (newV === undefined) {
                    this.inputValue = '';
                    return;
                }
                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].$el.parentElement.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[this.mapping['label'] ? this.mapping['label'] : 'label'];
                // 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"}
                 */
                if (!id) {
                    this.inputValue = '';
                    // this.$emit('update:selectDate', {});
                    return;
                }
                let node = this.findNodeObj(this.originalTreeData, 'id', id);
                if (node === null) {
                    console.log(this.originalTreeData, 'id', id);
                    throw new Error('id不存在');
                }
                this.inputValue = node[this.mapping['label'] ? this.mapping['label'] : 'label'];
                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>
<style lang="scss" scoped>
    .st-picker-panel {
        color: #606266;
        /*border: 1px solid #E4E7ED;*/
        /*box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);*/
        background: #FFF;
        border-radius: 4px;
        line-height: 30px;
        /**
         * @summary 修改 高度闪烁问题
         * @author Wxy
         * @date 2020/4/26
         */
        max-height: 250px;
    }
</style>
