#
Junjie
昨天 a637cdb04ab7e0954196ad0d8e7cc24ae22ee93a
src/main/webapp/static/js/permission/permission.js
@@ -1,378 +1,484 @@
var pageCurr;
layui.use(['table','laydate', 'form'], function(){
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;
    var layDate = layui.laydate;
    var form = layui.form;
    // 数据渲染
    tableIns = table.render({
        elem: '#permission',
        headers: {token: localStorage.getItem('token')},
        url: baseUrl+'/permission/list/auth',
        page: true,
        limit: 16,
        limits: [16, 30, 50, 100, 200, 500],
        toolbar: '#toolbar',
        cellMinWidth: 50,
        cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{field: 'id', title: 'ID', sort: true,align: 'center', fixed: 'left', width: 80}
            ,{field: 'name', align: 'center',title: '权限名称'}
            ,{field: 'action', align: 'center',title: '接口地址'}
            ,{field: 'resourceName', align: 'center',title: '所属菜单',event: 'Resource', style: 'text-decoration: underline;cursor:pointer'}
            ,{field: 'status$', align: 'center',title: '状态'}
            ,{fixed: 'right', title:'操作', align: 'center', toolbar: '#operate', width:150}
        ]],
        request: {
            pageName: 'curr',
            pageSize: 'limit'
        },
        parseData: function (res) {
            return {
                'code': res.code,
                'msg': res.msg,
                'count': res.data.total,
                'data': res.data.records
            }
        },
        response: {
            statusCode: 200
        },
        done: function(res, curr, count) {
            if (res.code === 403) {
                top.location.href = baseUrl+"/";
            }
            pageCurr=curr;
            limit();
        }
    });
    // 监听排序事件
    table.on('sort(permission)', function (obj) {
        var searchData = {};
        $.each($('#search-box [name]').serializeArray(), function() {
            searchData[this.name] = this.value;
        });
        searchData['orderByField'] = obj.field;
        searchData['orderByType'] = obj.type;
        tableIns.reload({
            where: searchData,
            page: {
                curr: 1
            },
            done: function (res, curr, count) {
                if (res.code === 403) {
                    top.location.href = baseUrl+"/";
                }
                pageCurr=curr;
                limit();
            }
        });
    });
    // 监听头工具栏事件
    table.on('toolbar(permission)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event) {
            case 'addData':
                layer.open({
                    type: 2,
                    title: '新增',
                    maxmin: true,
                    area: [top.detailWidth, top.detailHeight],
                    shadeClose: false,
                    content: 'permission_detail.html',
                    success: function(layero, index){
                       clearFormVal(layer.getChildFrame('#detail', index));
                        layer.iframeAuto(index);layer.style(index, {top: (($(window).height()-layer.getChildFrame('#data-detail', index).height())/3)+"px"});
                    }
                });
                break;
            case 'refreshData':
                tableIns.reload({
                    page: {
                        curr: pageCurr
                    }
                });
                limit();
                break;
            case 'deleteData':
                var data = checkStatus.data;
                var ids=[];
                data.map(function (track) {
                    ids.push(track.id);
                });
                if (ids.length === 0){
                    layer.msg('请选择数据');
                } else {
                    layer.confirm('确定删除'+(ids.length===1?'此':ids.length)+'条数据吗', function(){
                        $.ajax({
                            url: baseUrl+"/permission/delete/auth",
                            headers: {'token': localStorage.getItem('token')},
                            data: {ids: ids},
                            method: 'POST',
                            traditional:true,
                            success: function (res) {
                                if (res.code === 200){
                                    layer.closeAll();
                                    tableReload(false);
                                } else if (res.code === 403){
                                    top.location.href = baseUrl+"/";
                                } else {
                                    layer.msg(res.msg)
                                }
                            }
                        })
                    });
                }
                break;
            case 'exportData':
                layer.confirm('确定导出Excel吗', {shadeClose: true}, function(){
                    var titles=[];
                    var fields=[];
                    obj.config.cols[0].map(function (col) {
                        if (col.type === 'normal' && col.hide === false && col.toolbar == null) {
                            titles.push(col.title);
                            fields.push(col.field);
                        }
                    });
                    var exportData = {};
                    $.each($('#search-box [name]').serializeArray(), function() {
                        exportData[this.name] = this.value;
                    });
                    var param = {
                        'permission': exportData,
                        'fields': fields
                    };
                    $.ajax({
                        url: baseUrl+"/permission/export/auth",
                        headers: {'token': localStorage.getItem('token')},
                        data: JSON.stringify(param),
                        dataType:'json',
                        contentType:'application/json;charset=UTF-8',
                        method: 'POST',
                        success: function (res) {
                            layer.closeAll();
                            if (res.code === 200) {
                                table.exportFile(titles,res.data,'xls');
                            } else if (res.code === 403) {
                                top.location.href = baseUrl+"/";
                            } else {
                                layer.msg(res.msg)
                            }
                        }
                    });
                });
                break;
        }
    });
    // 监听行工具事件
    table.on('tool(permission)', function(obj){
        var data = obj.data;
        switch (obj.event) {
            // 详情
            case 'detail':
                layer.open({
                    type: 2,
                    title: '详情',
                    maxmin: true,
                    area: [top.detailWidth, top.detailHeight],
                    shadeClose: false,
                    content: 'permission_detail.html',
                    success: function(layero, index){
                        setFormVal(layer.getChildFrame('#detail', index), data, true);
                        top.convertDisabled(layer.getChildFrame('#data-detail :input', index), true);
                        layer.getChildFrame('#data-detail-submit', index).hide();
                        layer.iframeAuto(index);layer.style(index, {top: (($(window).height()-layer.getChildFrame('#data-detail', index).height())/3)+"px"});
                        layero.find('iframe')[0].contentWindow.layui.form.render('select');
                    }
                });
                break;
            // 编辑
            case 'edit':
                layer.open({
                    type: 2,
                    title: '修改',
                    maxmin: true,
                    area: [top.detailWidth, top.detailHeight],
                    shadeClose: false,
                    content: 'permission_detail.html',
                    success: function(layero, index){
                        setFormVal(layer.getChildFrame('#detail', index), data, false);
                        top.convertDisabled(layer.getChildFrame('#data-detail :input', index), false);
                        layer.iframeAuto(index);layer.style(index, {top: (($(window).height()-layer.getChildFrame('#data-detail', index).height())/3)+"px"});
                        layero.find('iframe')[0].contentWindow.layui.form.render('select');
                    }
                });
                break;
            case 'Resource':
                var param = top.reObject(data).resourceId;
                if (param === undefined) {
                    layer.msg("无数据");
                } else {
                   layer.open({
                       type: 2,
                       title: '所属详情',
                       maxmin: true,
                       area: [top.detailHeight, top.detailWidth],
                       shadeClose: false,
                       content: '../resource/resource_detail.html',
                       success: function(layero, index){
                           $.ajax({
                               url: baseUrl+"/resource/"+ param +"/auth",
                               headers: {'token': localStorage.getItem('token')},
                               method: 'GET',
                               success: function (res) {
                                   if (res.code === 200){
                                       setFormVal(layer.getChildFrame('#detail', index), res.data, true);
                                       top.convertDisabled(layer.getChildFrame('#data-detail :input', index), true);
                                       layer.getChildFrame('#data-detail-submit', index).hide();
                                       layer.iframeAuto(index);layer.style(index, {top: (($(window).height()-layer.getChildFrame('#data-detail', index).height())/3)+"px"});
                                       layero.find('iframe')[0].contentWindow.layui.form.render('select');
                                   } else if (res.code === 403){
                                       parent.location.href = "/";
                                   }else {
                                       layer.msg(res.msg)
                                   }
                               }
                           })
                       }
                   });
                }
                break;
        }
    });
    // 数据修改动作
    form.on('submit(edit)', function () {
        var index = layer.load(1, {
            shade: [0.5,'#000'] //0.1透明度的背景
        });
        var data = {
            id: $('#id').val(),
            name: $('#name').val(),
            action: $('#action').val(),
            resourceId: $('#resourceId').val(),
            status: $('#status').val(),
(function () {
    function authHeaders() {
        return {
            token: localStorage.getItem('token') || ''
        };
        $.ajax({
            url: baseUrl+"/permission/edit/auth",
            headers: {'token': localStorage.getItem('token')},
            data: top.reObject(data),
            method: 'POST',
            success: function (res) {
                if (res.code === 200){
                    parent.layer.closeAll();
                    tableReload(true);
                    $("#data-detail :input").each(function () {
                        $(this).val("");
                    });
                } else if (res.code === 403){
                    top.location.href = baseUrl+"/";
                }else {
                    layer.msg(res.msg)
    }
    function isForbidden(res) {
        return res && Number(res.code) === 403;
    }
    function isOk(res) {
        return res && Number(res.code) === 200;
    }
    function normalizeId(value) {
        if (value === null || value === undefined || value === '') {
            return null;
        }
        var numberValue = Number(value);
        return isNaN(numberValue) ? value : numberValue;
    }
    function normalizeNumber(value, fallback) {
        if (value === null || value === undefined || value === '') {
            return fallback;
        }
        var numberValue = Number(value);
        return isNaN(numberValue) ? fallback : numberValue;
    }
    function createPermissionForm() {
        return {
            id: null,
            name: '',
            action: '',
            resourceId: null,
            status: 1
        };
    }
    function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }
    function downloadExcel(filename, headers, rows) {
        var headHtml = headers.map(function (title) {
            return '<th style="mso-number-format:\\@;">' + escapeHtml(title) + '</th>';
        }).join('');
        var bodyHtml = rows.map(function (row) {
            return '<tr>' + row.map(function (cell) {
                return '<td style="mso-number-format:\\@;">' + escapeHtml(cell) + '</td>';
            }).join('') + '</tr>';
        }).join('');
        var workbook = [
            '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">',
            '<head><meta charset="UTF-8"></head>',
            '<body><table border="1"><tr>',
            headHtml,
            '</tr>',
            bodyHtml,
            '</table></body></html>'
        ].join('');
        var blob = new Blob([workbook], {type: 'application/vnd.ms-excel;charset=utf-8;'});
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
    }
    new Vue({
        el: '#app',
        data: function () {
            return {
                loading: false,
                exportLoading: false,
                resourceSearchLoading: false,
                dialogResourceLoading: false,
                tableHeight: Math.max(window.innerHeight - 220, 360),
                tableData: [],
                selection: [],
                pagination: {
                    curr: 1,
                    limit: 16,
                    total: 0
                },
                searchForm: {
                    id: '',
                    resourceId: null
                },
                resourceSearchOptions: [],
                permissionDialog: {
                    visible: false,
                    mode: 'create',
                    readonly: false,
                    submitting: false
                },
                permissionForm: createPermissionForm(),
                permissionRules: {
                    name: [
                        {required: true, message: '请输入权限名称', trigger: 'blur'}
                    ],
                    action: [
                        {required: true, message: '请输入接口地址', trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请选择状态', trigger: 'change'}
                    ]
                },
                dialogResourceOptions: [],
                resourceDetail: {
                    visible: false,
                    data: {}
                }
                layer.close(index);
            }
        })
    });
    // 搜索栏搜索事件
    form.on('submit(search)', function (data) {
        pageCurr = 1;
        tableReload(false);
    });
    // 搜索栏重置事件
    form.on('submit(reset)', function (data) {
        pageCurr = 1;
        clearFormVal($('#search-box'));
        tableReload(false);
    });
    // 时间选择器
});
// 关闭动作
$(document).on('click','#data-detail-close', function () {
    parent.layer.closeAll();
});
function tableReload(child) {
    var searchData = {};
    $.each($('#search-box [name]').serializeArray(), function() {
        searchData[this.name] = this.value;
    });
    (child ? parent.tableIns : tableIns).reload({
        where: searchData,
        page: {
            curr: pageCurr
            };
        },
        done: function (res, curr, count) {
            if (res.code === 403) {
                top.location.href = baseUrl+"/";
            }
            pageCurr=curr;
            if (res.data.length === 0 && count !== 0) {
                tableIns.reload({
                    where: searchData,
                    page: {
                        curr: pageCurr-1
        created: function () {
            this.loadList();
        },
        mounted: function () {
            window.addEventListener('resize', this.handleResize);
        },
        beforeDestroy: function () {
            window.removeEventListener('resize', this.handleResize);
        },
        methods: {
            handleResize: function () {
                this.tableHeight = Math.max(window.innerHeight - 220, 360);
                this.refreshTableLayout();
            },
            handleForbidden: function (res) {
                if (isForbidden(res)) {
                    top.location.href = baseUrl + '/';
                    return true;
                }
                return false;
            },
            refreshTableLayout: function () {
                var vm = this;
                this.$nextTick(function () {
                    if (vm.$refs.dataTable && vm.$refs.dataTable.doLayout) {
                        vm.$refs.dataTable.doLayout();
                    }
                });
                pageCurr -= 1;
            },
            currentQuery: function () {
                return {
                    curr: this.pagination.curr,
                    limit: this.pagination.limit,
                    id: $.trim(this.searchForm.id),
                    resourceId: this.searchForm.resourceId
                };
            },
            loadList: function () {
                var vm = this;
                vm.loading = true;
                $.ajax({
                    url: baseUrl + '/permission/list/auth',
                    method: 'GET',
                    headers: authHeaders(),
                    data: vm.currentQuery(),
                    success: function (res) {
                        vm.loading = false;
                        if (vm.handleForbidden(res)) {
                            return;
                        }
                        if (!isOk(res)) {
                            vm.$message.error(res && res.msg ? res.msg : '权限加载失败');
                            return;
                        }
                        var data = res.data || {};
                        vm.tableData = data.records || [];
                        vm.pagination.total = data.total || 0;
                        vm.selection = [];
                        vm.refreshTableLayout();
                    },
                    error: function () {
                        vm.loading = false;
                        vm.$message.error('权限加载失败');
                    }
                });
            },
            fetchResourceOptions: function (keyword, target) {
                var vm = this;
                var loadingKey = target === 'search' ? 'resourceSearchLoading' : 'dialogResourceLoading';
                vm[loadingKey] = true;
                $.ajax({
                    url: baseUrl + '/resourceQuery/auth',
                    method: 'GET',
                    headers: authHeaders(),
                    data: {
                        condition: keyword || ''
                    },
                    success: function (res) {
                        vm[loadingKey] = false;
                        if (vm.handleForbidden(res)) {
                            return;
                        }
                        if (!isOk(res)) {
                            vm.$message.error(res && res.msg ? res.msg : '菜单查询失败');
                            return;
                        }
                        if (target === 'search') {
                            vm.resourceSearchOptions = res.data || [];
                        } else {
                            vm.dialogResourceOptions = res.data || [];
                        }
                    },
                    error: function () {
                        vm[loadingKey] = false;
                        vm.$message.error('菜单查询失败');
                    }
                });
            },
            searchResourceOptions: function (keyword) {
                this.fetchResourceOptions(keyword, 'search');
            },
            searchDialogResourceOptions: function (keyword) {
                this.fetchResourceOptions(keyword, 'dialog');
            },
            ensureDialogResourceOption: function (id, label) {
                if (!id || !label) {
                    return;
                }
                var exists = this.dialogResourceOptions.some(function (item) {
                    return normalizeId(item.id) === normalizeId(id);
                });
                if (!exists) {
                    this.dialogResourceOptions = [{
                        id: normalizeId(id),
                        value: label
                    }].concat(this.dialogResourceOptions);
                }
            },
            handleSelectionChange: function (rows) {
                this.selection = rows || [];
            },
            handleSearch: function () {
                this.pagination.curr = 1;
                this.loadList();
            },
            handleReset: function () {
                this.searchForm.id = '';
                this.searchForm.resourceId = null;
                this.resourceSearchOptions = [];
                this.pagination.curr = 1;
                this.loadList();
            },
            handleCurrentChange: function (page) {
                this.pagination.curr = page;
                this.loadList();
            },
            handleSizeChange: function (size) {
                this.pagination.limit = size;
                this.pagination.curr = 1;
                this.loadList();
            },
            resetPermissionDialog: function () {
                this.permissionForm = createPermissionForm();
                this.dialogResourceOptions = [];
                var vm = this;
                this.$nextTick(function () {
                    if (vm.$refs.permissionForm) {
                        vm.$refs.permissionForm.clearValidate();
                    }
                });
            },
            openCreateDialog: function () {
                this.permissionDialog.mode = 'create';
                this.permissionDialog.readonly = false;
                this.permissionDialog.visible = true;
                this.resetPermissionDialog();
            },
            openEditDialog: function (row) {
                this.permissionDialog.mode = 'edit';
                this.permissionDialog.readonly = false;
                this.permissionDialog.visible = true;
                this.permissionForm = {
                    id: normalizeId(row.id),
                    name: row.name || '',
                    action: row.action || '',
                    resourceId: normalizeId(row.resourceId),
                    status: normalizeNumber(row.status, 1)
                };
                this.dialogResourceOptions = [];
                this.ensureDialogResourceOption(row.resourceId, row.resourceName);
                var vm = this;
                this.$nextTick(function () {
                    if (vm.$refs.permissionForm) {
                        vm.$refs.permissionForm.clearValidate();
                    }
                });
            },
            openDetailDialog: function (row) {
                this.permissionDialog.mode = 'edit';
                this.permissionDialog.readonly = true;
                this.permissionDialog.visible = true;
                this.permissionForm = {
                    id: normalizeId(row.id),
                    name: row.name || '',
                    action: row.action || '',
                    resourceId: normalizeId(row.resourceId),
                    status: normalizeNumber(row.status, 1)
                };
                this.dialogResourceOptions = [];
                this.ensureDialogResourceOption(row.resourceId, row.resourceName);
                var vm = this;
                this.$nextTick(function () {
                    if (vm.$refs.permissionForm) {
                        vm.$refs.permissionForm.clearValidate();
                    }
                });
            },
            submitPermission: function () {
                var vm = this;
                if (!vm.$refs.permissionForm) {
                    return;
                }
                vm.$refs.permissionForm.validate(function (valid) {
                    if (!valid) {
                        return false;
                    }
                    vm.permissionDialog.submitting = true;
                    $.ajax({
                        url: baseUrl + '/permission/' + (vm.permissionDialog.mode === 'create' ? 'add' : 'update') + '/auth',
                        method: 'POST',
                        headers: authHeaders(),
                        data: {
                            id: vm.permissionDialog.mode === 'edit' ? normalizeId(vm.permissionForm.id) : null,
                            name: $.trim(vm.permissionForm.name),
                            action: $.trim(vm.permissionForm.action),
                            resourceId: normalizeId(vm.permissionForm.resourceId),
                            status: normalizeNumber(vm.permissionForm.status, 1)
                        },
                        success: function (res) {
                            vm.permissionDialog.submitting = false;
                            if (vm.handleForbidden(res)) {
                                return;
                            }
                            if (!isOk(res)) {
                                vm.$message.error(res && res.msg ? res.msg : '保存失败');
                                return;
                            }
                            vm.$message.success(res.msg || '保存成功');
                            vm.permissionDialog.visible = false;
                            vm.loadList();
                        },
                        error: function () {
                            vm.permissionDialog.submitting = false;
                            vm.$message.error('保存失败');
                        }
                    });
                    return true;
                });
            },
            removeSelection: function () {
                var vm = this;
                if (!vm.selection.length) {
                    vm.$message.warning('请选择数据');
                    return;
                }
                var ids = vm.selection.map(function (row) {
                    return normalizeId(row.id);
                }).filter(function (id) {
                    return id !== null;
                });
                vm.$confirm('确定删除选中权限吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    $.ajax({
                        url: baseUrl + '/permission/delete/auth',
                        method: 'POST',
                        headers: authHeaders(),
                        traditional: true,
                        data: {
                            ids: ids
                        },
                        success: function (res) {
                            if (vm.handleForbidden(res)) {
                                return;
                            }
                            if (!isOk(res)) {
                                vm.$message.error(res && res.msg ? res.msg : '删除失败');
                                return;
                            }
                            vm.$message.success(res.msg || '删除成功');
                            if (vm.tableData.length === ids.length && vm.pagination.curr > 1) {
                                vm.pagination.curr -= 1;
                            }
                            vm.loadList();
                        },
                        error: function () {
                            vm.$message.error('删除失败');
                        }
                    });
                }).catch(function () {
                });
            },
            exportRows: function () {
                var vm = this;
                vm.exportLoading = true;
                $.ajax({
                    url: baseUrl + '/permission/export/auth',
                    method: 'POST',
                    headers: authHeaders(),
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({
                        permission: {
                            id: $.trim(vm.searchForm.id),
                            resourceId: vm.searchForm.resourceId
                        },
                        fields: ['id', 'name', 'action', 'resourceName', 'status$']
                    }),
                    success: function (res) {
                        vm.exportLoading = false;
                        if (vm.handleForbidden(res)) {
                            return;
                        }
                        if (!isOk(res)) {
                            vm.$message.error(res && res.msg ? res.msg : '导出失败');
                            return;
                        }
                        downloadExcel('权限管理.xls', ['ID', '权限名称', '接口地址', '所属菜单', '状态'], res.data || []);
                    },
                    error: function () {
                        vm.exportLoading = false;
                        vm.$message.error('导出失败');
                    }
                });
            },
            openResourceDetail: function (row) {
                var vm = this;
                if (!row.resourceId) {
                    vm.$message.warning('无所属菜单');
                    return;
                }
                $.ajax({
                    url: baseUrl + '/resource/' + row.resourceId + '/auth',
                    method: 'GET',
                    headers: authHeaders(),
                    success: function (res) {
                        if (vm.handleForbidden(res)) {
                            return;
                        }
                        if (!isOk(res)) {
                            vm.$message.error(res && res.msg ? res.msg : '菜单详情加载失败');
                            return;
                        }
                        vm.resourceDetail.data = res.data || {};
                        vm.resourceDetail.visible = true;
                    },
                    error: function () {
                        vm.$message.error('菜单详情加载失败');
                    }
                });
            }
            limit(child);
        }
    });
}
function setFormVal(el, data, showImg) {
    for (var val in data) {
        var find = el.find(":input[id='" + val + "']");
        find.val(data[val]);
        if (showImg){
            var next = find.next();
            if (next.get(0)){
                if (next.get(0).localName === "img") {
                    find.hide();
                    next.attr("src", data[val]);
                    next.show();
        },
        watch: {
            'permissionDialog.visible': function (visible) {
                if (!visible) {
                    this.permissionDialog.submitting = false;
                    this.permissionDialog.readonly = false;
                    this.resetPermissionDialog();
                }
            },
            'resourceDetail.visible': function (visible) {
                if (!visible) {
                    this.resourceDetail.data = {};
                }
            }
        }
    }
}
function clearFormVal(el) {
    $(':input', el)
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
}
function detailScreen(index) {
    var detail = layer.getChildFrame('#data-detail', index);
    var height = detail.height()+60;
    if (height > ($(window).height()*0.9)) {
        height = ($(window).height()*0.9);
    }
    layer.style(index, {
        top: (($(window).height()-height)/3)+"px",
        height: height+'px'
    });
    $(".layui-layer-shade").remove();
}
$('body').keydown(function () {
    if (event.keyCode === 13) {
        $("#search").click();
    }
});
})();