require-table.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. define(['jquery', 'bootstrap', 'moment', '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" + (ids.length > 0 ? '/' : '') + ids.join(","), __('Add'));
  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 + "/ids/" + j, __('Edit'));
  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. Toastr.success(__('Operation completed'));
  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 + "/ids/" + $(this).data("id"), __('Edit'));
  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. Toastr.success(__('Operation completed'));
  257. table.bootstrapTable('refresh');
  258. });
  259. },
  260. // 单元格元素事件
  261. events: {
  262. operate: {
  263. 'click .btn-editone': function (e, value, row, index) {
  264. e.stopPropagation();
  265. var options = $(this).closest('table').bootstrapTable('getOptions');
  266. Fast.api.open(options.extend.edit_url + "/ids/" + row[options.pk], __('Edit'));
  267. },
  268. 'click .btn-delone': function (e, value, row, index) {
  269. e.stopPropagation();
  270. var that = this;
  271. var top = $(that).offset().top - $(window).scrollTop();
  272. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  273. if (top + 154 > $(window).height()) {
  274. top = top - 154;
  275. }
  276. if ($(window).width() < 480) {
  277. top = left = undefined;
  278. }
  279. var index = Layer.confirm(
  280. __('Are you sure you want to delete this item?'),
  281. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  282. function () {
  283. var table = $(that).closest('table');
  284. var options = table.bootstrapTable('getOptions');
  285. Table.api.multi("del", row[options.pk], table, that);
  286. Layer.close(index);
  287. }
  288. );
  289. }
  290. }
  291. },
  292. // 单元格数据格式化
  293. formatter: {
  294. icon: function (value, row, index) {
  295. if (!value)
  296. return '';
  297. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  298. //渲染fontawesome图标
  299. return '<i class="' + value + '"></i> ' + value;
  300. },
  301. image: function (value, row, index, custom) {
  302. var classname = typeof custom !== 'undefined' ? custom : 'img-sm img-center';
  303. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  304. },
  305. images: function (value, row, index, custom) {
  306. var classname = typeof custom !== 'undefined' ? custom : '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, custom) {
  315. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  316. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  317. //如果有自定义状态,可以按需传入
  318. if (typeof custom !== 'undefined') {
  319. colorArr = $.extend(colorArr, 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, url) {
  335. return '<a href="' + url + '" class="addtabsit" title="' + __("Search %s", value) + '">' + value + '</a>';
  336. },
  337. flag: function (value, row, index, custom) {
  338. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  339. //如果有自定义状态,可以按需传入
  340. if (typeof custom !== 'undefined') {
  341. colorArr = $.extend(colorArr, custom);
  342. }
  343. //渲染Flag
  344. var html = [];
  345. var arr = value.split(',');
  346. $.each(arr, function (i, value) {
  347. value = value.toString();
  348. if (value == '')
  349. return true;
  350. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  351. value = value.charAt(0).toUpperCase() + value.slice(1);
  352. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  353. });
  354. return html.join(' ');
  355. },
  356. label: function (value, row, index, custom) {
  357. var colorArr = ['success', 'warning', 'danger', 'info'];
  358. //渲染Flag
  359. var html = [];
  360. var arr = value.split(',');
  361. $.each(arr, function (i, value) {
  362. value = value.toString();
  363. var color = colorArr[i % colorArr.length];
  364. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  365. });
  366. return html.join(' ');
  367. },
  368. datetime: function (value, row, index) {
  369. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  370. },
  371. operate: function (value, row, index, table) {
  372. var showweigh = true;
  373. var showedit = true;
  374. var showdel = true;
  375. if (typeof table != 'undefined') {
  376. var options = table.bootstrapTable('getOptions');
  377. if (options.extend.del_url == '')
  378. showdel = false;
  379. if (options.extend.edit_url == '')
  380. showedit = false;
  381. }
  382. showweigh = typeof row[Table.config.dragsortfield] != 'undefined' ? true : false;
  383. //行操作
  384. var html = [];
  385. if (showweigh)
  386. html.push('<a href="javascript:;" class="btn btn-primary btn-dragsort btn-xs"><i class="fa fa-arrows"></i></a>');
  387. if (showedit)
  388. html.push('<a href="javascript:;" class="btn btn-success btn-editone btn-xs"><i class="fa fa-pencil"></i></a>');
  389. if (showdel)
  390. html.push('<a href="javascript:;" class="btn btn-danger btn-delone btn-xs"><i class="fa fa-trash"></i></a>');
  391. return html.join(' ');
  392. }
  393. },
  394. // 获取选中的条目ID集合
  395. selectedids: function (table) {
  396. var options = table.bootstrapTable('getOptions');
  397. if (options.templateView) {
  398. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  399. return $(dom).data("id");
  400. });
  401. } else {
  402. return $.map(table.bootstrapTable('getSelections'), function (row) {
  403. return row[options.pk];
  404. });
  405. }
  406. },
  407. // 切换复选框状态
  408. toggleattr: function (table) {
  409. $("input[type='checkbox']", table).trigger('click');
  410. }
  411. },
  412. };
  413. return Table;
  414. });