(function () {
var admin = window.UA_ADMIN;
var form = window.UA_CORE.form,
layer = window.UA_CORE.layer,
table = window.UA_CORE.table,
laydate = window.UA_CORE.laydate,
laytpl = window.UA_CORE.laytpl,
util = window.UA_CORE.util;
var lastTableWhere = {};
var selectMode, selectConfirmCallback;
admin.table = {
render: function (options) {
options.init = options.init || admin.init;
options.modifyReload = admin.parame(options.modifyReload, true);
options.elem = options.elem || options.init.tableElem;
options.id = options.id || options.init.tableRenderId;
options.scrollPos = options.scrollPos || 'fixed';
options.layFilter = options.id + '_LayFilter';
options.url = options.url || admin.url(options.init.indexUrl);
options.headers = admin.headers();
options.page = admin.parame(options.page, true);
options.search = admin.parame(options.search, true);
options.layout = admin.parame(options.layout, true);
options.layoutList = admin.parame(options.layoutList,
[
'table',
'card',
{
name: 'usercard',
// 优先级1
tplFunction() {
},
// 优先级3
tplVue() {
},
// 优先级2
tplLay() {
},
// 优先级4
tplLayId: '',
// 优先级5
tplVueId: ''
}
]
);
options.layoutDefault = admin.parame(options.layoutDefault, true);
options.skin = options.skin || 'line';
options.autoSort = options.autoSort || false;
options.limit = options.limit || 15;
options.limits = options.limits || [10, 15, 20, 25, 50, 100];
options.cols = options.cols || [];
options.rowDisableCallback = options.rowDisableCallback || null;
var defaultToolbar = ['filter', 'print'];
if (options.layout === true) {
defaultToolbar.push({
title: '视图',
layEvent: 'TABLE_LAYOUT',
icon: 'layui-icon-template-1',
extend: 'data-table-id="' + options.id + '"'
});
if (options.layoutDefault === true) {
// 自动判断,手机端默认card,电脑端默认table
if (admin.checkMobile()) {
options.layoutDefault = 'card';
} else {
options.layoutDefault = 'table';
}
}
options.layoutDefault = admin.trySetPageSetting('table-layout-default', options.layoutDefault);
}
if (options.search) {
defaultToolbar.push({
title: '搜索',
layEvent: 'TABLE_SEARCH',
icon: 'layui-icon-search',
extend: 'data-table-id="' + options.id + '"'
});
}
if (options.defaultToolbar === undefined) {
options.defaultToolbar = defaultToolbar;
}
var optionBefore = function () { };
if (options.before != undefined) {
optionBefore = options.before;
}
options.before = function (tableIns) {
optionBefore(tableIns);
};
var optionDone = function () { };
if (options.done != undefined) {
optionDone = options.done;
}
options.done = function (res, curr, count) {
optionDone(res, curr, count);
// 监听表格内的复制组件
admin.api.copyText('[lay-id=' + options.id + ']');
};
/**
* 为空时认为自己是普通状态,否则是单选、多选、子页面,此时添加等默认行为走弹框而不是新标签页
*/
selectMode = admin.getQueryVariable("select_mode");
selectConfirmCallback = admin.getQueryVariable('select_confirm_callback', 'onTableDataConfirm');
if (selectMode == 'checkbox') {
if (options.cols[0][0].type == 'radio') {
options.cols[0][0].type = 'checkbox';
} else if (options.cols[0][0].type != 'checkbox') {
options.cols[0].unshift({
type: 'checkbox'
});
}
} else if (selectMode == 'radio') {
if (options.cols[0][0].type == 'checkbox') {
options.cols[0][0].type = 'radio';
} else if (options.cols[0][0].type != 'radio') {
options.cols[0].unshift({
type: 'radio'
});
}
} else {
if(!admin.isParentIndex()){
selectMode = 'childPage'
}
}
// 判断元素对象是否有嵌套的
options.cols = admin.table.formatCols(options.cols, options.init);
// 初始化表格lay-filter
$(options.elem).attr('lay-filter', options.layFilter);
// 初始化表格搜索
if (options.search === true) {
options = admin.table.renderSearch(options.cols, options.elem, options.id, options);
}
// 初始化模板切换
if (options.layout === true) {
options = admin.table.renderLayout(options);
}
// 初始化表格左上方工具栏
options.toolbar = options.toolbar || ['refresh', 'add', 'delete', 'export'];
if (selectMode == 'checkbox' || selectMode == 'radio') {
options.toolbar.unshift('selectConfirm');
options.height = 'full-85';
}
if (options.init.formFullScreen == true) {
options.init.formFullScreen = 'true';
} else {
options.init.formFullScreen = 'false';
}
options.toolbar = admin.table.renderToolbar(options.toolbar, options.elem, options.id, options.init);
// 判断是否有操作列表权限
options.cols = admin.table.renderOperat(options.cols, options.elem);
// 判断是否有操作列表权限
options.cols = admin.table.renderTrueHide(options.cols, options);
var parseData = function (res) { return res; };
if (typeof options.parseData === 'function') {
parseData = options.parseData;
}
options.parseData = function (res) {
// 初始化已经选择的值
if (selectMode == 'checkbox' || selectMode == 'radio') {
if (typeof options.rowDisableCallback == 'function') {
for (let index = 0; index < res.data.length; index++) {
const dataItem = res.data[index];
var rowDisableResult = options.rowDisableCallback(dataItem);
if (rowDisableResult === false || rowDisableResult === true) {
res.data[index].LAY_DISABLED = rowDisableResult;
}
}
}
var selectedIds = admin.getQueryVariable('selectedIds', '');
if (selectedIds.length > 0) {
var selectedIdArr = selectedIds.split(',');
for (let index = 0; index < res.data.length; index++) {
const dataItem = res.data[index];
if (selectedIdArr.indexOf(dataItem.id.toString()) > -1) {
res.data[index].LAY_DISABLED = true;
}
}
}
}
res = parseData(res);
return res;
};
// 初始化表格
var newTable = table.render(options);
// 监听表格搜索开关显示
admin.table.listenToolbar(options.layFilter, options.id);
// 监听表格瓶排序
admin.table.listenTableSort(options);
// 监听表格开关切换
admin.table.renderSwitch(options.cols, options.init, options.id, options.modifyReload);
// 监听表格开关切换
admin.table.listenEdit(options.init, options.layFilter, options.id, options.modifyReload);
// 监听导出事件
admin.table.listenExport(options);
// 监听表格选择器
admin.table.listenTableSelectConfirm(options);
return newTable;
},
renderToolbar: function (data, elem, tableId, init) {
data = data || [];
var toolbarHtml = '';
$.each(data, function (i, v) {
if (v === 'refresh') {
toolbarHtml += ' \n';
} else if (v === 'add') {
if (admin.checkAuth('add', elem)) {
if(selectMode){
toolbarHtml += '\n';
}else{
toolbarHtml += '\n';
}
}
} else if (v === 'delete') {
if (admin.checkAuth('delete', elem)) {
toolbarHtml += '\n';
}
} else if (v === 'export') {
if (admin.checkAuth('export', elem)) {
toolbarHtml += '\n';
}
} else if (v === 'selectConfirm') {
toolbarHtml += '\n';
} else if (typeof v === "object") {
$.each(v, function (ii, vv) {
vv.class = vv.class || '';
vv.icon = vv.icon || '';
vv.auth = vv.auth || 'add';
vv.url = vv.url || '';
vv.method = vv.method || 'open';
vv.title = vv.title || vv.text;
vv.text = vv.text || vv.title;
vv.extend = vv.extend || '';
vv.checkbox = vv.checkbox || false;
if (admin.checkAuth(vv.auth, elem)) {
toolbarHtml += admin.table.buildToolbarHtml(vv, tableId);
}
});
}
});
return '
' + toolbarHtml + '
';
},
renderSearch: function (cols, elem, tableId, options) {
// TODO 只初始化第一个table搜索字段,如果存在多个(绝少数需求),得自己去扩展
cols = cols[0] || {};
var newCols = [];
var formHtml = '';
var tabSetting = {};
var formatFilter = {},
formatOp = {};
$.each(cols, function (i, d) {
d.field = d.field || false;
d.fieldAlias = admin.parame(d.fieldAlias, d.field);
d.title = d.title || d.field || '';
d.selectList = d.selectList || {};
d.search = admin.parame(d.search, true);
d.searchTip = d.searchTip || '请输入' + d.title || '';
d.searchValue = d.searchValue || undefined;
d.searchHide = d.searchHide || '';
d.defaultSearchValue = d.defaultSearchValue;
d.searchOp = d.searchOp || '%*%';
d.timeType = d.timeType || 'datetime';
d.elemIdName = d.fieldAlias;
var a = '';
var b = '';
if (typeof d.fieldAlias == 'string') {
if (d.fieldAlias.indexOf('[') == 0) {
var fieldPlusArr = d.fieldAlias.replace('[').split(']');
d.elemIdName = fieldPlusArr.join('-');
}
d.elemIdName = d.elemIdName.replace('.', '-');
}
if (d.defaultSearchValue !== undefined) {
if (!d.searchValue || d.searchValue.length == 0) {
d.searchValue = d.defaultSearchValue;
}
} else {
if (d.field) {
d.defaultSearchValue = admin.getQueryVariable(d.field);
if (d.defaultSearchValue != undefined) {
d.searchValue = d.defaultSearchValue;
}
}
}
if (d.searchValue !== undefined) {
if (d.search == 'number_limit') {
var paramsArr = d.searchValue.split(',');
a = paramsArr[0];
b = paramsArr[1];
if (a) {
formatFilter['[' + d.field + ']min'] = a;
formatOp['[' + d.field + ']min'] = 'min';
}
if (b) {
formatFilter['[' + d.field + ']max'] = b;
formatOp['[' + d.field + ']max'] = 'max';
}
} else if (d.search == 'time_limit') {
var paramsArr = d.searchValue.split(',');
a = paramsArr[0];
b = paramsArr[1];
if (a) {
formatFilter['[' + d.field + ']min_date'] = a;
formatOp['[' + d.field + ']min_date'] = 'min_date';
}
if (b) {
formatFilter['[' + d.field + ']max_date'] = b;
formatOp['[' + d.field + ']max_date'] = 'max_date';
}
} else {
formatFilter[d.field] = d.searchValue;
formatOp[d.field] = d.searchOp;
}
}
var formSearchHideClass = '';
if (d.searchHide) {
formSearchHideClass = ' search-hide-item';
}
if (d.searchValue === undefined) {
d.searchValue = '';
}
if (d.field !== false) {
if (d.search !== false) {
switch (d.search) {
case true:
formHtml += '\t';
break;
case 'select':
d.searchOp = '=';
var selectHtml = '';
if (d.tab) {
tabSetting.field = d.field;
tabSetting.elemIdName = d.elemIdName;
tabSetting.list = d.selectList;
tabSetting.index = -1;
}
var selectListIndex = 0;
$.each(d.selectList, function (sI, sV) {
var selected = '';
if (sI === d.searchValue) {
selected = 'selected=""';
if (d.tab) {
tabSetting.index = selectListIndex;
}
}
selectHtml += '/n';
selectListIndex++;
});
if (d.tab) {
formHtml += '';
break;
}
formHtml += '\t';
break;
case 'range':
d.searchOp = 'range';
formHtml += '\t';
break;
case 'time':
d.searchOp = '=';
formHtml += '\t';
break;
case 'time_limit':
d.searchOp = '=';
formHtml += '\t';
break;
case 'number_limit':
d.searchOp = '=';
formHtml += '\t';
break;
}
newCols.push(d);
} else {
// TODO:支持更多种类型的初始化,比如number_limit、time_limit
formHtml += '';
}
}
});
if (tabSetting.field) {
var tabId = 'tabFieldset_' + tableId;
$(elem).before('');
var header = [
{
title: '全部',
key: '',
}
];
for (const tabSettingListKey in tabSetting.list) {
if (Object.prototype.hasOwnProperty.call(tabSetting.list, tabSettingListKey)) {
const tabItem = tabSetting.list[tabSettingListKey];
header.push({
title: tabItem,
key: tabSettingListKey,
});
}
}
layui.tabs.render({
elem: '#' + tabId,
header: header,
index: tabSetting.index + 1,
});
layui.tabs.on('afterChange(' + tabId + ')', function (data) {
var value = $(data.thisHeaderItem).attr('lay-key');
$('#c-' + tabSetting.elemIdName).val(value);
$('[lay-filter="' + tableId + '_filter"]').trigger('click');
});
}
if (formHtml !== '') {
$(elem).before('');
admin.table.listenTableSearch(tableId);
// 初始化form表单
form.render();
$.each(newCols, function (ncI, ncV) {
if (ncV.search === 'range') {
laydate.render({ range: true, type: ncV.timeType, elem: '[name="' + ncV.fieldAlias + '"]' });
}
if (ncV.search === 'time') {
laydate.render({ type: ncV.timeType, elem: '[name="' + ncV.fieldAlias + '"]' });
}
if (ncV.search === 'time_limit') {
laydate.render({ type: ncV.timeType, elem: '[name="[' + ncV.fieldAlias + ']min_date"]' });
laydate.render({ type: ncV.timeType, elem: '[name="[' + ncV.fieldAlias + ']max_date"]' });
}
});
}
options.where = {
filter: JSON.stringify(formatFilter),
op: JSON.stringify(formatOp)
};
lastTableWhere[tableId] = options.where;
return options;
},
renderLayout: function (options) {
if (!options.layoutList) {
return options;
}
var tableId = options.id;
var layuiTableElemName = '[lay-table-id="' + tableId + '"]';
var elem = options.elem;
// 初始化参数
options.layoutList = options.layoutList.map((item) => {
if (item == 'table') {
return {
name: 'table',
icon: 'layui-icon layui-icon-table',
title: '默认表格',
};
} else if (item == 'card') {
return {
name: 'card',
title: '默认卡片',
icon: 'layui-icon layui-icon-form',
tplFunction: function (options, res, container) {
console.log('card func');
console.log(options);
console.log(res);
console.log(container);
var baseItem = `
`;
var baseDataItem = `
`;
res.data.forEach(row => {
var rowItem = $.extend(true, {}, row);
var baseElem = $(baseItem).appendTo(container);
if (options.cols[0][0].type == 'checkbox' || options.cols[0[0]].type == 'radio') {
$('')
.appendTo(baseElem.find('.header').find('.plus'));
}
rowItem.LAY_COL = $.extend(true, {}, options.cols[0][1]);
baseElem.find('.header').find('.main').find('span').html(
options.cols[0][1].templet(rowItem)
);
options.cols[0].forEach(LAY_COL => {
var dataItem = $.extend(true, {}, row);
dataItem.LAY_COL = $.extend(true, {}, LAY_COL);
if (LAY_COL.type == 'checkbox' || LAY_COL.type == 'radio') {
return;
}
if (LAY_COL.templet == ua.table.tool) {
// 暂时隐藏按钮
// baseElem.find('.footer .plus').html(dataItem.LAY_COL.templet(dataItem));
return;
}
if (LAY_COL.field == 'create_time') {
baseElem.find('.footer .main').html(dataItem.LAY_COL.templet(dataItem));
return;
}
var baseDataItemElem = $(baseDataItem).appendTo(baseElem.find('.body .main'));
baseDataItemElem.find('.item-title').html(
dataItem.LAY_COL.title + ':'
);
baseDataItemElem.find('.item-value').html(
dataItem.LAY_COL.templet(dataItem)
);
});
});
return '';
}
};
} else {
if (item.icon == undefined) {
item.icon = 'layui-icon layui-icon-component';
}
if (item.title == undefined) {
item.title = item.name;
}
}
return item;
});
var optionBefore = options.before;
options.before = function (res, curr, count) {
optionBefore(res, curr, count);
console.log('layout before fun');
var currentLayout = admin.getPageSetting('table-layout-default', 'table');
// 隐藏所有数据体内容
var layuiTableElem = $(layuiTableElemName);
options.layoutList.forEach((item) => {
if (item.name == 'table') {
layuiTableElem.find('.layui-table-box').hide();
} else {
layuiTableElem.find('.layui-table-custom.layui-table-custom-' + item.name).hide();
}
});
if (currentLayout == 'table') {
layuiTableElem.find('.layui-table-box').show();
} else {
var className = '.layui-table-custom.layui-table-custom-' + currentLayout;
// 如果不存在则创建
if (!layuiTableElem.find(className).length) {
layuiTableElem.find('.layui-table-box').before('');
}
layuiTableElem.find(className).show();
loading.show();
}
};
var optionDone = options.done;
options.done = function (res, curr, count) {
optionDone(res, curr, count);
console.log('layout done fun');
var currentLayout = admin.getPageSetting('table-layout-default', 'table');
// 隐藏所有数据体内容
var layuiTableElem = $(layuiTableElemName);
options.layoutList.forEach((item) => {
if (currentLayout == 'table') {
// 如果是table,则不用生成数据,显示出来就行,before已经显示过了
return;
}
if (currentLayout != item.name) {
// 如果不是,则不进行任何操作
return;
}
var className = '.layui-table-custom.layui-table-custom-' + item.name;
// 清空里面的数据
layuiTableElem.find(className).html('');
loading.hide();
item.tplFunction(options, res, layuiTableElem.find(className));
});
};
return options;
},
renderSwitch: function (cols, tableInit, tableId, modifyReload) {
tableInit.modifyUrl = tableInit.modifyUrl || false;
cols = cols[0] || {};
tableId = tableId || admin.init.tableRenderId;
if (cols.length > 0) {
$.each(cols, function (i, v) {
v.filter = v.filter || false;
if (v.filter !== false && tableInit.modifyUrl !== false) {
admin.table.listenSwitch({ filter: v.filter, url: tableInit.modifyUrl, tableId: tableId, modifyReload: modifyReload });
}
});
}
},
renderOperat(data, elem) {
for (dk in data) {
var col = data[dk];
var operat = col[col.length - 1].operat;
if (operat !== undefined) {
var check = false;
for (key in operat) {
var item = operat[key];
if (typeof item === 'string') {
if (admin.checkAuth(item, elem)) {
check = true;
break;
}
} else {
for (k in item) {
var v = item[k];
if (v.auth == undefined) {
v.auth = 'add';
}
if (admin.checkAuth(v.auth, elem)) {
check = true;
break;
}
}
}
}
if (!check) {
data[dk].pop();
}
}
}
return data;
},
renderTrueHide(data, options) {
var newData = [];
for (dk in data) {
var newCol = [];
var col = data[dk];
col.forEach(colItem => {
var trueHide = false;
if (typeof colItem.trueHide == 'function') {
trueHide = colItem.trueHide(colItem, col, options);
} else if (typeof colItem.trueHide == 'string') {
trueHide = !admin.checkAuth(colItem.trueHide, options.elem);
} else {
trueHide = colItem.trueHide;
}
if (!trueHide) {
newCol.push(colItem);
}
});
newData.push(newCol);
}
return newData;
},
buildToolbarHtml: function (toolbar, tableId) {
var html = '';
toolbar.class = toolbar.class || '';
toolbar.icon = toolbar.icon || '';
toolbar.auth = toolbar.auth || 'add';
toolbar.url = toolbar.url || '';
toolbar.extend = toolbar.extend || '';
toolbar.method = toolbar.method || 'open';
toolbar.field = toolbar.field || 'id';
toolbar.title = toolbar.title || toolbar.text;
toolbar.text = toolbar.text || toolbar.title;
toolbar.checkbox = toolbar.checkbox || false;
var formatToolbar = toolbar;
formatToolbar.icon = formatToolbar.icon !== '' ? ' ' : '';
formatToolbar.class = formatToolbar.class !== '' ? 'class="' + formatToolbar.class + '" ' : '';
if (toolbar.method === 'open') {
formatToolbar.method = formatToolbar.method !== '' ? 'data-open="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
} else if (toolbar.method === 'none') { // 常用于与extend配合,自定义监听按钮
formatToolbar.method = '';
} else if (toolbar.method === 'blank') {
formatToolbar.method = ' href="' + formatToolbar.url + '" target="_blank" ';
} else if (operat.method === 'tab') {
formatToolbar.method = ' layuimini-content-href="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '"';
} else {
formatToolbar.method = formatToolbar.method !== '' ? 'data-request="' + formatToolbar.url + '" data-title="' + formatToolbar.title + '" ' : '';
}
formatToolbar.checkbox = toolbar.checkbox ? ' data-checkbox="true" ' : '';
formatToolbar.tableId = tableId !== undefined ? ' data-table="' + tableId + '" ' : '';
html = '';
return html;
},
buildOperatHtml: function (operat, data) {
var html = '';
operat.class = operat.class || '';
operat.icon = operat.icon || '';
operat.auth = operat.auth || 'add';
operat.url = operat.url || '';
operat.extend = operat.extend || '';
operat.method = operat.method || 'open';
operat.field = operat.field || 'id';
operat.data = operat.data || ['id'];
operat.titleField = operat.titleField || 'title';
operat.title = operat.title || operat.text;
operat.text = operat.text || operat.title;
var titleEndfix = '';
if (typeof operat.titleField == 'function') {
titleEndfix = operat.titleField(data, operat);
} else if (data[operat.titleField]) {
titleEndfix = '-' + data[operat.titleField];
}
if (typeof operat.text == 'function') {
operat.text = operat.text(data, operat);
}
if (typeof operat.title == 'function') {
operat.title = operat.title(data, operat);
}
var formatOperat = operat;
formatOperat.icon = formatOperat.icon !== '' ? ' ' : '';
formatOperat.class = formatOperat.class !== '' ? 'class="' + formatOperat.class + '" ' : '';
if (operat.method === 'open') {
formatOperat.method = formatOperat.method !== '' ? 'data-open="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
} else if (operat.method === 'none') { // 常用于与extend配合,自定义监听按钮
formatOperat.method = '';
} else if (operat.method === 'blank') {
formatOperat.method = ' href="' + formatOperat.url + '" target="_blank" ';
} else if (operat.method === 'tab') {
formatOperat.method = ' layuimini-content-href="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '"';
} else {
formatOperat.method = formatOperat.method !== '' ? 'data-request="' + formatOperat.url + '" data-title="' + formatOperat.title + titleEndfix + '" ' : '';
}
formatOperat.dataBind = ' ';
operat.data.forEach((item, index) => {
formatOperat.dataBind += 'data-' + item + '="' + data[item] + '" ';
});
html = '' + formatOperat.icon + formatOperat.text + '';
return html;
},
toolSpliceUrl(url, field, data) {
url = url.indexOf("?") !== -1 ? url + '&' + field + '=' + data[field] : url + '?' + field + '=' + data[field];
return url;
},
formatCols: function (cols, init) {
for (i in cols) {
var col = cols[i];
for (index in col) {
var val = col[index];
if (typeof val.hide == 'function') {
cols[i][index]['hide'] = val.hide(val, cols, init);
}
if (val['width'] == undefined && val['minWidth'] == undefined) {
var width = null;
if (val.title) {
width = val.title.length * 15 + 55;
}
if (width != null) {
cols[i][index]['minWidth'] = width;
}
}
// if str end with _time
if (val.field && val.field.indexOf('_time') !== -1) {
cols[i][index]['minWidth'] = 160;
}
if (val.sort === undefined) {
cols[i][index]['sort'] = true;
}
if (val.defaultValue === undefined) {
cols[i][index]['defaultValue'] = '';
}
// 判断是否包含初始化数据
if (val.init === undefined) {
cols[i][index]['init'] = init;
}
// 格式化列操作栏
if (val.templet === admin.table.tool && val.operat === undefined) {
cols[i][index]['operat'] = ['edit', 'delete'];
}
// 格式化列操作栏
if (val.templet === admin.table.tool) {
cols[i][index]['sort'] = false;
}
// 判断是否包含开关组件
if (val.templet === admin.table.switch && val.filter === undefined) {
cols[i][index]['filter'] = val.field;
}
// 判断是否含有搜索下拉列表
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 === admin.table.image && val.imageHeight === undefined) {
cols[i][index]['imageHeight'] = 26;
cols[i][index]['sort'] = false;
}
// 图片默认不搜索
if (val.templet === admin.table.image && val.search === undefined) {
cols[i][index]['search'] = false;
}
// 判断是否列表数据转换
if (val.selectList !== undefined && val.templet === undefined) {
cols[i][index]['templet'] = admin.table.list;
}
// 判断是否多层对象
if (val.field !== undefined && val.field.split(".").length > 1) {
if (val.templet === undefined) {
cols[i][index]['templet'] = admin.table.value;
}
}
// 如果未定义则默认使用value
if (cols[i][index]['templet'] === undefined) {
cols[i][index]['templet'] = admin.table.value;
} else {
// 针对特定的模板做数据调整
if (cols[i][index]['templet'] == admin.table.list) {
if (val.selectValue) {
var newSelectList = {};
val.selectList.map(item => {
newSelectList[item[val.selectValue]] = item[val.selectLabel];
});
cols[i][index]['selectList'] = newSelectList;
}
}
}
if (val.fieldFormat == undefined) {
switch (val.templet) {
case admin.table.image:
val.fieldFormat = 'image';
break;
case admin.table.date:
val.fieldFormat = 'date';
break;
default:
val.fieldFormat = 'text';
if (val.selectList !== undefined) {
val.fieldFormat = 'select';
}
break;
}
}
}
}
return cols;
},
tool: function (data) {
var option = data.LAY_COL;
option.operat = option.operat || ['edit', 'delete'];
var elem = option.init.tableElem || admin.init.tableElem;
var html = '';
$.each(option.operat, function (i, item) {
if (typeof item === 'string') {
switch (item) {
case 'edit':
var editMethod = 'tab';
if(selectMode){
editMethod = 'open';
}
var operat = {
class: 'layui-btn layui-btn-success layui-btn-xs',
method: editMethod,
field: 'id',
icon: '',
text: '编辑',
title: '编辑信息',
auth: 'edit',
url: option.init.editUrl,
extend: option.init.formFullScreen == 'true' ? ' data-full="true"' : ''
};
operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
if (admin.checkAuth(operat.auth, elem)) {
html += admin.table.buildOperatHtml(operat, data);
}
break;
case 'delete':
var operat = {
class: 'layui-btn layui-btn-danger layui-btn-xs',
method: 'get',
field: 'id',
icon: '',
text: '删除',
title: '确定删除?',
auth: 'delete',
url: option.init.deleteUrl,
extend: ""
};
operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
if (admin.checkAuth(operat.auth, elem)) {
html += admin.table.buildOperatHtml(operat, data);
}
break;
}
} else if (typeof item === 'object') {
$.each(item, function (i, operat) {
operat.class = operat.class || '';
operat.icon = operat.icon || '';
operat.auth = operat.auth || 'add';
operat.url = operat.url || '';
operat.method = operat.method || 'open';
operat.field = operat.field || 'id';
operat.title = operat.title || operat.text;
operat.text = operat.text || operat.title;
operat.extend = operat.extend || '';
operat._if = operat._if || function () { return true; };
if (typeof operat._if == 'function') {
if (operat._if(data, operat) !== true) {
return '';
}
} else if (typeof operat._if == 'string') {
var ifValue = admin.table.returnColumnValue(data, operat._if, false);
if (!ifValue) {
return '';
}
}
// 自定义表格opreat按钮的弹窗标题风格,extra是表格里的欲加入标题中的字段
operat.extra = operat.extra || '';
if (data[operat.extra] !== undefined) {
operat.title = data[operat.extra] + ' - ' + operat.title;
}
if (typeof operat.url == 'function') {
operat.url = operat.url(data, operat);
}
if (typeof operat.field != 'function') {
if (!admin.empty(operat.field)) {
operat.url = admin.table.toolSpliceUrl(operat.url, operat.field, data);
}
} else {
var fieldParam = operat.field(data, operat);
if (typeof fieldParam == 'string') {
operat.url = fieldParam;
} else {
var querys = '';
if (operat.url.indexOf("?") !== -1) {
if (operat.url.indexOf("?") !== operat.url.length - 1) {
querys = '&';
}
} else {
querys = '?';
}
operat.url += querys + $.param(fieldParam);
}
}
if (admin.checkAuth(operat.auth, elem)) {
html += admin.table.buildOperatHtml(operat, data);
}
});
}
});
return html;
},
list: function (data) {
var option = data.LAY_COL;
option.selectList = option.selectList || {};
var value = admin.table.returnColumnValue(data);
if (option.selectList[value] === undefined || option.selectList[value] === '' || option.selectList[value] === null) {
return value;
} else {
return option.selectList[value];
}
},
filePreview: function (data) {
var mimeName = data.mime_type.split('/')[0];
if (mimeName == 'image') {
return admin.table.image(data);
} else {
var value = admin.table.returnColumnValue(data);
var groupName = admin.getExtGroupName(data.file_ext);
return '
';
}
},
image: function (data) {
var option = data.LAY_COL;
option.imageWidth = option.imageWidth || 200;
option.imageHeight = option.imageHeight || 26;
option.imageSplit = option.imageSplit || '|';
option.imageJoin = option.imageJoin || '
';
option.title = option.title || option.field;
var title = data[option.title];
var value = admin.table.returnColumnValue(data);
if (value === undefined || value === null) {
return '
';
} else {
var values = value.split(option.imageSplit),
valuesHtml = [];
values.forEach((value, index) => {
valuesHtml.push('
');
});
return valuesHtml.join(option.imageJoin);
}
},
url: function (data) {
var option = data.LAY_COL;
var urlNameField = option.urlNameField || '';
var value = admin.table.returnColumnValue(data);
if (admin.empty(value)) {
return '';
}
var urlName = value;
if (urlNameField != '') {
try {
var urlNameFieldType = typeof urlNameField;
if (urlNameFieldType == 'string') {
urlName = data[urlNameField];
} else if (urlNameFieldType == 'function') {
urlName = urlNameField(data);
}
} catch (e) {
}
}
return '' + urlName + '';
},
switch: function (data) {
var option = data.LAY_COL;
if (!admin.checkAuth('modify', option.init.tableElem)) {
return admin.table.list(data);
}
option.filter = option.filter || option.field || null;
option.checked = option.checked || 1;
var value = admin.table.returnColumnValue(data);
var checked = value === option.checked ? 'checked' : '';
return laytpl('').render(data);
},
price: function (data) {
var value = admin.table.returnColumnValue(data);
return '¥' + value + '';
},
percent: function (data) {
var value = admin.table.returnColumnValue(data);
return '' + value + '%';
},
icon: function (data) {
var value = admin.table.returnColumnValue(data);
return '';
},
text: function (data) {
var value = admin.table.returnColumnValue(data);
return '' + value + '';
},
value: function (data) {
var value = admin.table.returnColumnValue(data);
return '' + value + '';
},
//时间戳转日期
date: function (data) {
var option = data.LAY_COL;
value = admin.table.returnColumnValue(data);
if (!admin.empty(value)) {
value = util.toDateString(value * 1000, option.format || 'yyyy-MM-dd HH:mm:ss');
}
return '' + value + '';
},
bytes: (data) => {
var size = admin.table.returnColumnValue(data);
sizeReadable = admin.bytes(size);
return sizeReadable;
},
copyText(data) {
var option = data.LAY_COL;
var value = admin.table.returnColumnValue(data);
var copyValue = value;
var copyText = option.copyText;
if (typeof copyText === 'function') {
copyValue = copyText(value, data);
}
return ' ' + value + '';
},
// 统一列返回数据处理
returnColumnValue(data, field, defaultValue) {
if (!data.LAY_COL) {
return '';
}
var option = data.LAY_COL;
field = field || option.field;
defaultValue = defaultValue || option.defaultValue;
var valueParser = option.valueParser;
var value = undefined;
try {
value = eval("data." + field);
} catch (e) {
}
if (typeof valueParser == 'function') {
value = valueParser(value, data);
}
if (value === null || value === undefined) {
value = defaultValue;
}
return value;
},
listenTableSearch: function (tableId) {
form.on('submit(' + tableId + '_filter)', function (data) {
var dataField = data.field;
var formatFilter = {},
formatOp = {};
$.each(dataField, function (key, val) {
if (val !== '') {
formatFilter[key] = val;
var elemId = admin.table.renderSearchFormItemElementId(key);
var op = $('#c-' + elemId).attr('data-search-op');
op = op || '%*%';
formatOp[key] = op;
}
});
var where = {
filter: JSON.stringify(formatFilter),
op: JSON.stringify(formatOp)
};
lastTableWhere[tableId] = where;
table.reloadData(tableId, {
page: {
curr: 1
}
, where: where
}, 'data');
return false;
});
},
listenSwitch: function (option, ok) {
option.filter = option.filter || '';
option.url = option.url || '';
option.field = option.field || option.filter || '';
option.tableId = option.tableId || admin.init.tableRenderId;
option.modifyReload = option.modifyReload || false;
form.on('switch(' + option.filter + ')', function (obj) {
var checked = obj.elem.checked ? 1 : 0;
if (typeof ok === 'function') {
return ok({
id: obj.value,
checked: checked,
});
} else {
var data = {
id: obj.value,
field: option.field,
value: checked,
};
admin.request.post({
url: option.url,
prefix: true,
data: data,
}, function (res) {
if (option.modifyReload) {
table.reloadData(option.tableId);
}
}, function (res) {
admin.msg.error(res.msg, function () {
table.reloadData(option.tableId);
});
}, function () {
table.reloadData(option.tableId);
});
}
});
},
listenTableSort(option) {
//触发排序事件
table.on('sort(' + option.layFilter + ')', function (obj) { //注:sort 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
var lastWhere = lastTableWhere[option.id] ? lastTableWhere[option.id] : {};
lastWhere.sort = {};
lastWhere.sort[obj.field] = obj.type;
table.reloadData(option.id, {
initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
, where: lastWhere
});
});
},
listenToolbar: function (layFilter, tableId) {
table.on('toolbar(' + layFilter + ')', function (obj) {
var options = obj.config;
var tableId = obj.config.id;
// 搜索表单的显示
switch (obj.event) {
case 'TABLE_SEARCH':
var searchFieldsetId = 'searchFieldset_' + tableId;
var _that = $("#" + searchFieldsetId);
if (_that.hasClass("layui-hide")) {
_that.removeClass('layui-hide');
} else {
_that.addClass('layui-hide');
}
break;
case 'TABLE_LAYOUT':
var layoutElemId = 'layout-list-option-' + tableId;
var layoutElemIdName = '#' + layoutElemId;
var currentLayout = admin.getPageSetting('table-layout-default', 'table');
// 构建下拉选择
var layoutHtml = '';
options.layoutList.forEach(item => {
var currentClassName = '';
if (item.name == currentLayout) {
currentClassName = 'current';
}
layoutHtml += `
`;
});
layoutHtml += '
';
var toolbarLayoutElem = $('[lay-table-id="' + tableId + '"]').find('[lay-event="TABLE_LAYOUT"]');
if (toolbarLayoutElem.find(layoutElemIdName).length > 0) {
// If it is, remove the HTML
$(layoutElemIdName).remove();
}
layoulElem = $(layoutHtml);
layoulElem.appendTo(toolbarLayoutElem);
layoulElem.on('click', function (event) {
var item = $(event.target).closest('.item');
if (item.length > 0) {
// 点击操作
item.addClass('current').siblings().removeClass('current');
var layoutName = item.data('name');
admin.setPageSetting('table-layout-default', layoutName);
table.reloadData(tableId, {}, true);
} else {
// 其他区域操作
}
// 不要冒泡
event.stopPropagation();
});
// Remove any existing click event listeners to avoid duplicates
$(document).off('click.table-layout').on('click.table-layout', function (event) {
if (!$(event.target).closest(toolbarLayoutElem).length) {
// If it is, remove the HTML
$(layoutElemIdName).remove();
}
});
break;
}
});
},
listenEdit: function (tableInit, layFilter, tableId, modifyReload) {
tableInit.modifyUrl = tableInit.modifyUrl || false;
tableId = tableId || admin.init.tableRenderId;
if (tableInit.modifyUrl !== false) {
table.on('edit(' + layFilter + ')', function (obj) {
var value = obj.value,
data = obj.data,
id = data.id,
field = obj.field;
var _data = {
id: id,
field: field,
value: value,
};
admin.request.post({
url: tableInit.modifyUrl,
prefix: true,
data: _data,
}, function (res) {
if (modifyReload) {
table.reloadData(tableId);
}
}, function (res) {
admin.msg.error(res.msg, function () {
table.reloadData(tableId);
});
}, function () {
table.reloadData(tableId);
});
});
}
},
listenTableSelectConfirm(options) {
$('.select-confirm').click(function () {
var checkStatus = table.checkStatus(options.id);
if (checkStatus.data.length == 0) {
layer.msg('请选择数据');
return false;
}
parent.window[selectConfirmCallback](checkStatus.data);
});
},
listenExport: function (options) {
var exportFields = {};
var imageFields = [];
var selectFields = {};
var dateFields = [];
options.cols[0].forEach(col => {
if (col.field) {
exportFields[col.field] = col.title;
options.cols[0].forEach(col => {
if (col.field) {
exportFields[col.field] = col.title;
switch (col.fieldFormat) {
case 'image':
imageFields.push(col.field);
break;
case 'select':
if (Object.keys(col.selectList).length > 0) {
selectFields[col.field] = col.selectList;
}
break;
case 'date':
dateFields.push(col.field);
break;
default:
break;
}
}
});
}
});
// excel导出
$('body').on('click', '[data-table-export]', function () {
var tableId = $(this).attr('data-table-export'),
url = $(this).attr('data-url');
var searchVals = form.val(tableId + '_filter_form');
var dataField = searchVals;
var formatFilter = {},
formatOp = {};
$.each(dataField, function (key, val) {
if (val !== '') {
formatFilter[key] = val;
var elemId = admin.table.renderSearchFormItemElementId(key);
var op = $('#c-' + elemId).attr('data-search-op');
op = op || '%*%';
formatOp[key] = op;
}
});
var searchQuery = {
filter: JSON.stringify(formatFilter),
op: JSON.stringify(formatOp),
fields: JSON.stringify(exportFields),
image_fields: JSON.stringify(imageFields),
select_fields: JSON.stringify(selectFields),
date_fields: JSON.stringify(dateFields),
};
var query = $.param(searchQuery);
var index = admin.msg.confirm('根据查询进行导出,确定导出?', function () {
toUrl = admin.url(url);
if (toUrl.indexOf('?') < 0) {
toUrl += '?';
} else {
toUrl += '&';
}
toUrl += query;
window.open(toUrl);
layer.close(index);
});
});
},
renderSearchFormItemElementId(key) {
var elemId = key;
if (key.indexOf('[') == 0) {
var keyArr = key.replace('[', '').split(']');
elemId = keyArr[0] + '-' + keyArr[1];
}
elemId = elemId.replace('.', '-');
return elemId;
}
};
})();