define(['jquery', 'layui'], function($, layui) {
var table = layui.table,
laydate = layui.laydate,
laytpl = layui.laytpl,
form = layui.form,
tabs = layui.tabs;
var Table = {
extend: {
table_elem: '#currentTable',
table_render_id: 'currentTable',
add_url: "",
edit_url: "",
delete_url: "",
multi_url: '',
dragsort_url: '',
},
config: {
//refreshbtn: '.btn-refresh',
//addbtn: '.btn-add',
//editbtn: '.btn-edit',
//delbtn: '.btn-del',
//multibtn: '.btn-multi',
//restoreonebtn: '.btn-restoreone',
//destroyonebtn: '.btn-destroyone',
//restoreallbtn: '.btn-restoreall',
//destroyallbtn: '.btn-destroyall',
disabledbtn: '.btn-disabled',
dragsortfield: 'listorder',
},
api: {
bindevent: function(tableId) {
var tableId = tableId || Table.init.table_render_id;
var options = layui.table.getOptions(tableId);
options.layFilter = options.layFilter || options.id;
//监听表格复选框选择
Table.listenCheckboxEvent(options);
//监听顶部工具栏
Table.listenToolbarEvent(options);
//监听单元格元素事件(编辑和删除)
Table.listenToolEvent(options);
// 监听表格文本框编辑
Table.listenEditEvent(options);
// 监听tab切换
Table.listenTabShowEvent(options);
// 监听表格开关切换
Table.listenSwitch(options);
},
// 批量操作请求
multi: function(action, ids, tableId, element) {
var options = layui.table.getOptions(tableId);
var data = element ? $(element).data() : {};
ids = $.isArray(ids) ? ids : [ids];
var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.init.delete_url : options.init.multi_url);
var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
options = { url: url, data: { action: action, id: ids, param: params } };
Yzn.api.ajax(options, function(data, ret) {
var success = $(element).data("success") || $.noop;
if (typeof success === 'function') {
if (false === success.call(element, data, ret)) {
return false;
}
}
tableId && table.reload(tableId);
}, function(data, ret) {
var error = $(element).data("error") || $.noop;
if (typeof error === 'function') {
if (false === error.call(element, data, ret)) {
return false;
}
}
});
},
// 获取选中的条目ID集合
selectedids: function(tableId, current) {
var options = layui.table.getOptions(tableId);
var checkStatus;
if (options.tree) {
checkStatus = layui.treeTable.checkStatus(tableId);
} else {
checkStatus = table.checkStatus(tableId);
}
var data = checkStatus.data;
var ids = [];
$.each(data, function(i, v) {
ids.push(v[options.pk]);
});
return ids;
},
// 获取选中的数据
selecteddata: function(tableId, current) {
var options = layui.table.getOptions(tableId);
var checkStatus;
if (options.tree) {
checkStatus = layui.treeTable.checkStatus(tableId);
} else {
checkStatus = table.checkStatus(tableId);
}
var data = checkStatus.data;
var arr = [];
$.each(data, function(i, v) {
arr.push(v);
});
return arr;
},
//替换URL中的数据
toolSpliceUrl: function(url, data) {
data.id = typeof data.id !== 'undefined' ? data.id : 0;
url = url == null || url.length === 0 ? '' : url.toString();
//自动添加id参数
url = !url.match(/(?=([?&]id=)|(\/id\/)|(\{id}))/i) ?
url + (url.match(/(\?|&)+/) ? "&id=" : "?id=") + '{id}' : url;
url = url.replace(/\{(.*?)\}/gi, function(matched) {
matched = matched.substring(1, matched.length - 1);
var temp = matched.split('.').reduce(function (obj, key) {
return obj === null || obj === undefined ? '' : obj[key];
}, data);
temp = layui.util.escape(temp);
return temp;
});
return url;
},
},
render: function(options) {
options.init = $.extend(true, {}, Table.extend, options.init);
options.modifyReload = Yzn.api.parame(options.modifyReload, false);
options.id = options.id || options.init.table_render_id;
options.pk = options.pk || 'id';
options.elem = options.elem || options.init.table_elem;
options.cols = options.cols || [];
options.layFilter = options.id + '_LayFilter';
options.searchFieldsetId = 'searchFieldset_' + options.id;
options.tabsId = 'tabs_' + options.id;
options.url = Yzn.api.fixurl(options.url || options.init.index_url);
options.search = Yzn.api.parame(options.search, true);
options.showSearch = Yzn.api.parame(options.showSearch, true);
options.renderDefault = Yzn.api.parame(options.renderDefault, false);
options.searchFormVisible = Yzn.api.parame(options.searchFormVisible, false);
options.searchFormTpl = Yzn.api.parame(options.searchFormTpl || options.init.searchFormTpl, false);
options.defaultToolbar = options.defaultToolbar || ['filter', 'print', 'exports'];
options.searchColumns = [];
if (options.search && options.showSearch) {
options.defaultToolbar.push({
title: '搜索',
layEvent: 'TABLE_SEARCH',
icon: 'layui-icon-search',
extend: 'data-table-id="' + options.id + '"'
})
}
options.even = Yzn.api.parame(options.even, true);
// 判断是否为移动端
if (Yzn.api.checkMobile()) {
options.defaultToolbar = !options.search ? ['filter'] : ['filter', {
title: '搜索',
layEvent: 'TABLE_SEARCH',
icon: 'layui-icon-search',
extend: 'data-table-id="' + options.id + '"'
}];
}
options.searchInput = options.search ? Yzn.api.parame(options.searchInput, true) : false;
// 判断元素对象是否有嵌套的
options.cols = Table.formatCols(options.cols, options.init);
// 初始化表格lay-filter
$(options.elem).attr('lay-filter', options.layFilter);
//自定义搜索
if (options.search === true && options.searchFormTpl !== false) {
data = options.tpldata || {}
laytpl($('#' + options.searchFormTpl).html()).render(data, function(html) {
$(options.elem).before(html);
Table.listenTableSearch(options.id);
})
// 初始化form表单
form.render();
}
// 初始化表格搜索
if (options.search === true && options.searchFormTpl === false) {
Table.renderSearch(options);
}
// 初始化表格左上方工具栏
if(options.toolbar === 'default'){
options.toolbar = ['refresh', 'add', 'delete', 'export'];
}
options.toolbar = typeof options.toolbar === 'object' ? Table.renderToolbar(options) : options.toolbar;
options.before = Table.wrapEvent(options.before, Table.before);
options.done = Table.wrapEvent(options.done, Table.done);
if(options.tree){
options.tree.view = options.tree.view || {};
// 设置默认图标
if (!options.tree.view.flexIconOpen) {
options.tree.view.flexIconOpen = 'layui-icon layui-icon-subtraction layui-table-cell-expand-icon';
}
if (!options.tree.view.flexIconClose) {
options.tree.view.flexIconClose = 'layui-icon layui-icon-addition layui-table-cell-expand-icon';
}
var newTable = layui.treeTable.render(options);
}else{
var newTable = table.render(options);
}
return newTable;
},
wrapEvent: function(original, wrapper) {
return original
? function () {
wrapper.apply(this, arguments);
original.apply(this, arguments);
}
: wrapper;
},
renderToolbar: function(options) {
var d = options.toolbar,
tableId = options.id,
searchInput = options.searchInput,
elem = options.elem,
init = options.init;
d = d || [];
var toolbarHtml = '';
$.each(d, function(i, v) {
if (v === 'refresh') {
toolbarHtml += ' \n';
} else if (v === 'add') {
if (Yzn.api.checkAuth('add', elem)) {
toolbarHtml += ' 添加\n';
}
} else if (v === 'edit') {
if (Yzn.api.checkAuth('edit', elem)) {
toolbarHtml += ' 编辑\n';
}
} else if (v === 'delete') {
if (Yzn.api.checkAuth('delete', elem)) {
toolbarHtml += ' 删除\n';
}
} else if (v === 'recyclebin') {
if (Yzn.api.checkAuth('recyclebin', elem)) {
toolbarHtml += ' 回收站\n';
}
} else if (v === 'restore') {
if (Yzn.api.checkAuth('restore', elem)) {
toolbarHtml += ' 还原\n';
}
} else if (v === 'destroy') {
if (Yzn.api.checkAuth('destroy', elem)) {
toolbarHtml += ' 销毁\n';
}
} else if (typeof v === "object") {
if (Yzn.api.checkAuth(v.auth, elem)) {
toolbarHtml += Table.buildToolbarHtml(tableId, v);
}
}
});
if (searchInput) {
toolbarHtml += '\n'
}
return '
' + toolbarHtml + '
';
},
buildToolbarHtml: function(tableId, j) {
j.html = j.html || '';
if (j.html !== '') {
return j.html;
}
var hidden, html, url, classname, refresh, extend, text, title, icon;
hidden = typeof j.hidden === 'function' ? j.hidden.call(Table, j) : (typeof j.hidden !== 'undefined' ? j.hidden : false);
if (hidden) {
return '';
}
text = j.text ? j.text : '';
title = j.title ? j.title : text;
icon = j.icon ? j.icon : '';
classname = j.class ? j.class : '';
refresh = j.refresh ? 'data-refresh="' + j.refresh + '"' : '';
url = j.url ? j.url : '';
url = url ? Yzn.api.fixurl(j.url) : 'javascript:;';
extend = typeof j.extend !== 'undefined' ? j.extend : '';
html = '' + (text ? ' ' + text : '') + '\n';
return html;
},
renderSearch: function(options) {
// TODO 只初始化第一个table搜索字段,如果存在多个(绝少数需求),得自己去扩展
var cols = options.cols[0] || {};
var elem = options.elem;
var tableId = options.id;
var searchFormVisible = options.searchFormVisible;
var newCols = [];
var formHtml = '';
$.each(cols, function(i, d) {
d.field = d.field || false;
d.search = Yzn.api.parame(d.search, true);
if (d.field !== false && d.search !== false) {
var query = Yzn.api.query(d.field);
var renderDefault = options.renderDefault && (typeof d.renderDefault == 'undefined' || d.renderDefault);
d.searchValue = renderDefault && query ? query : (typeof d.searchValue === 'undefined' ? '' : d.searchValue);
d.fieldAlias = Yzn.api.parame(d.fieldAlias, d.field);
d.title = d.title || d.field || '';
d.selectList = d.selectList || {};
d.searchTip = d.searchTip || '请输入' + d.title || '';
d.searchOp = d.searchOp || 'eq';
d.timeType = d.timeType || 'datetime';
d.extend = typeof d.extend === 'undefined' ? '' : d.extend;
d.addClass = typeof d.addClass === 'undefined' ? (typeof d.addclass === 'undefined' ? 'layui-input' : 'layui-input ' + d.addclass) : 'layui-input ' + d.addClass;
options.searchColumns.push(d);
switch (d.search) {
case true:
formHtml += '\t';
break;
case 'select':
var selectHtml = '';
$.each(d.selectList, function(sI, sV) {
var selected = '';
if (sI === d.searchValue) {
selected = 'selected=""';
}
selectHtml += '/n';
});
formHtml += '\t';
break;
case 'range':
d.searchOp = 'range';
formHtml += '\t';
break;
case 'between':
d.searchOp = 'BETWEEN';
formHtml += '\t';
break;
}
//newCols.push(d);
}
});
if (formHtml !== '') {
$(elem).before('');
Table.listenTableSearch(tableId);
// 初始化form表单
form.render();
}
},
formatCols: function(cols, init) {
for (i in cols) {
var col = cols[i];
for (index in col) {
var val = col[index];
// 判断是否包含初始化数据
if (val.init === undefined) {
cols[i][index]['init'] = init;
}
// 格式化列操作栏
if (val.templet === Table.formatter.tool && val.operat === undefined) {
cols[i][index]['operat'] = ['edit', 'delete'];
}
// 判断是否包含开关组件
if (val.templet === Table.formatter.switch && val.filter === undefined) {
cols[i][index]['filter'] = 'switchStatus';
}
// 判断是否含有搜索下拉列表
if (val.selectList !== undefined && val.search === undefined) {
cols[i][index]['search'] = 'select';
}
// 判断是否初始化对齐方式
if (val.align === undefined) {
cols[i][index]['align'] = 'left';
}
// 部分字段开启排序
var sortDefaultFields = ['id', 'sort'];
if (val.sort === undefined && sortDefaultFields.indexOf(val.field) >= 0) {
cols[i][index]['sort'] = true;
}
// 初始化图片高度
if (val.templet === Table.formatter.image && val.imageHeight === undefined) {
cols[i][index]['imageHeight'] = 30;
}
// 判断是否多层对象
if (val.field !== undefined && val.field.split(".").length > 1) {
if (val.templet === undefined) {
cols[i][index]['templet'] = Table.formatter.value;
}
}
// 判断是否列表数据转换
/*if (val.selectList !== undefined && val.templet === undefined) {
cols[i][index]['templet'] = Table.formatter.list;
}*/
}
}
return cols;
},
listenTableSearch: function(tableId) {
var $commonsearch = $("#searchFieldset_" + tableId);
var layForm = $("form.form-commonsearch", $commonsearch);
require(['form'], function(Form) {
Form.api.bindevent(layForm);
})
form.on('submit(' + tableId + '_filter)', function(data) {
var options = layui.table.getOptions(tableId);
var searchQuery = Table.getSearchQuery(options, true);
// 提交通用搜索时判断是否和Tabs筛选一致
var options = layui.table.getOptions(tableId);
var tabs = $('.layui-tabs-header[data-field]', $('div[id="' + options.tabsId + '"]'));
var field = tabs.data("field");
var value = $("li.layui-this", tabs).data("value");
if (data.field && typeof data.field[field] !== 'undefined' && data.field[field] != value) {
$("li", tabs).removeClass("layui-this");
$("li[data-value='" + data.field[field] + "']", tabs).addClass("layui-this");
}
table.reloadData(tableId, {
page: {
curr: 1
},
where: {
filter: JSON.stringify(searchQuery.filter),
op: JSON.stringify(searchQuery.op)
}
});
return false;
})
// 重置事件
layForm.on('click', 'button[data-table-reset]', function() {
layForm[0].reset();
var options = layui.table.getOptions(tableId);
$('[data-field] li', $('div[lay-filter="' + options.layFilter + '"]')).removeClass('layui-this');
$('[data-field] li:first', $('div[lay-filter="' + options.layFilter + '"]')).addClass('layui-this');
setTimeout(function() {
table.reloadData(tableId);
}, 1);
})
//表格点击搜索
$(document).on("click", ".searchit", function() {
var value = $(this).data("value");
var field = $(this).data("field");
var obj = $("form [name='" + field + "']", $commonsearch);
if (obj.length > 0) {
if (obj.is("select")) {
$("option[value='" + value + "']", obj).prop("selected", true);
form.render('select');
} else if (obj.length > 1) {
$("form [name='" + field + "'][value='" + value + "']", $commonsearch).prop("checked", true);
} else {
obj.val(value + "");
}
obj.trigger("change");
$("form button[type='submit']", $commonsearch).trigger("click");
}
});
//快速搜索
$(document).on('blur keydown', '#layui-input-search-' + tableId, function(event) {
if (event.type === 'keydown' && event.keyCode !== 13) {
return true;
}
var text = $(this).val();
table.reloadData(tableId, { where: { search: text } });
$(this).prop("value", $(this).val());
return false
})
},
getSearchQuery: function(that, removeempty) {
var op = {};
var filter = {};
var value = '';
$("form.form-commonsearch .operate", that.$commonsearch).each(function(i) {
var name = $(this).data("name");
var sym = $(this).is("select") ? $("option:selected", this).val() : $(this).val().toUpperCase();
var obj = $("[name='" + name + "']", that.$commonsearch);
if (obj.length == 0)
return true;
var vObjCol = that.searchColumns[i];
var process = vObjCol && typeof vObjCol.process == 'function' ? vObjCol.process : null;
if (obj.length > 1) {
if (/BETWEEN$/.test(sym)) {
var value_begin = $.trim($("[name='" + name + "']:first", that.$commonsearch).val()),
value_end = $.trim($("[name='" + name + "']:last", that.$commonsearch).val());
if (value_begin.length || value_end.length) {
if (process) {
value_begin = process(value_begin, 'begin');
value_end = process(value_end, 'end');
}
value = value_begin + ',' + value_end;
} else {
value = '';
}
//如果是时间筛选,将operate置为RANGE
if ($("[name='" + name + "']:first", that.$commonsearch).hasClass("datetimepicker")) {
sym = 'RANGE';
}
} else {
value = $("[name='" + name + "']:checked", that.$commonsearch).val();
value = process ? process(value) : value;
}
} else {
value = process ? process(obj.val()) : obj.val();
}
if (removeempty && (value == '' || value == null || ($.isArray(value) && value.length == 0)) && !sym.match(/null/i)) {
return true;
}
op[name] = sym;
filter[name] = value;
});
return { op: op, filter: filter };
},
getQueryParams: function (params, searchQuery, removeempty) {
params.filter = typeof params.filter === 'Object' ? params.filter : (params.filter ? JSON.parse(params.filter) : {});
params.op = typeof params.op === 'Object' ? params.op : (params.op ? JSON.parse(params.op) : {});
params.filter = $.extend({}, params.filter, searchQuery.filter);
params.op = $.extend({}, params.op, searchQuery.op);
//移除empty的值
if (removeempty) {
$.each(params.filter, function (i, j) {
if ((j == '' || j == null || ($.isArray(j) && j.length == 0)) && !params.op[i].match(/null/i)) {
delete params.filter[i];
delete params.op[i];
}
});
}
params.filter = JSON.stringify(params.filter);
params.op = JSON.stringify(params.op);
return params;
},
listenCheckboxEvent: function(options) {
table.on('checkbox(' + options.layFilter + ')', function(obj) {
//监听表格是否选中,多选按钮禁用恢复
var checkStatus;
if (options.tree) {
checkStatus = layui.treeTable.checkStatus(obj.config.id);
} else {
checkStatus = table.checkStatus(obj.config.id);
}
$(Table.config.disabledbtn + '[data-table="' + options.id + '"]').toggleClass('layui-btn-disabled', !checkStatus.data.length);
return false;
})
},
listenToolEvent: function(options) {
table.on('tool(' + options.layFilter + ')', function(obj) {
var attrEvent = obj.event;
if (Table.toolEvents.hasOwnProperty(attrEvent)) {
Table.toolEvents[attrEvent] && Table.toolEvents[attrEvent].call(this, obj, options);
}
return false;
})
},
listenToolbarEvent: function(options) {
table.on('toolbar(' + options.layFilter + ')', function(obj) {
var attrEvent = obj.event;
if (Table.toolbarEvents.hasOwnProperty(attrEvent)) {
Table.toolbarEvents[attrEvent] && Table.toolbarEvents[attrEvent].call(this, obj, options);
}
return false;
})
},
listenEditEvent: function(options) {
table.on('edit(' + options.layFilter + ')', function(obj) {
Table.editEvents['edit'].call(this, obj, options)
return false;
})
},
listenTabShowEvent: function(options) {
tabs.on('afterChange(' + options.tabsId + ')', function(data){
var field = $(this).closest("[data-field]").data("field");
var value = $(this).data("value");
var object = $("[name='" + field + "']", $('#' + options.searchFieldsetId));
if (object.prop('tagName') === "SELECT") {
$("option[value='" + value + "']", object).prop("selected", true);
form.render('select');
} else {
object.val(value);
}
table.reload(options.id,{
page: {
curr: 1 // 重置到第一页
}
});
})
},
listenSwitch: function(options) {
var modifyReload = options.modifyReload || false;
layui.form.on('switch(switchStatus)', function(obj) {
var checked = obj.elem.checked ? 1 : 0;
var that = $(this);
var url = $(this).attr('data-url') || options.init.multi_url;
var field = $(this).attr('data-field') || 'status';
var data = {
id: obj.value,
param: field + '=' + checked,
};
Yzn.api.ajax({
url: url,
data: data,
}, function(data, ret) {
if (modifyReload) {
layui.table.reloadData(options.id);
}
}, function(data, ret) {
obj.elem.checked = !checked;
});
});
},
buildOperatHtml: function(tableId, i, row, j) {
var hidden, disable, url, classname, icon, text, title, refresh, confirm, extend,
dropdown, html, key;
hidden = typeof j.hidden === 'function' ? j.hidden.call(Table, row, j) : (typeof j.hidden !== 'undefined' ? j.hidden : false);
if (hidden) {
return '';
}
key = row.LAY_COL.key;
index = row.LAY_INDEX;
url = j.url ? j.url : '';
url = typeof url === 'function' ? url.call(Table, row, j) : (url ? Yzn.api.fixurl(Table.api.toolSpliceUrl(url, row)) : 'javascript:;');
classname = j.class ? j.class : '';
icon = j.icon ? j.icon : '';
text = typeof j.text === 'function' ? j.text.call(Table, row, j) : j.text ? j.text : '';
title = typeof j.title === 'function' ? j.title.call(Table, row, j) : j.title ? j.title : text;
refresh = j.refresh ? 'data-refresh="' + j.refresh + '"' : '';
confirm = typeof j.confirm === 'function' ? j.confirm.call(Table, row, j) : (typeof j.confirm !== 'undefined' ? j.confirm : false);
confirm = confirm ? 'data-confirm="' + confirm + '"' : '';
extend = typeof j.extend === 'function' ? j.extend.call(Table, row, j) : (typeof j.extend !== 'undefined' ? j.extend : '');
disable = typeof j.disable === 'function' ? j.disable.call(Table, row, j) : (typeof j.disable !== 'undefined' ? j.disable : false);
if (disable) {
classname = classname + ' layui-btn-disabled disabled';
}
html = '' + (text ? ' ' + text : '') + '';
return html;
},
getItemField: function(item, field) {
var customValue = field.split('.').reduce(function(obj, key) {
return obj === null || obj === undefined ? '' : obj[key];
}, item);
return typeof customValue === 'string' ?
(item.LAY_COL && item.LAY_COL.escape !== false ? layui.util.escape(customValue) : customValue) :
customValue;
},
done: function (res, curr, count) {
//初始化导入按钮
const btnImport = $('[lay-event="btn-import"]');
if (btnImport.length > 0) {
btnImport.click();
}
//拖拽
var options = this;
if(options.init.dragsort_url !== '' ){
var tbv = options.elem.next();
var tbody = tbv.find('.layui-table-main tbody');
var tableId = options.init.table_render_id;
require(['dragsort'], function () {
tbody.dragsort({
itemSelector: 'tr:visible',
dragSelector: "a.btn-dragsort",
dragEnd: function (a, b) {
var element = $("a.btn-dragsort", this);
var data = table.cache[tableId];
var current = data[$(this).data("index")];
var ids = $.map($("tr:visible", tbody), function (tr) {
return data[$(tr).data("index")][options.pk];
});
var changeid = current[options.pk];
var pid = typeof current.parentid != 'undefined' ? current.parentid : '';
var params = {
url: options.init.dragsort_url,
data: {
ids: ids.join(','),
changeid: changeid,
pid: pid,
field: Table.config.dragsortfield,
orderway: options.sortOrder,
table: options.init.table,
pk: options.pk
}
};
Yzn.api.ajax(params, function (data, ret) {
var success = $(element).data("success") || $.noop;
if (typeof success === 'function') {
if (false === success.call(element, data, ret)) {
return false;
}
}
table.reload(tableId);
}, function (data, ret) {
var error = $(element).data("error") || $.noop;
if (typeof error === 'function') {
if (false === error.call(element, data, ret)) {
return false;
}
}
table.reload(tableId);
});
}
})
})
}
},
before: function(options) {
if (options.search === true) {
//初始化搜索参数
this.$commonsearch = $("#" + options.searchFieldsetId);
var queryParams = Table.getQueryParams({}, Table.getSearchQuery(this, true));
options.where.filter = queryParams.filter;
options.where.op = queryParams.op;
}
},
toolbarEvents: {
//监听头部工具栏-刷新
'btn-refresh': function(obj, options) {
// 监听动态表格刷新
tableId = options.init.table_render_id || $(this).attr('data-table-refresh');
table.reload(tableId);
},
//监听头部工具栏-新增
'btn-add': function(obj, options) {
// 监听弹出层的打开
var url = options.init.add_url;
Yzn.api.open(url, $(this).data("original-title") || $(this).attr("title") || '添加', $(this).data() || {});
},
//监听头部工具栏-编辑
'btn-edit': function(obj, options) {
// 批量编辑按钮事件
tableId = options.init.table_render_id;
var that = this;
var ids = Table.api.selectedids(tableId);
if (ids.length <= 0) {
Toastr.error('请勾选需要操作的数据');
return false;
}
if (ids.length > 10) {
Toastr.error('最多勾选10条数据');
return false;
}
var title = $(that).data('title') || $(that).attr("title") || '编辑';
var data = $(that).data() || {};
delete data.title;
//循环弹出多个编辑框
$.each(Table.api.selecteddata(tableId), function(index, row) {
var url = options.init.edit_url;
row = $.extend({}, row ? row : {}, { id: row[options.pk] });
url = Table.api.toolSpliceUrl(url, row);
Yzn.api.open(url, typeof title === 'function' ? title.call(table, row) : title, data);
});
},
//监听头部工具栏-删除
'btn-delete': function(obj, options) {
//表格批量删除
tableId = options.init.table_render_id;
var that = this;
var ids = Table.api.selectedids(tableId);
var confirm = $(that).data("confirm");
var message = typeof confirm === 'function' ? confirm.call(that, ids) : (typeof confirm !== 'undefined' ? confirm : '');
if (ids.length <= 0) {
Toastr.error('请勾选需要操作的数据');
return false;
}
Layer.confirm(message || '确定要删除选中的 ' + ids.length + ' 项吗?', { icon: 3, title: '提示信息', offset: 0, shadeClose: true, btn: ['确认', '取消'] },
function(index) {
Table.api.multi("del", ids, tableId, that);
Layer.close(index);
}
);
},
//监听头部工具栏-多选操作
'btn-multi': function(obj, options) {
// 批量操作按钮事件
tableId = options.init.table_render_id;
var ids = Table.api.selectedids(tableId);
if (ids.length <= 0) {
Toastr.error('请勾选需要操作的数据');
return false;
}
Table.api.multi($(this).data("action"), ids, tableId, this);
},
//监听头部工具栏-批量导入
'btn-import': function(obj, options) {
var that = this;
require(['upload'], function (Upload) {
var tableId = options.init.table_render_id || $(this).attr('data-table-refresh');
Upload.api.upload($(that), function (data, ret) {
Yzn.api.ajax({
url: options.init.import_url,
data: {file: data.url},
}, function (data, ret) {
table.reloadData(tableId);
});
});
});
},
//监听头部工具栏-搜索点击
'TABLE_SEARCH': function(obj, options) {
// 搜索表单的显示
var _that = $("#" + options.searchFieldsetId);
if (_that.hasClass("layui-hide")) {
_that.removeClass('layui-hide');
} else {
_that.addClass('layui-hide');
}
}
},
toolEvents: {
//监听表格右侧工具-编辑
'btn-editone': function(obj, options) {
var data = obj.data;
var ids = data[options.pk];
var row = $.extend({}, data ? data : {}, { id: ids });
var url = options.init.edit_url;
Yzn.api.open(Table.api.toolSpliceUrl(url, row), $(this).data("original-title") || $(this).attr("title") || '编辑', $(this).data() || {});
},
//监听表格右侧工具-删除
'btn-delone': function(obj, options) {
var that = this;
var tableId = options.init.table_render_id;
var data = obj.data;
var top = $(that).offset().top - $(window).scrollTop();
var left = $(that).offset().left - $(window).scrollLeft() - 260;
if (top + 154 > $(window).height()) {
top = top - 154;
}
if (left < 0 || $(window).width() < 480) {
top = left = undefined;
}
Layer.confirm($(that).data("confirm") || '确定要删除选中项?', { icon: 3, title: '提示信息', offset: [top, left], shadeClose: true, btn: ['确认', '取消'] },
function(index) {
Table.api.multi("del", data[options.pk], tableId, that);
Layer.close(index);
}
);
}
},
editEvents: {
//监听表格文本框-编辑
'edit': function(obj, options) {
var tableId = options.init.table_render_id;
var url = options.init.multi_url;
var modifyReload = options.modifyReload || false;
var data = {
id: obj.data.id,
param: obj.field + '=' + obj.value,
};
Yzn.api.ajax({
url: url,
data: data,
}, function(data, ret) {
if (modifyReload) {
layui.table.reloadData(tableId);
}
});
}
},
formatter: {
tool: function(data) {
var that = this;
that.operat = that.operat || ['edit', 'delete'];
var elem = that.init.table_elem || init.table_elem;
var tableId = that.init.table_render_id || init.table_render_id;
var html = '';
// 定义操作按钮配置
const buttonConfigs = {
edit: {
class: 'layui-btn layui-btn-success layui-btn-xs',
field: 'id',
icon: 'iconfont icon-edit-2-line',
auth: 'edit',
text: "",
title: '编辑信息',
extend: "lay-event='btn-editone'"
},
restore: {
class: 'layui-btn layui-btn-xs btn-ajax',
field: 'id',
icon: 'iconfont icon-arrow-go-back-line',
auth: 'restore',
text: "还原",
title: '还原',
url: that.init.restore_url,
refresh: true,
extend: ""
},
destroy: {
class: 'layui-btn layui-btn-danger layui-btn-xs btn-ajax',
field: 'id',
icon: 'iconfont icon-close-fill',
auth: 'destroy',
text: "销毁",
title: '销毁',
url: that.init.destroy_url,
refresh: true,
extend: ""
},
delete: {
class: 'layui-btn layui-btn-danger layui-btn-xs',
field: 'id',
icon: 'iconfont icon-delete-bin-line',
auth: 'delete',
text: "",
title: '删除',
extend: "lay-event='btn-delone'"
},
dragsort:{
class: 'layui-btn layui-btn-xs layui-bg-black btn-dragsort',
field: 'id',
icon: 'iconfont icon-drag-move-2-fill',
auth: 'weigh',
text: "",
title: '移动',
url: that.init.dragsort_url,
refresh: true,
extend: ""
}
};
$.each(that.operat, function(i, item) {
if (typeof item === 'string' && buttonConfigs[item]) {
const config = buttonConfigs[item];
if (Yzn.api.checkAuth(config.auth, elem)) {
html += Table.buildOperatHtml(tableId, i, data, config);
}
} else if (typeof item === 'object') {
if (Yzn.api.checkAuth(item.auth, elem)) {
html += Table.buildOperatHtml(tableId, i, data, item);
}
}
});
return html;
},
status: function(data) {
var custom = { normal: 'success', hidden: 'gray', deleted: 'danger', locked: 'info' };
if (typeof this.custom !== 'undefined') {
custom = $.extend(custom, this.custom);
}
this.custom = custom;
this.icon = 'iconfont icon-circle-fill';
return Table.formatter.normal.call(this, data);
},
normal: function(data) {
var that = this;
var colorArr = ["danger", "success", "primary", "warning", "info", "gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];
var custom = {};
if (typeof that.custom !== 'undefined') {
custom = $.extend(custom, that.custom);
}
var field = that.field;
try {
var value = Table.getItemField(data, field);
value = value == null || value.length === 0 ? '' : value.toString();
} catch (e) {
var value = undefined;
}
value = value == null || value.length === 0 ? '' : value.toString();
var keys = typeof that.selectList === 'object' ? Object.keys(that.selectList) : [];
var index = keys.indexOf(value);
var color = value && typeof custom[value] !== 'undefined' ? custom[value] : null;
var display = index > -1 ? that.selectList[value] : null;
var icon = typeof that.icon !== 'undefined' ? that.icon : null;
if (!color) {
color = index > -1 && typeof colorArr[index] !== 'undefined' ? colorArr[index] : 'primary';
}
if (!display) {
display = value.charAt(0).toUpperCase() + value.slice(1);
}
var html = '' + (icon ? '' : '') + display + '';
if (that.search != false) {
html = '' + html + '';
}
return html;
},
flag: function(data) {
var that = this;
var field = that.field;
try {
var value = Table.getItemField(data, field);
value = value == null || value.length === 0 ? '' : value.toString();
} catch (e) {
var value = undefined;
}
//赤色 墨绿 蓝色 藏青 雅黑 橙色
var colorArr = { 0: 'red', 1: 'green', 2: 'blue', 3: 'cyan', 4: 'black', 5: 'orange' };
//如果字段列有定义custom
if (typeof that.custom !== 'undefined') {
colorArr = $.extend(colorArr, that.custom);
}
if (typeof that.selectList === 'object' && typeof that.custom === 'undefined') {
var i = 0;
var searchValues = Object.values(colorArr);
$.each(that.selectList, function(key, val) {
if (typeof colorArr[key] == 'undefined') {
colorArr[key] = searchValues[i];
i = typeof searchValues[i + 1] === 'undefined' ? 0 : i + 1;
}
});
}
//渲染Flag
var html = [];
var arr = value != '' ? value.split(',') : [];
var color, display, label;
$.each(arr, function(i, value) {
value = value == null || value.length === 0 ? '' : value.toString();
if (value == '')
return true;
color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'green';
display = typeof that.selectList !== 'undefined' && typeof that.selectList[value] !== 'undefined' ? that.selectList[value] : value.charAt(0).toUpperCase() + value.slice(1);
label = '' + display + '';
if (that.search != false) {
html.push('' + label + '');
} else {
html.push(label);
}
})
return html.join(' ');
},
label: function(data) {
return Table.formatter.flag.call(this, data);
},
switch: function(data) {
var that = this;
var field = that.field;
that.filter = that.filter || that.field || null;
that.checked = that.checked || 1;
that.tips = that.tips || '开|关';
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
var checked = value === that.checked ? 'checked' : '';
return laytpl('').render(data);
},
image: function(data) {
var that = this;
that.imageWidth = that.imageWidth || 30;
that.imageHeight = that.imageHeight || 30;
that.imageSplit = that.imageSplit || ',';
that.imageJoin = that.imageJoin || ' ';
that.title = that.title || that.field;
var field = that.field,
title = data[that.title];
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
if (!value) {
return '';
} else {
var valuesHtml = [];
valuesHtml.push('
');
return valuesHtml.join(that.imageJoin);
}
},
images: function(data) {
var that = this;
that.imageWidth = that.imageWidth || 30;
that.imageHeight = that.imageHeight || 30;
that.imageSplit = that.imageSplit || ',';
that.imageJoin = that.imageJoin || ' ';
that.title = that.title || that.field;
var field = that.field,
title = data[that.title];
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
if (!value) {
return '';
} else {
var values = value.split(that.imageSplit),
valuesHtml = [];
values.forEach(function(value, index) {
valuesHtml.push('
');
});
return valuesHtml.join(that.imageJoin);
}
},
file: function(data) {
var that = this;
that.imageWidth = that.imageWidth || 80;
that.imageHeight = that.imageHeight || 30;
that.imageSplit = that.imageSplit || ',';
that.imageJoin = that.imageJoin || ' ';
that.title = that.title || that.field;
var field = that.field,
title = data[that.title];
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
if (!value) {
return '';
} else {
var values = value.split(that.imageSplit),
valuesHtml = [];
values.forEach(function(value, index) {
suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(value);
suffix = suffix ? suffix[1] : 'file';
url = Yzn.api.fixurl("ajax/icon?suffix=" + suffix);
valuesHtml.push('
');
});
return valuesHtml.join(that.imageJoin);
}
},
files: function(data) {
return Table.formatter.image.file(this, data);
},
url: function(data) {
var field = this.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
return '';
},
price: function(data) {
var field = this.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
return '¥' + value + '';
},
icon: function(data) {
var field = this.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
return '';
},
text: function(data) {
var field = this.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
return '' + value + '';
},
value: function(data) {
var field = this.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
return '' + value + '';
},
datetime: function(data) {
var that = this;
var field = that.field;
try {
var value = Table.getItemField(data, field);
} catch (e) {
var value = undefined;
}
var datetimeFormat = typeof that.datetimeFormat === 'undefined' ? 'yyyy-MM-dd HH:mm:ss' : that.datetimeFormat;
if (value && isNaN(Date.parse(value))) {
return layui.util.toDateString(value * 1000, datetimeFormat)
} else if (value && !isNaN(Date.parse(value))) {
return layui.util.toDateString(Date.parse(value), datetimeFormat)
} else {
return '-';
}
}
},
}
return Table;
});