require-table.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. value=value?value:'/assets/img/blank.gif';
  302. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  303. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  304. },
  305. images: function (value, row, index) {
  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. value=value?value:'/assets/img/blank.gif';
  311. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  312. });
  313. return html.join(' ');
  314. },
  315. status: function (value, row, index) {
  316. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  317. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  318. //如果字段列有定义custom
  319. if (typeof this.custom !== 'undefined') {
  320. colorArr = $.extend(colorArr, this.custom);
  321. }
  322. value = value.toString();
  323. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  324. value = value.charAt(0).toUpperCase() + value.slice(1);
  325. //渲染状态
  326. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  327. return html;
  328. },
  329. url: function (value, row, index) {
  330. 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>';
  331. },
  332. search: function (value, row, index) {
  333. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  334. },
  335. addtabs: function (value, row, index) {
  336. var url = Table.api.replaceurl(this.url, value, row, this.table);
  337. var title = this.title ? this.title : __("Search %s", value);
  338. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  339. },
  340. dialog: function (value, row, index) {
  341. var url = Table.api.replaceurl(this.url, value, row, this.table);
  342. var title = this.title ? this.title : value;
  343. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  344. },
  345. flag: function (value, row, index) {
  346. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  347. //如果字段列有定义custom
  348. if (typeof this.custom !== 'undefined') {
  349. colorArr = $.extend(colorArr, this.custom);
  350. }
  351. //渲染Flag
  352. var html = [];
  353. var arr = value.split(',');
  354. $.each(arr, function (i, value) {
  355. value = value.toString();
  356. if (value == '')
  357. return true;
  358. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  359. value = value.charAt(0).toUpperCase() + value.slice(1);
  360. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  361. });
  362. return html.join(' ');
  363. },
  364. label: function (value, row, index) {
  365. var colorArr = ['success', 'warning', 'danger', 'info'];
  366. //如果字段列有定义custom
  367. if (typeof this.custom !== 'undefined') {
  368. colorArr = $.merge(colorArr, this.custom);
  369. }
  370. //渲染Flag
  371. var html = [];
  372. var arr = value.split(',');
  373. $.each(arr, function (i, value) {
  374. value = value.toString();
  375. var color = colorArr[i % colorArr.length];
  376. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  377. });
  378. return html.join(' ');
  379. },
  380. datetime: function (value, row, index) {
  381. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  382. },
  383. operate: function (value, row, index) {
  384. var table = this.table;
  385. // 操作配置
  386. var options = table ? table.bootstrapTable('getOptions') : {};
  387. // 默认按钮组
  388. var buttons = $.extend([], this.buttons || []);
  389. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  390. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone'});
  391. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  392. var html = [];
  393. var url, classname, icon, text, title, extend;
  394. $.each(buttons, function (i, j) {
  395. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  396. return true;
  397. }
  398. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  399. return true;
  400. }
  401. var attr = table.data("operate-" + j.name);
  402. if (typeof attr === 'undefined' || attr) {
  403. url = j.url ? j.url : '';
  404. if (url.indexOf("{ids}") === -1) {
  405. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  406. }
  407. url = Table.api.replaceurl(url, value, row, table);
  408. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  409. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  410. icon = j.icon ? j.icon : '';
  411. text = j.text ? j.text : '';
  412. title = j.title ? j.title : text;
  413. extend = j.extend ? j.extend : '';
  414. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  415. }
  416. });
  417. return html.join(' ');
  418. },
  419. buttons: function (value, row, index) {
  420. var table = this.table;
  421. // 操作配置
  422. var options = table ? table.bootstrapTable('getOptions') : {};
  423. // 默认按钮组
  424. var buttons = $.extend([], this.buttons || []);
  425. var html = [];
  426. var url, classname, icon, text, title, extend;
  427. $.each(buttons, function (i, j) {
  428. var attr = table.data("buttons-" + j.name);
  429. if (typeof attr === 'undefined' || attr) {
  430. url = j.url ? j.url : '';
  431. if (url.indexOf("{ids}") === -1) {
  432. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  433. }
  434. url = Table.api.replaceurl(url, value, row, table);
  435. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  436. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  437. icon = j.icon ? j.icon : '';
  438. text = j.text ? j.text : '';
  439. title = j.title ? j.title : text;
  440. extend = j.extend ? j.extend : '';
  441. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  442. }
  443. });
  444. return html.join(' ');
  445. }
  446. },
  447. //替换URL中的{ids}和{value}
  448. replaceurl: function (url, value, row, table) {
  449. url = url ? url : '';
  450. url = url.replace(/\{value\}/ig, value);
  451. if (table) {
  452. var options = table.bootstrapTable('getOptions');
  453. url = url.replace(/\{ids\}/ig, row[options.pk]);
  454. } else {
  455. url = url.replace(/\{ids\}/ig, 0);
  456. }
  457. return url;
  458. },
  459. // 获取选中的条目ID集合
  460. selectedids: function (table) {
  461. var options = table.bootstrapTable('getOptions');
  462. if (options.templateView) {
  463. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  464. return $(dom).data("id");
  465. });
  466. } else {
  467. return $.map(table.bootstrapTable('getSelections'), function (row) {
  468. return row[options.pk];
  469. });
  470. }
  471. },
  472. // 切换复选框状态
  473. toggleattr: function (table) {
  474. $("input[type='checkbox']", table).trigger('click');
  475. }
  476. },
  477. };
  478. return Table;
  479. });