<template>
    <div class="container">
        <div class="topTree" :style="{height:(allHeight-142)+'px'}">
            <div @mouseleave="showTable=false" style="position:relactive">
                <el-tree :data="menus" class="tree" :render-content="renderContent" :highlight-current="true" :expand-on-click-node="false" @node-click="nodeClick" node-key="id" default-expand-all>
                </el-tree>

                <div class="tipRight" id='tipRight' v-if="showTable" :style="{top:tableTop+'px'}">
                    <el-table :data="departUsers" :show-header="false">
                        <el-table-column prop="username" label="用户名"></el-table-column>
                    </el-table>
                    <div class="popper__arrow"></div>
                </div>
            </div>

        </div>

        <!-- <el-button size="mini" type="text" @click="addRootMenu" class="btn-add">添加</el-button> -->
        <el-button type="primary" @click="addRootMenu" style="margin-left: 24px;margin-top:20px;width:98px;">添加</el-button>

        <el-dialog :visible.sync="dialogVisible" title="添加菜单">
            <el-form :model="menu" ref="form" size="small">
                <el-form-item label="部门名称" prop="departName" :rules="[{required: true, message: '请填写部门名', trigger: 'blur'}]">
                    <el-input v-model="menu.departName"></el-input>
                </el-form-item>
                <el-form-item label="部门代码" prop="departCode">
                    <el-input v-model="menu.departCode"></el-input>
                </el-form-item>
                <el-form-item label="MIS部门代码" prop="misOrgCode">
                    <el-input v-model="menu.misOrgCode"></el-input>
                </el-form-item>
                <el-form-item label="MIS部门名称" prop="misOrgName">
                    <el-input v-model="menu.misOrgName"></el-input>
                </el-form-item>
                <el-form-item label="MIS包含下属" prop="misInclude">
                    <el-input v-model="menu.misInclude"></el-input>
                </el-form-item>
                <!-- <el-form-item label="MIS下属部门信息" prop="misChild">
                    <el-input v-model="menu.misChild"></el-input>
                </el-form-item> -->
                <el-form-item label="MIS下属部门信息" prop="misChild">
                </el-form-item>
                <el-tree ref="misChildTree" :data="menus" :highlight-current="true" :expand-on-click-node="false" node-key="id" label="label" show-checkbox default-expand-all>
                </el-tree>
            </el-form>
            <div slot="footer">
                <el-button @click="dialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="addMenu" :loading="loading" size="small">保存</el-button>
            </div>
        </el-dialog>
    </div>
    <!-- <el-container class="container">
        <el-aside class="depart-tree" style="width: 400px;">

        </el-aside>
        <el-main class="users">

        </el-main>
    </el-container> -->
</template>
<script>
import axios from 'axios'
import { mapState } from 'vuex'

export default {
    created() {
        this.getData();
    },
    data() {
        return {
            dialogVisible: false,
            curr: null,
            loading: false,
            menus: [],
            menu: {
                departName: '',
                departCode: '',
                misInclude: 'N',
                misOrgCode: '',
                misOrgName: '',
                misChild: '',
            },
            departUsers: [],
            showTable: false,
            tableTop: 0,
        }
    },
    computed: {
        ...mapState(['allHeight']),
    },
    methods: {
        addRootMenu() {
            this.menu = {
                parentId: 0,
                departName: '',
                departCode: '',
                misInclude: 'N',
                misOrgCode: '',
                misOrgName: '',
                misChild: '',
            };
            /*  if (this.menus && this.menus.length > 0) {
                  this.menu.sort = this.menus[this.menus.length - 1].extra.sort + 1;
              } else {
                  this.menu.sort = 1;
              }*/
            this.dialogVisible = true;
        },
        showAddDialog(node, data) {
            this.menu = {
                parentId: node.data.extra.id,
                departName: '',
                departCode: '',
                misInclude: 'N',
                misOrgCode: '',
                misOrgName: '',
                misChild: '',
            };
            if (node.childNodes && node.childNodes.length > 0) {
                this.menu.sort = node.childNodes[node.childNodes.length - 1].data.extra.sort + 1;
            } else {
                this.menu.sort = 1;
            }
            this.dialogVisible = true;
        },
        addMenu() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.menu.misChild = this.$refs.misChildTree.getCheckedKeys(false).join();
                    this.$http.post({
                        url: this.menu.id ? '/departInfo/update' : '/departInfo/save',
                        data: this.menu
                    }).then(res => {
                        this.loading = false;
                        if (res.success) {
                            this.$message.success('保存成功');
                            this.dialogVisible = false;
                            this.getData();
                        } else {
                            this.$message.warning('添加失败')
                        }
                    })
                }
            });
        },
        showEditDialog(node, data) {
            this.menu = {
                id: data.extra.id,
                departName: data.extra.departName,
                departCode: data.extra.departCode || '',
                misInclude: data.extra.misInclude || '',
                misOrgCode: data.extra.misOrgCode || '',
                misOrgName: data.extra.misOrgName || '',
                misChild: data.extra.misChild || '',
            };
            this.dialogVisible = true;
            if (this.menu.misChild) {
                setTimeout(() => {
                    this.$refs.misChildTree.setCheckedKeys(this.menu.misChild.split(','))
                }, 100)
            }


        },
        moveUp(node, data) {
            const formData = d => {
                let formData = new FormData();
                for (let key in d) {
                    if (d.hasOwnProperty(key)) {
                        formData.append(key, d[key]);
                    }
                }
                return formData;
            };
            if (node.previousSibling) {
                axios.all([axios.post(this.$baseUrl + '/departInfo/update', formData({
                    id: node.data.id,
                    sort: node.previousSibling.data.extra.sort
                })), axios.post(this.$baseUrl + '/departInfo/update', formData({
                    id: node.previousSibling.data.id,
                    sort: node.data.extra.sort
                }))]).then(axios.spread((acct, perms) => {
                    this.getData();
                }));
            }
        },
        moveDown(node, data) {

            const formData = d => {
                let formData = new FormData();
                for (let key in d) {
                    if (d.hasOwnProperty(key)) {
                        formData.append(key, d[key]);
                    }
                }
                return formData;
            };
            if (node.nextSibling) {
                axios.all([axios.post(this.$baseUrl + '/departInfo/update', formData({
                    id: node.data.id,
                    sort: node.nextSibling.data.extra.sort
                })), axios.post(this.$baseUrl + '/departInfo/update', formData({
                    id: node.nextSibling.data.id,
                    sort: node.data.extra.sort
                }))]).then(axios.spread((acct, perms) => {
                    this.getData();
                }));
            }
        },
        remove(node, data) {
            this.$confirm('确定删除菜单？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
            }).then(() => {
                this.$http.post({
                    url: '/departInfo/del',
                    data: {
                        id: data.id
                    }
                }).then(res => {
                    if (res.success) {
                        this.$message.success('删除成功');
                        this.getData();
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            }).catch(() => {
            });
        },
        nodeClick(data, node, component) {


            this.$http.get({
                url: '/departInfo/departUsers',
                data: {
                    departId: data.id
                }
            }).then(res => {
                if (res.success) {
                    this.departUsers = res.data
                    var list = document.getElementsByClassName('el-tree-node__content')
                    this.tableTop = list[this.getIndex(data.id)].offsetTop
                    this.showTable = true
                }
            })


        },
        getIndex(id) {
            var index = 0
            var menus = [...this.menus]
            var list = this.getList(menus, [])
            list.forEach((item, i) => {
                if (item == id) {
                    index = i
                }
            })
            return index
        },
        getList(menus, nowList) {
            var list = nowList
            menus.forEach(item => {
                if (item.extra.id) {
                    list.push(item.extra.id)
                }
                if (item.children) {
                    item.children.forEach(todo => {
                        list = this.getList([todo], list)
                    })
                }
            })

            return list
        },
        getData() {
            this.$http.get({
                url: '/departInfo/departTree'
            }).then(res => {
                if (res.success) {
                    const parse = (trees) => {
                        trees.sort((a, b) => {
                            return a.extra.sort - b.extra.sort;
                        });
                        return trees.map(i => {

                            var mis = '';
                            if (i.extra.misOrgCode && i.extra.misOrgName) {

                                mis = '(' + i.extra.misOrgCode + ',' + i.extra.misOrgName + ')'
                            }
                            let t = {
                                id: i.id,
                                label: i.name + mis,
                                parentId: i.parentId,
                                extra: i.extra
                            };
                            if (i.children instanceof Array) {
                                t.children = parse(i.children);
                            }
                            return t;
                        });
                    };
                    this.menus = parse(res.data);
                }
            })
        },
        renderContent(h, { node, data, store }) {
            return (
                <span class="custom-tree-node">
                    <span>{node.label}</span>
                    <span class="url">{data.extra.href}</span>
                    <span class="opt">
                        <el-button size="mini" type="primary" plain on-click={() => this.moveUp(node, data)} class="up">上移</el-button>
                        <el-button size="mini" type="primary" plain on-click={() => this.moveDown(node, data)}>下移</el-button>
                        <el-button size="mini" type="warning" plain on-click={() => this.showEditDialog(node, data)}>编辑</el-button>
                        <el-button size="mini" type="success" plain on-click={() => this.showAddDialog(node, data)}>添加</el-button>
                        <el-button size="mini" type="danger" plain on-click={() => this.remove(node, data)}>删除</el-button>
                    </span>
                </span>
            );
        }
    }
}
</script>
<style lang="less">
.container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;

    .topTree {
        overflow: auto;
        // padding-bottom: 20px;
        border: 1px solid #f2f4f5;
        position: relative;

        .tipRight {
            position: absolute;
            top: 0;
            left: 200px;
            z-index: 500;
            width: 400px;
            padding: 12px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            background-color: #fff;
            // transform: translateY(-30%);
            .popper__arrow {
                background-color: #fff;
                box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.1);
                transform: rotate(125deg);
                width: 10px;
                height: 10px;
                position: absolute;
                left: -4px;
                top: 15px;
            }
        }
    }
    // display: flex;
    // .depart-tree {
    //     width: 400px;
    // }
    // .btn-add {
    //     margin-left: 20px;
    // }
    // .users{
    //     flex-grow: 1;
    // }
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .url {
        flex-grow: 1;
        text-align: right;
        margin-right: 20px;
        color: #999;
    }
    .opt {
        opacity: 0;
    }
}

.custom-tree-node:hover {
    .opt {
        opacity: 1;
    }
}
</style>

