<template>
    <div>
        <el-card class="box-card" shadow="always" :style="'height:' + vh + 'px'">
            <div class="clearfix" slot="header">
                <b>
                    <!-- <svg-icon icon-class="menu"/> -->
                    菜单列表
                </b>
            </div>
            <!-- 搜索表单 -->
            <el-form ref="queryForm" :model="queryParams" :inline="true">
                <el-form-item>
                    <el-button type="primary" icon="el-icon-plus" @click="menuAdd">新增</el-button>
                    <el-input v-model="search" placeholder="输入关键字搜索" style="width: 500px" />
                </el-form-item>
            </el-form>

            <!-- 数据表格 -->
            <el-table
                v-loading="loading"
                :data="pageList"
                :height="vhh"
                row-key="id"
                :expand-row-keys="expandRow"
                highlight-current-row
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                @row-click="handleRowClick"
                header-cell-class-name="table_header"
                stripe
                border
                size="mini"
            >
                <el-table-column min-width="150" label="菜单名称">
                    <template slot-scope="scope">
                        <svg-icon :icon-class="scope.row.icon ? scope.row.icon : 'build'" />
                        {{ scope.row.title }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="120" align="center">
                    <template slot-scope="scope">
                        <!-- v-if="scope.row.parentNode==='0'" -->
                        <el-button
                            v-if="scope.row.addflag"
                            type="primary"
                            icon="el-icon-plus"
                            size="mini"
                            @click.stop="menuHandAdd(scope.row)"
                        >
                            新增
                        </el-button>
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click.stop="handleEdit(scope.row)">
                            修改
                        </el-button>
                        <el-button
                            type="danger"
                            size="mini"
                            icon="el-icon-delete"
                            @click.stop="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog
            :close-on-click-modal="false"
            :title="rowName"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="closemenu"
        >
            <el-form ref="form" :model="formData" :rules="rules" label-width="90px">
                <el-form-item label="上级菜单:" prop="pid">
                    <!-- <el-select v-model="formData.pid" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in tableData"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select> -->
                    <el-select style="width: 100%" ref="selectTree" v-model="formData.pid" placeholder="请选择上级菜单">
                        <el-option :value="formData.pid" :label="treename" style="height: auto">
                            <el-tree
                                ref="tree"
                                :data="categoryOptions"
                                :default-expand-all="false"
                                node-key="pid"
                                empty-text="无匹配数据"
                                :props="defaultProps1"
                                highlight-current
                                @node-click="handleNodeClick"
                            />
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="菜单名称:" class="top" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入菜单名称" />
                </el-form-item>
                <el-form-item label="菜单别名:" class="top" prop="routeName">
                    <el-input v-model="formData.routeName" placeholder="请输入英文菜单名称" />
                </el-form-item>
                <el-form-item label="排序:" class="top" prop="sort">
                    <el-input v-model="formData.sort" placeholder="请输入排序" />
                    <!-- <el-radio-group v-model="form.state">
            <el-radio :label="0">不启用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group> -->
                </el-form-item>
                <el-form-item label="资源路径:" class="top" prop="path">
                    <el-input v-model="formData.path" placeholder="sys/admin/user或sys:user:add" style="width: 100%" />
                </el-form-item>
                <el-form-item label="菜单图标:" class="top" prop="icon">
                    <el-popover
                        placement="bottom-start"
                        width="500"
                        trigger="click"
                        @show="$refs['iconSelect'].reset()"
                    >
                        <IconSelect ref="iconSelect" @selected="handleIconSelected" />
                        <el-input slot="reference" v-model="formData.icon" placeholder="点击选择图标">
                            <svg-icon
                                v-if="formData.icon"
                                slot="prefix"
                                :icon-class="formData.icon"
                                class="el-input__icon"
                                style="height: 40px; width: 16px"
                            />
                            <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                        </el-input>
                    </el-popover>
                </el-form-item>

                <el-form-item label="资源类型:" prop="type">
                    <el-radio-group v-model="formData.type">
                        <el-radio :label="0">菜单</el-radio>
                        <!-- <el-radio :label="1">公共资源</el-radio> -->
                        <!-- <el-radio :label="2">服务间调用资源</el-radio> -->
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单描述:">
                    <el-input type="textarea" v-model="formData.remark" placeholder="请输入菜单描述" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="handleSubmit" >确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { add, list, update, listmesg, deleteMenu } from '@/api/admin/menu'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import TreeSelect from '@riophae/vue-treeselect'
import IconSelect from '@/components/IconSelect'
export default {
    name: 'Menu',
    components: { IconSelect },
    computed: {
        pageList: function () {
            var searchValue = this.search
            if (searchValue) {
                // 一般表格的查询
                // return  this.tableData.filter(function(dataNews){
                //   return Object.keys(dataNews).some(function(key){
                //     return String(dataNews[key]).toLowerCase().indexOf(search) > -1
                //   })
                // })
                let treeData = this.tableData
                let handleTreeData = this.handleTreeData(treeData, searchValue)
                this.setExpandRow(handleTreeData)
                this.expandRow = this.expandRow.join(',').split(',')
                return handleTreeData
            }
            return this.tableData
        }
    },
    data() {
        return {
            flag: -1,
            categoryOptions: [],
            // 树型数据
            treename: '根节点',
            defaultProps1: {
                /** 唯一标识 **/
                value: 'id',
                /** 标签显示 **/
                label: 'title',
                /** 子级 **/
                children: 'children',
                /** 是否禁用 **/
                disabled: function (data, node) {
                    if (data.isLeaf == 1) {
                        return false
                    } else {
                        return true
                    }
                }
            },

            search: '',
            expandRow: [],
            vh: null,
            vhh: null,
            rowhang: undefined,
            tableheight: null,
            loading: true,
            flagb: false,
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            ids: [],
            single: true,
            multiple: true,
            addScode: false,
            queryParams: {
                name: undefined,
                queryMode: undefined
            },
            pagination: {
                page: 1,
                limit: 10,
                total: 0
            },
            tableData: [],
            t: undefined,
            rowName: '新增菜单',
            dialogVisible: false,
            parentName: '根节点',
            formData: {
                id: '',
                code: 'menu',
                routeName: '',
                icon: '',
                name: '',
                path: '',
                pid: '0',
                remark: '',
                sort: 0,
                type: 0
            },
            rules: {
                // parentId: [
                //   {required: true, message: '请选择顶级菜单', trigger: 'blur'}
                // ],
                pid: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
                name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
                routeName: [{ required: true, message: '请输入菜单别名', trigger: 'blur' }],
                sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
                path: [{ required: true, message: '请输入资源路径', trigger: 'blur' }],
                icon: [{ required: true, message: '请选择菜单图标', trigger: 'blur' }],
                type: [{ required: true, message: '请选择资源类型', trigger: 'blur' }],
                diecable: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }]
            },
            menuOptions: [],
            currentRow: undefined
        }
    },
    created() {
        //this.loadMenuOptions()
        this.handleQuery()
    },
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)

        this.loadCategoryList()
        this.loadDataSet()
        this.echoDataSet(this.formData)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 10
            this.vhh = window.sessionStorage.getItem('appheight') - 134
        },
        handleNodeClick(data, node, nodeData) {
            if (this.t == 'edit') {
                this.treename = data.title
                //this.formData.id= data.pid;
                this.formData.pid = data.id
                this.formData.code = data.code
            } else {
                this.treename = data.title
                this.formData.id = data.id
                this.formData.pid = data.id
                this.formData.code = data.code
            }

            // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
            this.$refs.selectTree.blur()
        },

        //  树形表格过滤
        handleTreeData(treeData, searchValue) {
            if (!treeData || treeData.length === 0) {
                return []
            }
            const array = []
            for (let i = 0; i < treeData.length; i += 1) {
                let match = false
                for (let pro in treeData[i]) {
                    if (typeof treeData[i][pro] == 'string') {
                        match |= treeData[i][pro].includes(searchValue)
                        if (match) break
                    }
                }
                if (this.handleTreeData(treeData[i].children, searchValue).length > 0 || match) {
                    if (treeData[i].type == 0 && match) {
                        this.flag = 0
                        searchValue = ''
                        array.push({
                            ...treeData[i],
                            children: this.handleTreeData(treeData[i].children, searchValue)
                        })
                    } else if (treeData[i].type == 1 && match) {
                        if (this.flag == 0) {
                            this.flag = 1
                        }
                        searchValue = ''
                        array.push({
                            ...treeData[i],
                            children: this.handleTreeData(treeData[i].children, searchValue)
                        })
                        if (this.flag != 1) {
                            searchValue = this.search
                        }
                    } else {
                        array.push({
                            ...treeData[i],
                            children: this.handleTreeData(treeData[i].children, searchValue)
                        })
                    }
                }
            }
            return array
        },
        // 将过滤好的树形数据展开
        setExpandRow(handleTreeData) {
            this.flag = -1
            if (handleTreeData.length) {
                for (let i of handleTreeData) {
                    this.expandRow.push(i.id)
                    if (i.children.length) {
                        this.setExpandRow(i.children)
                    }
                }
            }
        },
        //查询菜单树
        handleQuery() {
            this.resetForm()
            //this.queryParams.queryMode = 'list'
            list().then(response => {
                var data = response.data
                data.splice(0, 1)
                data.forEach(m => {
                    m.addflag = true
                    m.children.forEach(n => {
                        n.addflag = true
                        n.children.forEach(d => {
                            d.addflag = false
                        })
                    })
                })
                this.switchDataVersonName(data)
                this.tableData = data
                var data1 = JSON.stringify(data)
                data1 = JSON.parse(data1)
                data1.push({
                    id: '001',
                    code: 'gen',
                    routeName: null,
                    icon: '1台账管理',
                    title: '根节点',
                    path: '/',
                    pid: '0',
                    remark: '根节点',
                    sort: 100,
                    type: 0,
                    children: []
                })
                this.categoryOptions = data1

                // this.tableData = data
                //console.log("++++++++++++++",data)
                //console.log(this.pageList);
                //this.pagination.total = response.total
                this.loading = false
            })
        },
        // 递归过滤
        switchDataVersonName(data) {
            // column 是表格数据， text是判断是否是含税//  先过滤第一层
            let arr = data.filter(item => !item.type == 1) // 得到新的数组，但只是第一层的过滤，需要再次循环然后 判断有children的时候 在调用一次本函数 传入 x.children，还有判断条件
            arr.forEach(x => x.children && (x.children = this.switchDataVersonName(x.children))) // 最后把新数组 return 出去
            return arr
        },
        handleReset() {
            this.pagination = {
                page: 1,
                limit: 10,
                total: 0
            }
            this.queryParams.name = undefined
            this.handleQuery()
            this.loadMenuOptions()
        },
        handleRowClick(row) {
            this.rowhang = row
            //row.panduan = false
            const currentRow = JSON.parse(JSON.stringify(row))
            //this.currentRow = currentRow
            // this.form = currentRow
            // this.title = '修改菜单'
            this.$emit('menuClick', row)
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        handleStatusChange(row) {
            const text = row.status === 1 ? '启用' : '停用'
            this.$confirm('确认要"' + text + row.name + '"数据项吗?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(function () {
                    return patch(row.id, 1, { status: row.status })
                })
                .then(() => {
                    this.$message.success(text + '成功')
                })
                .catch(function () {
                    row.status = row.status === 1 ? 0 : 1
                })
        },
        chuligen(data, row) {
            if (data.length) {
                data.forEach(m => {
                    if (m.id == row.pid) {
                        this.treename = m.title
                        // return treename
                    }
                    if (m.children.length) {
                        this.chuligen(m.children, row)
                    }
                })
            }
        },
        chuliadd(data, row) {
            if (data.length) {
                data.forEach(m => {
                    if (m.id == row.id) {
                        this.treename = row.title
                        //return treename
                    }

                    if (m.children.length) {
                        this.chuliadd(m.children, row)
                    }
                    // return
                })
            }
        },
        closemenu() {
            this.resetForm()
            this.dialogVisible = false
        },

        //新增
        menuAdd() {
            this.flagb = false
            this.dialogVisible = true
            this.rowName = '新增菜单'
            this.t = 'add'
            this.treename = '根节点'
            this.formData = {
                code: 'gen',
                icon: '1台账管理',
                name: '',
                path: '',
                pid: '0',
                remark: '',
                sort: '100',
                type: 0
            }
        },
        //行内新增
        menuHandAdd(row) {
            this.rowhang = row
            this.flagb = false
            this.treename = ''
            this.formData.pid = ''
            this.formData.sort == '100'
            this.dialogVisible = true
            this.parentName = row.title
            this.rowName = row.title + '下新增'
            this.t = 'add'
            // if(row.pid =='0'){
            //  this.treename = '根节点'
            // }
            // this.categoryOptions.forEach((m) => {
            //    if(m.id == row.id){
            //     this.treename = row.title
            //    }
            // });
            this.chuliadd(this.categoryOptions, row)
            this.formData = {
                code: 'menu',
                icon: row.icon,
                name: '',
                path: '',
                pid: row.id,
                remark: '',
                sort: '100',
                type: 0
            }
        },
        //行类修改
        handleEdit(row) {
            this.rowhang = row
            this.flagb = false
            this.treename = ''
            this.dialogVisible = true
            if (row.pid == '0') {
                this.treename = '根节点'
            }
            this.chuligen(this.categoryOptions, row)
            // this.categoryOptions.forEach((m) => {
            //    if(m.id == row.pid){
            //     this.treename = m.title
            //    }
            // });
            this.parentName = row.title
            this.rowName = row.title + '修改'
            this.t = 'edit'
            this.formData = {
                id: row.id,
                routeName: row.routeName,
                code: row.code,
                icon: row.icon,
                name: row.title,
                path: row.routePath,
                pid: row.pid,
                remark: row.remark,
                sort: row.sort,
                type: row.type
            }
        },
        //提交
        handleSubmit() {
            this.flagb = true
            if (this.t == 'add') {
                add(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('新增成功')
                        this.flagb = false
                        this.handleQuery()
                        this.dialogVisible = false
                    } else {
                        this.flagb = false
                    }
                })
            }
            if (this.t == 'edit') {
                update(this.formData).then(response => {
                    if (response.code == 'A0000') {
                        this.$message.success('修改成功')
                        this.flagb = false
                        this.handleQuery()
                        this.dialogVisible = false
                    } else {
                        this.flagb = false
                    }
                })
            }
        },
        handleDelete(row) {
            this.rowhang = row
            const ids = [row.id || this.ids].join(',')
            this.$confirm('是否确认删除当前菜单？', '警告', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    var p = {
                        id: row.id
                    }
                    deleteMenu(p).then(response => {
                        if (response.code == 'A0000') {
                            this.$message.success('删除成功')
                            this.handleQuery()
                        }
                    })
                })
                .catch(() => this.$message.info('已取消删除'))
        },
        resetForm() {
            this.form = {
                // visible: 1,
                // parentId: 0,
                // icon: undefined,
                // sort: 1,
                // component: 'Layout',
                // routeName: undefined,
                // routePath: undefined
            }
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
        },
        loadMenuOptions() {
            this.menuOptions = []
            list().then(response => {
                const data = response.data
                this.menuOptions.push({ value: 0, label: '根节点' })
                //  for (var key in data) {
                //    let menuOption = {
                //       value:data[key].functionIndex,
                //       label:data[key].functionName
                //    }
                //   this.menuOptions.push(menuOption)
                //  }

                this.$forceUpdate()
            })
        },
        handleIconSelected(name) {
            this.formData.icon = name
            this.$forceUpdate()
        },
        handleMenuSelect(node) {
            if (node.id == 0) {
                this.form.component = 'Layout'
            } else {
                this.form.component = undefined
            }
        },
        closeDialog() {
            this.resetForm()
            this.dialogVisible = false
            this.dialog = {
                title: undefined,
                visible: false
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../../styles/comStyle.less');
</style>
<style lang="less" scoped>
::v-deep .el-card__body,
.el-main {
    padding: 10px;
    // background: #abacac;
}
::v-deep .svg-icon {
    color: #5a5959;
}
</style>
