<template>
    <el-dialog title="选择上级菜单" :visible.sync="show" append-to-body destroy-on-close :before-close="onClose">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        <el-tree
            class="mt"
            :data="data"
            :props="defaultProps"
            highlight-current
            :expand-on-click-node="false"
            default-expand-all
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="onNodeClick">
        </el-tree>
        <div class="tool">
            <el-button @click="onClose">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getMenus } from '@/api/menu';

export default {
    props: ['show'],
    data () {
        return {
            filterText: '',
            data: [],
            defaultProps: {
                label: 'name',
                children: 'sub_menus',
            },
            selectedRow: null,
        }
    },
    watch: {
        show(n) {
            if (n) {
                this.loadMenuTree();
            }
        },
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        onClose(flag = false) {
            this.$emit('update:show', false);
            this.$emit('close', flag);
        },
        loadMenuTree() {
            getMenus().then(res => {
                if (res && res.data) {
                    const list = res.data || [];
                    this.data = [{
                        id: '-1',
                        name: '顶级菜单',
                    }, ...list];
                }
            });
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        onNodeClick(data) {
            this.selectedRow = data;
        },
        onSubmit() {
            if (!this.selectedRow) {
                this.$message({
                    message: '请选择一个菜单后操作',
                    type: 'warning'
                });
                return;
            }
            this.$emit('confirm', this.selectedRow);
        },
    }
}
</script>

<style lang="scss" scoped>
.tool {
    display: flex;
    justify-content: flex-end;
    margin: 8px;
}
</style>