require-table.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. var that = this;
  162. //循环弹出多个编辑框
  163. $.each(ids, function (i, j) {
  164. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + j, __('Edit'), $(that).data() || {});
  165. });
  166. });
  167. // 批量操作按钮事件
  168. $(toolbar).on('click', Table.config.multibtn, function () {
  169. var ids = Table.api.selectedids(table);
  170. Table.api.multi($(this).data("action"), ids, table, this);
  171. });
  172. // 批量删除按钮事件
  173. $(toolbar).on('click', Table.config.delbtn, function () {
  174. var that = this;
  175. var ids = Table.api.selectedids(table);
  176. var index = Layer.confirm(
  177. __('Are you sure you want to delete the %s selected item?', ids.length),
  178. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  179. function () {
  180. Table.api.multi("del", ids, table, that);
  181. Layer.close(index);
  182. }
  183. );
  184. });
  185. // 拖拽排序
  186. require(['dragsort'], function () {
  187. //绑定拖动排序
  188. $("tbody", table).dragsort({
  189. itemSelector: 'tr',
  190. dragSelector: "a.btn-dragsort",
  191. dragEnd: function () {
  192. var data = table.bootstrapTable('getData');
  193. var current = data[parseInt($(this).data("index"))];
  194. var options = table.bootstrapTable('getOptions');
  195. //改变的值和改变的ID集合
  196. var ids = $.map($("tbody tr:visible", table), function (tr) {
  197. return data[parseInt($(tr).data("index"))][options.pk];
  198. });
  199. var changeid = current[options.pk];
  200. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  201. var params = {
  202. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  203. data: {
  204. ids: ids.join(','),
  205. changeid: changeid,
  206. pid: pid,
  207. field: Table.config.dragsortfield,
  208. orderway: options.sortOrder,
  209. table: options.extend.table
  210. }
  211. };
  212. Fast.api.ajax(params, function (data) {
  213. table.bootstrapTable('refresh');
  214. });
  215. },
  216. placeHolderTemplate: ""
  217. });
  218. });
  219. $(table).on("click", "input[data-id][name='checkbox']", function (e) {
  220. table.trigger('fa.event.check');
  221. });
  222. $(table).on("click", "[data-id].btn-change", function (e) {
  223. e.preventDefault();
  224. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  225. });
  226. $(table).on("click", "[data-id].btn-edit", function (e) {
  227. e.preventDefault();
  228. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + $(this).data("id"), __('Edit'), $(this).data() || {});
  229. });
  230. $(table).on("click", "[data-id].btn-del", function (e) {
  231. e.preventDefault();
  232. var id = $(this).data("id");
  233. var that = this;
  234. var index = Layer.confirm(
  235. __('Are you sure you want to delete this item?'),
  236. {icon: 3, title: __('Warning'), shadeClose: true},
  237. function () {
  238. Table.api.multi("del", id, table, that);
  239. Layer.close(index);
  240. }
  241. );
  242. });
  243. var id = table.attr("id");
  244. Table.list[id] = table;
  245. return table;
  246. },
  247. // 批量操作请求
  248. multi: function (action, ids, table, element) {
  249. var options = table.bootstrapTable('getOptions');
  250. var data = element ? $(element).data() : {};
  251. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  252. url = url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ($.isArray(ids) ? ids.join(",") : ids);
  253. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  254. var options = {url: url, data: {action: action, ids: ids, params: params}};
  255. Fast.api.ajax(options, function (data) {
  256. table.bootstrapTable('refresh');
  257. });
  258. },
  259. // 单元格元素事件
  260. events: {
  261. operate: {
  262. 'click .btn-editone': function (e, value, row, index) {
  263. e.stopPropagation();
  264. var options = $(this).closest('table').bootstrapTable('getOptions');
  265. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk], __('Edit'), $(this).data() || {});
  266. },
  267. 'click .btn-delone': function (e, value, row, index) {
  268. e.stopPropagation();
  269. var that = this;
  270. var top = $(that).offset().top - $(window).scrollTop();
  271. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  272. if (top + 154 > $(window).height()) {
  273. top = top - 154;
  274. }
  275. if ($(window).width() < 480) {
  276. top = left = undefined;
  277. }
  278. var index = Layer.confirm(
  279. __('Are you sure you want to delete this item?'),
  280. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  281. function () {
  282. var table = $(that).closest('table');
  283. var options = table.bootstrapTable('getOptions');
  284. Table.api.multi("del", row[options.pk], table, that);
  285. Layer.close(index);
  286. }
  287. );
  288. }
  289. }
  290. },
  291. // 单元格数据格式化
  292. formatter: {
  293. icon: function (value, row, index) {
  294. if (!value)
  295. return '';
  296. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  297. //渲染fontawesome图标
  298. return '<i class="' + value + '"></i> ' + value;
  299. },
  300. image: function (value, row, index) {
  301. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  302. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  303. },
  304. images: function (value, row, index) {
  305. value = value.toString();
  306. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  307. var arr = value.split(',');
  308. var html = [];
  309. $.each(arr, function (i, value) {
  310. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  311. });
  312. return html.join(' ');
  313. },
  314. status: function (value, row, index) {
  315. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  316. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  317. //如果字段列有定义custom
  318. if (typeof this.custom !== 'undefined') {
  319. colorArr = $.extend(colorArr, this.custom);
  320. }
  321. value = value.toString();
  322. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  323. value = value.charAt(0).toUpperCase() + value.slice(1);
  324. //渲染状态
  325. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  326. return html;
  327. },
  328. url: function (value, row, index) {
  329. 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>';
  330. },
  331. search: function (value, row, index) {
  332. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  333. },
  334. addtabs: function (value, row, index) {
  335. var url = Table.api.replaceurl(this.url, value, row, this.table);
  336. var title = this.atitle ? this.atitle : __("Search %s", value);
  337. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  338. },
  339. dialog: function (value, row, index) {
  340. var url = Table.api.replaceurl(this.url, value, row, this.table);
  341. var title = this.atitle ? this.atitle : __("View %s", value);
  342. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  343. },
  344. flag: function (value, row, index) {
  345. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  346. //如果字段列有定义custom
  347. if (typeof this.custom !== 'undefined') {
  348. colorArr = $.extend(colorArr, this.custom);
  349. }
  350. //渲染Flag
  351. var html = [];
  352. var arr = value.split(',');
  353. $.each(arr, function (i, value) {
  354. value = value.toString();
  355. if (value == '')
  356. return true;
  357. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  358. value = value.charAt(0).toUpperCase() + value.slice(1);
  359. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  360. });
  361. return html.join(' ');
  362. },
  363. label: function (value, row, index) {
  364. return Table.api.formatter.flag.call(this, value, row, index);
  365. },
  366. datetime: function (value, row, index) {
  367. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  368. },
  369. operate: function (value, row, index) {
  370. var table = this.table;
  371. // 操作配置
  372. var options = table ? table.bootstrapTable('getOptions') : {};
  373. // 默认按钮组
  374. var buttons = $.extend([], this.buttons || []);
  375. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  376. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone'});
  377. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  378. var html = [];
  379. var url, classname, icon, text, title, extend;
  380. $.each(buttons, function (i, j) {
  381. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  382. return true;
  383. }
  384. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  385. return true;
  386. }
  387. var attr = table.data("operate-" + j.name);
  388. if (typeof attr === 'undefined' || attr) {
  389. url = j.url ? j.url : '';
  390. if (url.indexOf("{ids}") === -1) {
  391. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  392. }
  393. url = Table.api.replaceurl(url, value, row, table);
  394. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  395. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  396. icon = j.icon ? j.icon : '';
  397. text = j.text ? j.text : '';
  398. title = j.title ? j.title : text;
  399. extend = j.extend ? j.extend : '';
  400. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  401. }
  402. });
  403. return html.join(' ');
  404. },
  405. buttons: function (value, row, index) {
  406. var table = this.table;
  407. // 操作配置
  408. var options = table ? table.bootstrapTable('getOptions') : {};
  409. // 默认按钮组
  410. var buttons = $.extend([], this.buttons || []);
  411. var html = [];
  412. var url, classname, icon, text, title, extend;
  413. $.each(buttons, function (i, j) {
  414. var attr = table.data("buttons-" + j.name);
  415. if (typeof attr === 'undefined' || attr) {
  416. url = j.url ? j.url : '';
  417. if (url.indexOf("{ids}") === -1) {
  418. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  419. }
  420. url = Table.api.replaceurl(url, value, row, table);
  421. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  422. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  423. icon = j.icon ? j.icon : '';
  424. text = j.text ? j.text : '';
  425. title = j.title ? j.title : text;
  426. extend = j.extend ? j.extend : '';
  427. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  428. }
  429. });
  430. return html.join(' ');
  431. }
  432. },
  433. //替换URL中的{ids}和{value}
  434. replaceurl: function (url, value, row, table) {
  435. url = url ? url : '';
  436. url = url.replace(/\{value\}/ig, value);
  437. if (table) {
  438. var options = table.bootstrapTable('getOptions');
  439. url = url.replace(/\{ids\}/ig, row[options.pk]);
  440. } else {
  441. url = url.replace(/\{ids\}/ig, 0);
  442. }
  443. return url;
  444. },
  445. // 获取选中的条目ID集合
  446. selectedids: function (table) {
  447. var options = table.bootstrapTable('getOptions');
  448. if (options.templateView) {
  449. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  450. return $(dom).data("id");
  451. });
  452. } else {
  453. return $.map(table.bootstrapTable('getSelections'), function (row) {
  454. return row[options.pk];
  455. });
  456. }
  457. },
  458. // 切换复选框状态
  459. toggleattr: function (table) {
  460. $("input[type='checkbox']", table).trigger('click');
  461. }
  462. },
  463. };
  464. return Table;
  465. });