(function () {
function authHeaders() {
return {
token: localStorage.getItem('token') || ''
};
}
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 createRoleForm() {
return {
id: null,
code: '',
name: '',
leader: null
};
}
function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function downloadExcel(filename, headers, rows) {
var headHtml = headers.map(function (title) {
return '
' + escapeHtml(title) + ' | ';
}).join('');
var bodyHtml = rows.map(function (row) {
return '' + row.map(function (cell) {
return '| ' + escapeHtml(cell) + ' | ';
}).join('') + '
';
}).join('');
var workbook = [
'',
'',
'',
headHtml,
'
',
bodyHtml,
'
'
].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,
leaderSearchLoading: false,
dialogLeaderLoading: false,
tableHeight: Math.max(window.innerHeight - 220, 360),
tableData: [],
selection: [],
pagination: {
curr: 1,
limit: 16,
total: 0
},
searchForm: {
leader: null
},
leaderSearchOptions: [],
roleDialog: {
visible: false,
mode: 'create',
submitting: false
},
roleForm: createRoleForm(),
roleRules: {
code: [
{required: true, message: '请输入编码', trigger: 'blur'}
],
name: [
{required: true, message: '请输入名称', trigger: 'blur'}
]
},
dialogLeaderOptions: [],
powerDialog: {
visible: false,
roleId: null,
roleName: '',
loading: false,
submitting: false
},
powerTreeData: [],
powerExpandedKeys: []
};
},
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();
}
});
},
currentQuery: function () {
return {
curr: this.pagination.curr,
limit: this.pagination.limit,
leader: this.searchForm.leader
};
},
loadList: function () {
var vm = this;
vm.loading = true;
$.ajax({
url: baseUrl + '/role/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('角色加载失败');
}
});
},
fetchRoleOptions: function (keyword, target) {
var vm = this;
var loadingKey = target === 'search' ? 'leaderSearchLoading' : 'dialogLeaderLoading';
vm[loadingKey] = true;
$.ajax({
url: baseUrl + '/roleQuery/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.leaderSearchOptions = res.data || [];
} else {
vm.dialogLeaderOptions = res.data || [];
}
},
error: function () {
vm[loadingKey] = false;
vm.$message.error('角色查询失败');
}
});
},
searchLeaderOptions: function (keyword) {
this.fetchRoleOptions(keyword, 'search');
},
searchDialogLeaderOptions: function (keyword) {
this.fetchRoleOptions(keyword, 'dialog');
},
ensureDialogLeaderOption: function (id, label) {
if (!id || !label) {
return;
}
var exists = this.dialogLeaderOptions.some(function (item) {
return normalizeId(item.id) === normalizeId(id);
});
if (!exists) {
this.dialogLeaderOptions = [{
id: normalizeId(id),
value: label
}].concat(this.dialogLeaderOptions);
}
},
handleSelectionChange: function (rows) {
this.selection = rows || [];
},
handleSearch: function () {
this.pagination.curr = 1;
this.loadList();
},
handleReset: function () {
this.searchForm.leader = null;
this.leaderSearchOptions = [];
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();
},
resetRoleDialog: function () {
this.roleForm = createRoleForm();
this.dialogLeaderOptions = [];
var vm = this;
this.$nextTick(function () {
if (vm.$refs.roleForm) {
vm.$refs.roleForm.clearValidate();
}
});
},
openCreateDialog: function () {
this.roleDialog.mode = 'create';
this.roleDialog.visible = true;
this.resetRoleDialog();
},
openEditDialog: function (row) {
this.roleDialog.mode = 'edit';
this.roleDialog.visible = true;
this.roleForm = {
id: normalizeId(row.id),
code: row.code || '',
name: row.name || '',
leader: normalizeId(row.leader)
};
this.dialogLeaderOptions = [];
this.ensureDialogLeaderOption(row.leader, row['leader$']);
var vm = this;
this.$nextTick(function () {
if (vm.$refs.roleForm) {
vm.$refs.roleForm.clearValidate();
}
});
},
submitRole: function () {
var vm = this;
if (!vm.$refs.roleForm) {
return;
}
vm.$refs.roleForm.validate(function (valid) {
if (!valid) {
return false;
}
vm.roleDialog.submitting = true;
$.ajax({
url: baseUrl + '/role/' + (vm.roleDialog.mode === 'create' ? 'add' : 'update') + '/auth',
method: 'POST',
headers: authHeaders(),
data: {
id: vm.roleDialog.mode === 'edit' ? normalizeId(vm.roleForm.id) : null,
code: $.trim(vm.roleForm.code),
name: $.trim(vm.roleForm.name),
leader: normalizeId(vm.roleForm.leader)
},
success: function (res) {
vm.roleDialog.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.roleDialog.visible = false;
vm.loadList();
},
error: function () {
vm.roleDialog.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 + '/role/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 + '/role/export/auth',
method: 'POST',
headers: authHeaders(),
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify({
role: {
leader: vm.searchForm.leader
},
fields: ['id', 'code', 'name', 'leader$']
}),
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('导出失败');
}
});
},
ensurePowerTree: function (callback) {
var vm = this;
if (vm.powerTreeData.length) {
if (callback) {
callback();
}
return;
}
$.ajax({
url: baseUrl + '/power/list/auth',
method: 'GET',
headers: authHeaders(),
success: function (res) {
if (vm.handleForbidden(res)) {
vm.powerDialog.loading = false;
return;
}
if (!isOk(res)) {
vm.powerDialog.loading = false;
vm.$message.error(res && res.msg ? res.msg : '权限树加载失败');
return;
}
vm.powerTreeData = res.data || [];
vm.powerExpandedKeys = [];
if (callback) {
callback();
}
},
error: function () {
vm.powerDialog.loading = false;
vm.$message.error('权限树加载失败');
}
});
},
loadRolePower: function () {
var vm = this;
vm.powerDialog.loading = true;
$.ajax({
url: baseUrl + '/power/' + vm.powerDialog.roleId + '/auth',
method: 'GET',
headers: authHeaders(),
success: function (res) {
vm.powerDialog.loading = false;
if (vm.handleForbidden(res)) {
return;
}
if (!isOk(res)) {
vm.$message.error(res && res.msg ? res.msg : '权限回显失败');
return;
}
vm.$nextTick(function () {
if (vm.$refs.powerTree) {
vm.$refs.powerTree.setCheckedKeys(res.data || []);
}
});
},
error: function () {
vm.powerDialog.loading = false;
vm.$message.error('权限回显失败');
}
});
},
openPowerDialog: function (row) {
var vm = this;
vm.powerDialog.visible = true;
vm.powerDialog.roleId = normalizeId(row.id);
vm.powerDialog.roleName = row.name || '';
vm.powerDialog.loading = true;
vm.ensurePowerTree(function () {
vm.$nextTick(function () {
if (vm.$refs.powerTree) {
vm.$refs.powerTree.setCheckedKeys([]);
}
vm.loadRolePower();
});
});
},
collectPowerPayload: function () {
var tree = this.$refs.powerTree;
if (!tree) {
return [];
}
var selected = tree.getCheckedKeys().concat(tree.getHalfCheckedKeys());
var selectedMap = {};
selected.forEach(function (key) {
selectedMap[key] = true;
});
var payload = [];
this.powerTreeData.forEach(function (top) {
(top.children || []).forEach(function (node) {
var childList = node.children || [];
var checkedChildren = childList.filter(function (child) {
return !!selectedMap[child.id];
}).map(function (child) {
return String(child.id);
});
if (childList.length === 0) {
if (selectedMap[node.id]) {
payload.push({
two: node.id,
three: []
});
}
return;
}
if (selectedMap[node.id] || checkedChildren.length > 0) {
payload.push({
two: node.id,
three: checkedChildren
});
}
});
});
return payload;
},
submitPower: function () {
var vm = this;
vm.powerDialog.submitting = true;
$.ajax({
url: baseUrl + '/power/auth',
method: 'POST',
headers: authHeaders(),
traditional: true,
data: {
roleId: vm.powerDialog.roleId,
powers: JSON.stringify(vm.collectPowerPayload())
},
success: function (res) {
vm.powerDialog.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.powerDialog.visible = false;
},
error: function () {
vm.powerDialog.submitting = false;
vm.$message.error('权限保存失败');
}
});
}
},
watch: {
'roleDialog.visible': function (visible) {
if (!visible) {
this.resetRoleDialog();
this.roleDialog.submitting = false;
}
},
'powerDialog.visible': function (visible) {
if (!visible) {
this.powerDialog.roleId = null;
this.powerDialog.roleName = '';
this.powerDialog.loading = false;
this.powerDialog.submitting = false;
if (this.$refs.powerTree) {
this.$refs.powerTree.setCheckedKeys([]);
}
}
}
}
});
})();