<!-- Created by henian.xu on 2018/9/4. -->

<template>
    <div
        :class="['tree-picker',{disabled:isDisabled}]"
        v-clickoutside="handleClose"
    >
        <!--<el-input
            ref="reference"
            :readonly="true"
            height="200px"
            @focus="handleFocus"/>-->
        <div
            class="inner"
            @click="handleFocus"
        >
            <Tags ref="reference">
                <el-tag
                    v-for="(item) in checkedData"
                    :key="item.id"
                    size="small"
                    disable-transitions
                    type="info"
                >
                    {{ item[props.label] }}
                </el-tag>
            </Tags>
            <i class="icon el-icon-arrow-down" />
        </div>
        <transition
            @after-leave="doDestroy"
            name="el-zoom-in-top"
        >
            <el-select-menu
                class="tree-picker-select-menu"
                ref="popper"
                :append-to-body="popperAppendToBody"
                v-show="visible"
            >
                <div
                    v-if="filterable"
                    class="pa-a"
                >
                    <el-input
                        :placeholder="$$t('vmf_enter_key_words2', '输入关键字进行过滤')"
                        v-model="filterText"
                    />
                </div>
                <el-tree
                    ref="tree"
                    :data="treeData"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    highlight-current
                    @check="onTreeCheck"
                    :filter-node-method="onTreeFilterMethod"
                    :props="props"
                />
            </el-select-menu>
        </transition>
    </div>
</template>

<script>
import emitter from 'element-ui/src/mixins/emitter';
import selectMixin from './mixin';
import Tags from './tags';

export default {
    name: 'TreePicker',
    mixins: [emitter, selectMixin],
    components: { Tags },
    data() {
        return {
            treeData: [],
            filterText: '',
            loaded: false,
        };
    },
    props: {
        value: {
            type: Array,
            required: true,
        },
        remote: {
            type: String,
            required: true,
        },
        remoteParams: {
            type: Object,
            default() {
                return {};
            },
        },
        selectAnyOne: {
            type: Boolean,
            default: false,
        },
        filterable: {
            type: Boolean,
            default: false,
        },
        props: {
            type: Object,
            default() {
                return {
                    label: 'name',
                    children: 'children',
                };
            },
        },
        popperAppendToBody: {
            type: Boolean,
            default: true,
        },
    },
    computed: {
        checkedData: {
            get() {
                const { value, loaded } = this;
                const { tree } = this.$refs;
                const res = [];
                if (!loaded || !tree) return res;
                value.forEach(item => {
                    const node = tree.getNode(item);
                    // console.log(loaded, value, node);
                    if (node) res.push(node.data);
                });
                return res;
            },
            set(val) {
                const res = val.reduce((prev, curr) => {
                    prev.push(curr.id);
                    return prev;
                }, []);
                this.$emit('input', res);
                this.dispatch('ElFormItem', 'el.form.change', [res]);
            },
        },
    },
    watch: {
        value: {
            handler(val) {
                this.setCheckedKeys(val);
            },
        },
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        getDataList() {
            // /sp/shopGoodsCat/selectAll
            this.loaded = false;
            this.$http
                .get(
                    this.remote,
                    {
                        ...this.remoteParams,
                    },
                    {
                        isAxiosResponseData: true,
                        isRepeat: true,
                    },
                )
                .then(res => {
                    this.treeData = this.$utils.Convert.listToTree(res.data);
                    this.setCheckedKeys(this.value);
                    this.$nextTick(() => {
                        this.loaded = true;
                    });
                });
        },
        setCheckedKeys(val) {
            if (!this.$refs.tree) return;
            this.$refs.tree.setCheckedKeys(val);
        },
        onTreeFilterMethod(value, data) {
            if (!value) return true;
            return data[this.props.label].indexOf(value) !== -1;
        },
        onTreeCheck(data, checkedData) {
            // checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys
            const { checkedNodes } = checkedData;

            if (this.selectAnyOne) {
                let childrenList = [];
                checkedNodes.forEach(item => {
                    const children = item[this.props.children];
                    if (!children || !children.length) return;
                    childrenList = childrenList.concat(
                        children.reduce((prev, curr) => {
                            prev.push(curr.id);
                            return prev;
                        }, []),
                    );
                });
                // eslint-disable-next-line no-plusplus,no-cond-assign
                for (let i = checkedNodes.length, item; (item = checkedNodes[--i]); ) {
                    // eslint-disable-next-line no-continue
                    if (childrenList.indexOf(item.id) === -1) continue;
                    checkedNodes.splice(i, 1);
                }
            } else {
                // eslint-disable-next-line no-plusplus,no-cond-assign
                for (let i = checkedNodes.length, item; (item = checkedNodes[--i]); ) {
                    const children = item[this.props.children];
                    // eslint-disable-next-line no-continue
                    if (!children || !children.length) continue;
                    checkedNodes.splice(i, 1);
                }
            }
            this.checkedData = checkedNodes;
            // console.log(data, checkedData);
        },
    },
    created() {
        this.getDataList();
    },
};
</script>

<style lang="scss">
.tree-picker {
    display: inline-block;
    vertical-align: top;
    /*width: 200px;*/
    min-width: 200px;
    > .inner {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        border: 1px solid #dcdfe6;
        border-radius: 4px;

        > .tags {
            flex: 1 1 1%;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: flex-start;
            flex-wrap: wrap;
            padding: $padding-small 0 0 0;
            min-height: 32px;

            > .el-tag {
                margin: 0 $margin-small $margin-small $margin-small;
            }
        }

        &:focus {
            border-color: $color-main;
            outline: none;
        }
        > .icon {
            flex: 0 0 auto;
            width: 30px;
            text-align: center;
            color: #c0c4cc;
        }
    }
    &.disabled {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
        color: #c0c4cc;
        cursor: not-allowed;
    }
}
.tree-picker-select-menu {
    max-height: 480px;
    overflow: auto;
    @include beautify-scrollbar();
}
</style>
