var $table = $('#tbUser');
var $formUserInfo;
var $deluser = $('#BtnDelUser');
var EditUserID;
$(document).ready(function () {
$('#tab_2').hide();
$deluser.prop("disabled", true);
$('input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-green'
});
$(window).bind("load resize", HandleBoxHeight);
SetBoxHeight();
new TableInit().Init();
//var objTbini = new TableInit();
//objTbini.Init();
//$("#UserModal").on("hidden.bs.modal", function () {
// $(this).removeData();
//});
iniInputValition();
//Mock.mock(/\.json/, {
// 'list|1-10': [{
// 'id|+1': 1,
// 'email': '@EMAIL'
// }]
//})
//fetchMock.mock('*', { res: "hello world" })
//fetchMock.mock(/^(\/api\/Administration\/QueryRole)/, Mock.mock({
// 'roles': [{
// 'id': 1,
// 'value': 'Adminstrator'
// }, { 'id': 2, 'value': 'Operator' }]
//}));
//fetchMock.mock(/^(\/api\/Administration\/)/, Mock.mock({
// 'list|1-10': [{
// 'id|+1': 1,
// 'email': '@EMAIL'
// }]
//}));
});
function getIdSelections() {
return $.map($table.bootstrapTable('getSelections'), function (row) {
return row.UserId
})
}
function getRoleIDs() {
var ids=[]
$('.cbxRole').each(function (i, obj) {
if ($(this).iCheck('update')[0].checked == true) {
ids.push($(this).val())
}
});
return ids
}
$('#btnSave').on('click', function () {
//$.ajax({
// url: 'hello.json',
// dataType: 'json'
//}).done(function (data, status, jqXHR) {
// console.log(data)
// })
//fetch("/hello.json").then(function (res) {
// return res.json();
//}).then(function (res) {
// console.log(res);
//})
//return;
if ($formUserInfo.form() == false) {
toastr.warning("请输入内容", '', { progressBar: true });
return;
}
//角色数组
var roleids = getRoleIDs()
//提交数据
fetch("../api/Permission/AddUser", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
'Content-Type': 'application/json'
},
body: JSON.stringify({ password:$('#txtPassword').val(),username: $('#txtUsername').val(), displayname: $('#txtDisplayname').val(), workshop: $('#txtWorkshop').val(), roleids: roleids })
}).then(function (res) {
return res.json();
}).then(function (res) {
if (res.result == "success") {
toastr.success("添加成功", '', { progressBar: true });
console.log("added");
//清楚模态框内容
ClearModel();
//刷新表格
new TableInit().Init();
//关闭模态窗
$('#UserModal').modal('hide')
}
else {
toastr.error(res.msg,"添加失败", { progressBar: true });
}
}).catch(function (ex) {
console.log('request failed', ex);
toastr.error(ex, '', { progressBar: true });
})
})
$('#btnEditSave').on('click', function () {
EditUser(EditUserID, $('#txtUsername').val(), $('#txtDisplayname').val(), getRoleIDs())
})
$('#BtnDelUser').on('click', function () {
var ids = getIdSelections();
DelUser(ids)
})
$('#BtnAddUser').on('click', function () {
$('#btnSave').show()
$('#btnEditSave').hide()
ClearModel();
$('#UserModal').modal({ backdrop: 'static', keyboard: false });
QueryRole([]);
})
function DelUser(userids) {
fetch("/api/Permission/DelUser", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({ userids: userids })
}).then(function (res) {
return res.json()
}).then(function (res) {
if (res.result == "success") {
toastr.success("删除成功", '', { progressBar: true });
//刷新表格
new TableInit().Init();
}
else {
toastr.error(res.msg, '删除失败', { progressBar: true });
}
}).catch(function (ex) {
console.log('request failed', ex);
})
}
$('#user').click(function () {
$('#tab_2').hide();
})
$('#role').click(function () {
$('#tab_2').show();
})
function QueryRole(userids) {
fetch("../api/Permission/QueryRole", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({ userid: -1 })
}).then(function (res) {
return res.json()
}).then(function (res) {
//清除角色元素
$('#tab_2').empty();
_.each(res.info, function (ele, index, list) {
$('#tab_2').append(' ')
})
$('#tab_2 input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-green'
});
//toastr.success("删除成功", '', { progressBar: true });
//刷新表格
//new TableInit().Init();
}).catch(function (ex) {
console.log('request failed', ex);
})
}
function EditQueryRole(userid) {
fetch("../api/Permission/QueryRole", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({ userid: -1 })
}).then(function (res) {
return res.json()
}).then(function (res) {
//清除角色元素
$('#tab_2').empty();
_.each(res.info, function (ele, index, list) {
$('#tab_2').append(' ')
})
$('#tab_2 input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-green'
});
//查询需要修改的用户的角色
return fetch("../api/Permission/QueryRole", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify({ userid: EditUserID })
})
}).then(function (response) {
return response.json()
}).then(function (data) {
//将用户的角色选中
_.each(data.info, function (ele, index, list) {
$('.cbxRole').each(function (i, obj) {
if ($(this).val() == ele.RoleId) {
$(this).iCheck('check')
}
});
})
console.log(data)
//查询用户信息
return FetchApi("GetInfo", { userid: EditUserID })
}).then(function (response) {
return response.json()
}).then(function (data) {
$('#txtPassword').val(data.info.Password)
}).catch (function (ex) {
console.log('request failed', ex);
})
}
function FetchApi(funname,para) {
return fetch("../api/Permission/"+funname+"", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify(para)
})
}
function ClearModel() {
$('#formUserInfo input[type="text"]').val("")
$('#tab_2').empty()
//$('.divRole ')
}
function iniInputValition() {
$formUserInfo = $('#formUserInfo').validate({
ignore: "",
//onfocusout: false,
rules: {
'txtUsername': { required: true },
'txtDisplayname': { required: true },
'txtWorkshop': { required: true },
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
// Add the `help-block` class to the error element
error.addClass("help-block");
console.log(element);
//element.prop("type") === "select"
if (element.is('select') == true) {
error.insertAfter(element.next());
console.log(element.next());
} else {
error.insertAfter(element);
}
},
highlight: function (element, errorClass, validClass) {
//$(element).parents(".form-group").addClass("has-error").removeClass("has-success");
$(element).parents(".form-group").addClass("has-error");
},
unhighlight: function (element, errorClass, validClass) {
//$(element).parents(".form-group").addClass("has-success").removeClass("has-error");
$(element).parents(".form-group").removeClass("has-error");
}
}
);
}
function HandleBoxHeight() {
var resize1;
$(window).resize(function () {
if (resize1) {
clearTimeout(resize1);
}
resize1 = setTimeout(function () {
//_runResizeHandlers();
SetBoxHeight();
//handleIframeContent();
}, 100); // wait 50ms until window resize finishes.
});
}
function SetBoxHeight() {
var height = window["innerHeight"] - $('.content-header').outerHeight() - 60;
//var aaa = window["innerHeight"];
$('.box.box-primary .user').css("min-height", height + "px");
}
var TableInit = function () {
var oTableInit = new Object();
//初始化Table
oTableInit.Init = function () {
$table.bootstrapTable('destroy').bootstrapTable({
url: '../api/Permission/GetInfo', //请求后台的URL(*)
method: 'post', //请求方式(*)
toolbar: '#tlb', //工具按钮用哪个容器
//buttonsToolbar:'#t1',
striped: true, //是否显示行间隔色
cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination: true, //是否显示分页(*)
sortable: false, //是否启用排序
sortOrder: "asc", //排序方式
queryParams: oTableInit.queryParams,//传递参数(*)
sidePagination: "client", //分页方式:client客户端分页,server服务端分页(*)
contentType: 'application/json',
pageNumber: 1, //初始化加载第一页,默认第一页
pageSize: 11, //每页的记录行数(*)
pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
strictSearch: true,
showColumns: true, //是否显示所有的列
showRefresh: true, //是否显示刷新按钮
minimumCountColumns: 2, //最少允许的列数
clickToSelect: true, //是否启用点击选中行
//height: 500, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
//uniqueId: "aiid", //每一行的唯一标识,一般为主键列
showToggle: true, //是否显示详细视图和列表视图的切换按钮
cardView: false, //是否显示详细视图
detailView: false, //是否显示父子表
showExport: true, //是否显示导出
exportDataType: "all", //basic', 'all', 'selected'.
exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel'],
exportHiddenCells: true,
//onLoadSuccess: function (data) {
// var data = $('#tbqc').bootstrapTable('getData', true);
// //合并单元格
// mergeCells(data, "serial_nbr", 1, $('#tbqc'));
// mergeCells(data, "schedule_nbr", 1, $('#tbqc'));
//},
columns: [{
checkbox: true
}, {
field: 'UserId',
title: 'ID'
}, {
field: 'Username',
title: '用户名'
}, {
field: 'DisplayName',
title: '显示名称'
},
{
field: 'workshop',
title: '车间'
},
{
field: 'Createtime',
title: '创建时间'
}, {
field: 'operate',
title: 'Item Operate',
align: 'center',
events: window.operateEvents,
formatter: operateFormatter
}
]
});
};
function operateFormatter(value, row, index) {
return [
'',
'',
' ',
'',
'',
''
].join('')
}
window.operateEvents = {
'click .like': function (e, value, row, index) {
//alert('You click like action, row: ' + JSON.stringify(row))
EditUserID = row.UserId
ClickEditUser(row.Username, row.DisplayName, row.workshop)
},
'click .remove': function (e, value, row, index) {
$table.bootstrapTable('remove', {
field: 'UserId',
values: [row.UserId]
})
}
}
//得到查询的参数
oTableInit.queryParams = function (params) {
var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
limit: params.limit, //页面大小
offset: params.offset, //页码
username: $('#txtUser').val(),
};
return temp;
};
return oTableInit;
};
function ClickEditUser(username, displayname, workshop) {
$('#btnSave').hide()
$('#btnEditSave').show()
$('#txtUsername').val(username)
$('#txtDisplayname').val(displayname)
$('#txtWorkshop').val(workshop)
//QueryRole(EditUserID)
EditQueryRole(EditUserID)
$('#UserModal').modal({ backdrop: 'static', keyboard: false });
}
function EditUser(userid, username, displayname, roleids) {
fetch("../api/Permission/EditUser", {
method: "post",
headers: {
"Accept": "application/json, text/plain, */*",
'Content-Type': 'application/json'
},
body: JSON.stringify({ password:$('#txtPassword').val(), userid: EditUserID, username: $('#txtUsername').val(), displayname: $('#txtDisplayname').val(), workshop: $('#txtWorkshop').val(), roleids: roleids })
}).then(function (res) {
return res.json();
}).then(function (res) {
if (res.result == "success") {
toastr.success("修改成功", '', { progressBar: true });
console.log("edited");
//清楚模态框内容
ClearModel();
//刷新表格
new TableInit().Init();
//关闭模态窗
$('#UserModal').modal('hide')
}
else {
toastr.error("修改失败", '', { progressBar: true });
}
}).catch(function (ex) {
console.log('request failed', ex);
})
}
$table.on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table',
function () {
$('#BtnDelUser').prop('disabled', !$table.bootstrapTable('getSelections').length)
// save your data, here just save the current page
//selections = getIdSelections()
// push or splice the selections if you want to save all data selections
})
$('#btntest').on('click', function () {
console.log('pressed')
$('#tab_2').append(' ')
$('input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-green'
});
})