require-table.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. define(['jquery', 'bootstrap', 'moment', 'moment/locale/zh-cn', 'bootstrap-table', 'bootstrap-table-lang', 'bootstrap-table-mobile', 'bootstrap-table-export', 'bootstrap-table-commonsearch', 'bootstrap-table-template'], function ($, undefined, Moment) {
  2. var Table = {
  3. list: {},
  4. // Bootstrap-table 基础配置
  5. defaults: {
  6. url: '',
  7. sidePagination: 'server',
  8. method: 'get',
  9. toolbar: "#toolbar",
  10. search: true,
  11. cache: false,
  12. commonSearch: true,
  13. searchFormVisible: false,
  14. titleForm: '', //为空则不显示标题,不定义默认显示:普通搜索
  15. idTable: 'commonTable',
  16. showExport: true,
  17. exportDataType: "all",
  18. exportTypes: ['json', 'xml', 'csv', 'txt', 'doc', 'excel'],
  19. pageSize: 10,
  20. pageList: [10, 25, 50, 'All'],
  21. pagination: true,
  22. clickToSelect: true,
  23. showRefresh: false,
  24. locale: 'zh-CN',
  25. showToggle: true,
  26. showColumns: true,
  27. pk: 'id',
  28. sortName: 'id',
  29. sortOrder: 'desc',
  30. paginationFirstText: __("First"),
  31. paginationPreText: __("Previous"),
  32. paginationNextText: __("Next"),
  33. paginationLastText: __("Last"),
  34. mobileResponsive: true,
  35. cardView: true,
  36. checkOnInit: true,
  37. escape: true,
  38. extend: {
  39. index_url: '',
  40. add_url: '',
  41. edit_url: '',
  42. del_url: '',
  43. multi_url: '',
  44. dragsort_url: 'ajax/weigh',
  45. }
  46. },
  47. // Bootstrap-table 列配置
  48. columnDefaults: {
  49. align: 'center',
  50. valign: 'middle',
  51. },
  52. config: {
  53. firsttd: 'tbody tr td:first-child:not(:has(div.card-views))',
  54. toolbar: '.toolbar',
  55. refreshbtn: '.btn-refresh',
  56. addbtn: '.btn-add',
  57. editbtn: '.btn-edit',
  58. delbtn: '.btn-del',
  59. multibtn: '.btn-multi',
  60. disabledbtn: '.btn-disabled',
  61. editonebtn: '.btn-editone',
  62. dragsortfield: 'weigh',
  63. },
  64. api: {
  65. init: function (defaults, columnDefaults, locales) {
  66. defaults = defaults ? defaults : {};
  67. columnDefaults = columnDefaults ? columnDefaults : {};
  68. locales = locales ? locales : {};
  69. // 写入bootstrap-table默认配置
  70. $.extend(true, $.fn.bootstrapTable.defaults, Table.defaults, defaults);
  71. // 写入bootstrap-table column配置
  72. $.extend($.fn.bootstrapTable.columnDefaults, Table.columnDefaults, columnDefaults);
  73. // 写入bootstrap-table locale配置
  74. $.extend($.fn.bootstrapTable.locales[Table.defaults.locale], {
  75. formatCommonSearch: function () {
  76. return __('Common search');
  77. },
  78. formatCommonSubmitButton: function () {
  79. return __('Submit');
  80. },
  81. formatCommonResetButton: function () {
  82. return __('Reset');
  83. },
  84. formatCommonCloseButton: function () {
  85. return __('Close');
  86. },
  87. formatCommonChoose: function () {
  88. return __('Choose');
  89. }
  90. }, locales);
  91. },
  92. // 绑定事件
  93. bindevent: function (table) {
  94. //Bootstrap-table的父元素,包含table,toolbar,pagnation
  95. var parenttable = table.closest('.bootstrap-table');
  96. //Bootstrap-table配置
  97. var options = table.bootstrapTable('getOptions');
  98. //Bootstrap操作区
  99. var toolbar = $(options.toolbar, parenttable);
  100. //当刷新表格时
  101. table.on('load-error.bs.table', function (status, res) {
  102. Toastr.error(__('Unknown data format'));
  103. });
  104. //当刷新表格时
  105. table.on('refresh.bs.table', function (e, settings, data) {
  106. $(Table.config.refreshbtn, toolbar).find(".fa").addClass("fa-spin");
  107. });
  108. //当双击单元格时
  109. table.on('dbl-click-row.bs.table', function (e, row, element, field) {
  110. $(Table.config.editonebtn, element).trigger("click");
  111. });
  112. //当内容渲染完成后
  113. table.on('post-body.bs.table', function (e, settings, json, xhr) {
  114. $(Table.config.refreshbtn, toolbar).find(".fa").removeClass("fa-spin");
  115. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', true);
  116. if ($(Table.config.firsttd, table).find("input[type='checkbox'][data-index]").size() > 0) {
  117. // 挺拽选择,需要重新绑定事件
  118. require(['drag', 'drop'], function () {
  119. $(Table.config.firsttd, table).drag("start", function (ev, dd) {
  120. return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
  121. }).drag(function (ev, dd) {
  122. $(dd.proxy).css({
  123. top: Math.min(ev.pageY, dd.startY),
  124. left: Math.min(ev.pageX, dd.startX),
  125. height: Math.abs(ev.pageY - dd.startY),
  126. width: Math.abs(ev.pageX - dd.startX)
  127. });
  128. }).drag("end", function (ev, dd) {
  129. $(dd.proxy).remove();
  130. });
  131. $(Table.config.firsttd, table).drop("start", function () {
  132. Table.api.toggleattr(this);
  133. }).drop(function () {
  134. Table.api.toggleattr(this);
  135. }).drop("end", function () {
  136. Table.api.toggleattr(this);
  137. });
  138. $.drop({
  139. multi: true
  140. });
  141. });
  142. }
  143. });
  144. // 处理选中筛选框后按钮的状态统一变更
  145. table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
  146. var ids = Table.api.selectedids(table);
  147. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', !ids.length);
  148. });
  149. // 刷新按钮事件
  150. $(toolbar).on('click', Table.config.refreshbtn, function () {
  151. table.bootstrapTable('refresh');
  152. });
  153. // 添加按钮事件
  154. $(toolbar).on('click', Table.config.addbtn, function () {
  155. var ids = Table.api.selectedids(table);
  156. Fast.api.open(options.extend.add_url + (ids.length > 0 ? (options.extend.add_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ids.join(",") : ''), __('Add'), $(this).data() || {});
  157. });
  158. // 批量编辑按钮事件
  159. $(toolbar).on('click', Table.config.editbtn, function () {
  160. var ids = Table.api.selectedids(table);
  161. //循环弹出多个编辑框
  162. $.each(ids, function (i, j) {
  163. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + j, __('Edit'), $(this).data() || {});
  164. });
  165. });
  166. // 批量操作按钮事件
  167. $(toolbar).on('click', Table.config.multibtn, function () {
  168. var ids = Table.api.selectedids(table);
  169. Table.api.multi($(this).data("action"), ids, table, this);
  170. });
  171. // 批量删除按钮事件
  172. $(toolbar).on('click', Table.config.delbtn, function () {
  173. var that = this;
  174. var ids = Table.api.selectedids(table);
  175. var index = Layer.confirm(
  176. __('Are you sure you want to delete the %s selected item?', ids.length),
  177. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  178. function () {
  179. Table.api.multi("del", ids, table, that);
  180. Layer.close(index);
  181. }
  182. );
  183. });
  184. // 拖拽排序
  185. require(['dragsort'], function () {
  186. //绑定拖动排序
  187. $("tbody", table).dragsort({
  188. itemSelector: 'tr',
  189. dragSelector: "a.btn-dragsort",
  190. dragEnd: function () {
  191. var data = table.bootstrapTable('getData');
  192. var current = data[parseInt($(this).data("index"))];
  193. var options = table.bootstrapTable('getOptions');
  194. //改变的值和改变的ID集合
  195. var ids = $.map($("tbody tr:visible", table), function (tr) {
  196. return data[parseInt($(tr).data("index"))][options.pk];
  197. });
  198. var changeid = current[options.pk];
  199. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  200. var params = {
  201. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  202. data: {
  203. ids: ids.join(','),
  204. changeid: changeid,
  205. pid: pid,
  206. field: Table.config.dragsortfield,
  207. orderway: options.sortOrder,
  208. table: options.extend.table
  209. }
  210. };
  211. Fast.api.ajax(params, function (data) {
  212. table.bootstrapTable('refresh');
  213. });
  214. },
  215. placeHolderTemplate: ""
  216. });
  217. });
  218. $(table).on("click", "input[data-id][name='checkbox']", function (e) {
  219. table.trigger('fa.event.check');
  220. });
  221. $(table).on("click", "[data-id].btn-change", function (e) {
  222. e.preventDefault();
  223. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  224. });
  225. $(table).on("click", "[data-id].btn-edit", function (e) {
  226. e.preventDefault();
  227. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + $(this).data("id"), __('Edit'), $(this).data() || {});
  228. });
  229. $(table).on("click", "[data-id].btn-del", function (e) {
  230. e.preventDefault();
  231. var id = $(this).data("id");
  232. var that = this;
  233. var index = Layer.confirm(
  234. __('Are you sure you want to delete this item?'),
  235. {icon: 3, title: __('Warning'), shadeClose: true},
  236. function () {
  237. Table.api.multi("del", id, table, that);
  238. Layer.close(index);
  239. }
  240. );
  241. });
  242. var id = table.attr("id");
  243. Table.list[id] = table;
  244. return table;
  245. },
  246. // 批量操作请求
  247. multi: function (action, ids, table, element) {
  248. var options = table.bootstrapTable('getOptions');
  249. var data = element ? $(element).data() : {};
  250. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  251. url = url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ($.isArray(ids) ? ids.join(",") : ids);
  252. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  253. var options = {url: url, data: {action: action, ids: ids, params: params}};
  254. Fast.api.ajax(options, function (data) {
  255. table.bootstrapTable('refresh');
  256. });
  257. },
  258. // 单元格元素事件
  259. events: {
  260. operate: {
  261. 'click .btn-editone': function (e, value, row, index) {
  262. e.stopPropagation();
  263. var options = $(this).closest('table').bootstrapTable('getOptions');
  264. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk], __('Edit'), $(this).data() || {});
  265. },
  266. 'click .btn-delone': function (e, value, row, index) {
  267. e.stopPropagation();
  268. var that = this;
  269. var top = $(that).offset().top - $(window).scrollTop();
  270. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  271. if (top + 154 > $(window).height()) {
  272. top = top - 154;
  273. }
  274. if ($(window).width() < 480) {
  275. top = left = undefined;
  276. }
  277. var index = Layer.confirm(
  278. __('Are you sure you want to delete this item?'),
  279. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  280. function () {
  281. var table = $(that).closest('table');
  282. var options = table.bootstrapTable('getOptions');
  283. Table.api.multi("del", row[options.pk], table, that);
  284. Layer.close(index);
  285. }
  286. );
  287. }
  288. }
  289. },
  290. // 单元格数据格式化
  291. formatter: {
  292. icon: function (value, row, index) {
  293. if (!value)
  294. return '';
  295. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  296. //渲染fontawesome图标
  297. return '<i class="' + value + '"></i> ' + value;
  298. },
  299. image: function (value, row, index) {
  300. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  301. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  302. },
  303. images: function (value, row, index) {
  304. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  305. var arr = value.split(',');
  306. var html = [];
  307. $.each(arr, function (i, value) {
  308. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  309. });
  310. return html.join(' ');
  311. },
  312. status: function (value, row, index) {
  313. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  314. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  315. //如果字段列有定义custom
  316. if (typeof this.custom !== 'undefined') {
  317. colorArr = $.extend(colorArr, this.custom);
  318. }
  319. value = value.toString();
  320. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  321. value = value.charAt(0).toUpperCase() + value.slice(1);
  322. //渲染状态
  323. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  324. return html;
  325. },
  326. url: function (value, row, index) {
  327. return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
  328. },
  329. search: function (value, row, index) {
  330. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  331. },
  332. addtabs: function (value, row, index) {
  333. var url = Table.api.replaceurl(this.url, value, row, this.table);
  334. var title = this.title ? this.title : __("Search %s", value);
  335. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  336. },
  337. dialog: function (value, row, index) {
  338. var url = Table.api.replaceurl(this.url, value, row, this.table);
  339. var title = this.title ? this.title : value;
  340. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  341. },
  342. flag: function (value, row, index) {
  343. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  344. //如果字段列有定义custom
  345. if (typeof this.custom !== 'undefined') {
  346. colorArr = $.extend(colorArr, this.custom);
  347. }
  348. //渲染Flag
  349. var html = [];
  350. var arr = value.split(',');
  351. $.each(arr, function (i, value) {
  352. value = value.toString();
  353. if (value == '')
  354. return true;
  355. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  356. value = value.charAt(0).toUpperCase() + value.slice(1);
  357. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  358. });
  359. return html.join(' ');
  360. },
  361. label: function (value, row, index) {
  362. var colorArr = ['success', 'warning', 'danger', 'info'];
  363. //如果字段列有定义custom
  364. if (typeof this.custom !== 'undefined') {
  365. colorArr = $.merge(colorArr, this.custom);
  366. }
  367. //渲染Flag
  368. var html = [];
  369. var arr = value.split(',');
  370. $.each(arr, function (i, value) {
  371. value = value.toString();
  372. var color = colorArr[i % colorArr.length];
  373. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  374. });
  375. return html.join(' ');
  376. },
  377. datetime: function (value, row, index) {
  378. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  379. },
  380. operate: function (value, row, index) {
  381. var table = this.table;
  382. // 操作配置
  383. var options = table ? table.bootstrapTable('getOptions') : {};
  384. // 默认按钮组
  385. var buttons = $.extend([], this.buttons || []);
  386. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  387. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone'});
  388. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  389. var html = [];
  390. var url, classname, icon, text, title, extend;
  391. $.each(buttons, function (i, j) {
  392. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  393. return true;
  394. }
  395. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  396. return true;
  397. }
  398. var attr = table.data("operate-" + j.name);
  399. if (typeof attr === 'undefined' || attr) {
  400. url = j.url ? j.url : '';
  401. if (url.indexOf("{ids}") === -1) {
  402. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  403. }
  404. url = Table.api.replaceurl(url, value, row, table);
  405. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  406. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  407. icon = j.icon ? j.icon : '';
  408. text = j.text ? j.text : '';
  409. title = j.title ? j.title : text;
  410. extend = j.extend ? j.extend : '';
  411. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  412. }
  413. });
  414. return html.join(' ');
  415. },
  416. buttons: function (value, row, index) {
  417. var table = this.table;
  418. // 操作配置
  419. var options = table ? table.bootstrapTable('getOptions') : {};
  420. // 默认按钮组
  421. var buttons = $.extend([], this.buttons || []);
  422. var html = [];
  423. var url, classname, icon, text, title, extend;
  424. $.each(buttons, function (i, j) {
  425. var attr = table.data("buttons-" + j.name);
  426. if (typeof attr === 'undefined' || attr) {
  427. url = j.url ? j.url : '';
  428. if (url.indexOf("{ids}") === -1) {
  429. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  430. }
  431. url = Table.api.replaceurl(url, value, row, table);
  432. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  433. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  434. icon = j.icon ? j.icon : '';
  435. text = j.text ? j.text : '';
  436. title = j.title ? j.title : text;
  437. extend = j.extend ? j.extend : '';
  438. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  439. }
  440. });
  441. return html.join(' ');
  442. }
  443. },
  444. //替换URL中的{ids}和{value}
  445. replaceurl: function (url, value, row, table) {
  446. url = url ? url : '';
  447. url = url.replace(/\{value\}/ig, value);
  448. if (table) {
  449. var options = table.bootstrapTable('getOptions');
  450. url = url.replace(/\{ids\}/ig, row[options.pk]);
  451. } else {
  452. url = url.replace(/\{ids\}/ig, 0);
  453. }
  454. return url;
  455. },
  456. // 获取选中的条目ID集合
  457. selectedids: function (table) {
  458. var options = table.bootstrapTable('getOptions');
  459. if (options.templateView) {
  460. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  461. return $(dom).data("id");
  462. });
  463. } else {
  464. return $.map(table.bootstrapTable('getSelections'), function (row) {
  465. return row[options.pk];
  466. });
  467. }
  468. },
  469. // 切换复选框状态
  470. toggleattr: function (table) {
  471. $("input[type='checkbox']", table).trigger('click');
  472. }
  473. },
  474. };
  475. return Table;
  476. });