require-table.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. define(['jquery', 'bootstrap', 'backend', 'toastr', 'moment', 'bootstrap-table', 'bootstrap-table-lang', 'bootstrap-table-mobile', 'bootstrap-table-export', 'bootstrap-table-commonsearch'], function ($, undefined, Backend, Toastr, 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. extend: {
  38. index_url: '',
  39. add_url: '',
  40. edit_url: '',
  41. del_url: '',
  42. multi_url: '',
  43. dragsort_url: 'ajax/weigh',
  44. }
  45. },
  46. // Bootstrap-table 列配置
  47. columnDefaults: {
  48. align: 'center',
  49. valign: 'middle',
  50. },
  51. config: {
  52. firsttd: 'tbody tr td:first-child:not(:has(div.card-views))',
  53. toolbar: '.toolbar',
  54. refreshbtn: '.btn-refresh',
  55. addbtn: '.btn-add',
  56. editbtn: '.btn-edit',
  57. delbtn: '.btn-del',
  58. multibtn: '.btn-multi',
  59. disabledbtn: '.btn-disabled',
  60. editonebtn: '.btn-editone',
  61. dragsortfield: 'weigh',
  62. },
  63. api: {
  64. init: function (defaults, columnDefaults, locales) {
  65. defaults = defaults ? defaults : {};
  66. columnDefaults = columnDefaults ? columnDefaults : {};
  67. locales = locales ? locales : {};
  68. // 写入bootstrap-table默认配置
  69. $.extend(true, $.fn.bootstrapTable.defaults, Table.defaults, defaults);
  70. // 写入bootstrap-table column配置
  71. $.extend($.fn.bootstrapTable.columnDefaults, Table.columnDefaults, columnDefaults);
  72. // 写入bootstrap-table locale配置
  73. $.extend($.fn.bootstrapTable.locales[Table.defaults.locale], {
  74. formatCommonSearch: function () {
  75. return __('Common search');
  76. },
  77. formatCommonSubmitButton: function () {
  78. return __('Submit');
  79. },
  80. formatCommonResetButton: function () {
  81. return __('Reset');
  82. },
  83. formatCommonCloseButton: function () {
  84. return __('Close');
  85. },
  86. formatCommonChoose: function () {
  87. return __('Choose');
  88. }
  89. }, locales);
  90. },
  91. // 绑定事件
  92. bindevent: function (table) {
  93. //Bootstrap-table的父元素,包含table,toolbar,pagnation
  94. var parenttable = table.closest('.bootstrap-table');
  95. //Bootstrap-table配置
  96. var options = table.bootstrapTable('getOptions');
  97. //Bootstrap操作区
  98. var toolbar = $(options.toolbar, parenttable);
  99. //当刷新表格时
  100. table.on('load-error.bs.table', function (status, res) {
  101. Toastr.error(__('Unknown data format'));
  102. });
  103. //当刷新表格时
  104. table.on('refresh.bs.table', function (e, settings, data) {
  105. $(Table.config.refreshbtn, toolbar).find(".fa").addClass("fa-spin");
  106. });
  107. //当双击单元格时
  108. table.on('dbl-click-row.bs.table', function (e, row, element, field) {
  109. $(Table.config.editonebtn, element).trigger("click");
  110. });
  111. //当内容渲染完成后
  112. table.on('post-body.bs.table', function (e, settings, json, xhr) {
  113. $(Table.config.refreshbtn, toolbar).find(".fa").removeClass("fa-spin");
  114. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', true);
  115. // 挺拽选择,需要重新绑定事件
  116. require(['drag', 'drop'], function () {
  117. $(Table.config.firsttd, table).drag("start", function (ev, dd) {
  118. return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
  119. }).drag(function (ev, dd) {
  120. $(dd.proxy).css({
  121. top: Math.min(ev.pageY, dd.startY),
  122. left: Math.min(ev.pageX, dd.startX),
  123. height: Math.abs(ev.pageY - dd.startY),
  124. width: Math.abs(ev.pageX - dd.startX)
  125. });
  126. }).drag("end", function (ev, dd) {
  127. $(dd.proxy).remove();
  128. });
  129. $(Table.config.firsttd, table).drop("start", function () {
  130. Table.api.toggleattr(this);
  131. }).drop(function () {
  132. Table.api.toggleattr(this);
  133. }).drop("end", function () {
  134. Table.api.toggleattr(this);
  135. });
  136. $.drop({
  137. multi: true
  138. });
  139. });
  140. });
  141. // 处理选中筛选框后按钮的状态统一变更
  142. table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () {
  143. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', !table.bootstrapTable('getSelections').length);
  144. });
  145. // 刷新按钮事件
  146. $(toolbar).on('click', Table.config.refreshbtn, function () {
  147. table.bootstrapTable('refresh');
  148. });
  149. // 添加按钮事件
  150. $(toolbar).on('click', Table.config.addbtn, function () {
  151. var ids = Table.api.selectedids(table);
  152. Backend.api.open(options.extend.add_url + "/ids/" + ids.join(","), __('Add'));
  153. });
  154. // 编辑按钮事件
  155. $(toolbar).on('click', Table.config.editbtn, function () {
  156. var ids = Table.api.selectedids(table);
  157. //循环弹出多个编辑框
  158. $.each(ids, function (i, j) {
  159. Backend.api.open(options.extend.edit_url + "/ids/" + j, __('Edit'));
  160. });
  161. });
  162. // 批量操作按钮事件
  163. $(toolbar).on('click', Table.config.multibtn, function () {
  164. var ids = Table.api.selectedids(table);
  165. Table.api.multi($(this).data("action"), ids, table, this);
  166. });
  167. // 批量删除按钮事件
  168. $(toolbar).on('click', Table.config.delbtn, function () {
  169. var that = this;
  170. var ids = Table.api.selectedids(table);
  171. var index = Backend.api.layer.confirm(
  172. __('Are you sure you want to delete the %s selected item?', ids.length),
  173. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  174. function () {
  175. Table.api.multi("del", ids, table, that);
  176. Backend.api.layer.close(index);
  177. }
  178. );
  179. });
  180. // 拖拽排序
  181. require(['dragsort'], function () {
  182. //绑定拖动排序
  183. $("tbody", table).dragsort({
  184. itemSelector: 'tr',
  185. dragSelector: "a.btn-dragsort",
  186. dragEnd: function () {
  187. var data = table.bootstrapTable('getData');
  188. var current = data[parseInt($(this).data("index"))];
  189. var options = table.bootstrapTable('getOptions');
  190. //改变的值和改变的ID集合
  191. var ids = $.map($("tbody tr:visible", table), function (tr) {
  192. return data[parseInt($(tr).data("index"))][options.pk];
  193. });
  194. var changeid = current[options.pk];
  195. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  196. var params = {
  197. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  198. data: {
  199. ids: ids.join(','),
  200. changeid: changeid,
  201. pid: pid,
  202. field: Table.config.dragsortfield,
  203. orderway: options.sortOrder,
  204. table: options.extend.table
  205. }
  206. };
  207. Backend.api.ajax(params, function (data) {
  208. Toastr.success(__('Operation completed'));
  209. table.bootstrapTable('refresh');
  210. });
  211. },
  212. placeHolderTemplate: ""
  213. });
  214. });
  215. var id = table.attr("id");
  216. Table.list[id] = table;
  217. return table;
  218. },
  219. // 批量操作请求
  220. multi: function (action, ids, table, element) {
  221. var options = table.bootstrapTable('getOptions');
  222. var url = action == "del" ? options.extend.del_url : options.extend.multi_url;
  223. url = url + "/ids/" + ($.isArray(ids) ? ids.join(",") : ids);
  224. var options = {url: url, data: {action: action, ids: ids, params: element ? $(element).data("params") : ''}};
  225. Backend.api.ajax(options, function (data) {
  226. Toastr.success(__('Operation completed'));
  227. table.bootstrapTable('refresh');
  228. });
  229. },
  230. // 单元格元素事件
  231. events: {
  232. operate: {
  233. 'click .btn-editone': function (e, value, row, index) {
  234. var options = $(this).closest('table').bootstrapTable('getOptions');
  235. Backend.api.open(options.extend.edit_url + "/ids/" + row[options.pk], __('Edit'));
  236. },
  237. 'click .btn-delone': function (e, value, row, index) {
  238. var that = this;
  239. var top = $(that).offset().top - $(window).scrollTop();
  240. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  241. if (top + 154 > $(window).height()) {
  242. top = top - 154;
  243. }
  244. if ($(window).width() < 480) {
  245. top = left = undefined;
  246. }
  247. var index = Backend.api.layer.confirm(
  248. __('Are you sure you want to delete this item?'),
  249. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  250. function () {
  251. var table = $(that).closest('table');
  252. var options = table.bootstrapTable('getOptions');
  253. Table.api.multi("del", row[options.pk], table, that);
  254. Backend.api.layer.close(index);
  255. }
  256. );
  257. }
  258. }
  259. },
  260. // 单元格数据格式化
  261. formatter: {
  262. icon: function (value, row, index) {
  263. if (!value)
  264. return '';
  265. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  266. //渲染fontawesome图标
  267. return '<i class="' + value + '"></i> ' + value;
  268. },
  269. image: function (value, row, index) {
  270. return '<img class="img-rounded img-sm" src="' + Backend.api.cdnurl(value) + '" />';
  271. },
  272. status: function (value, row, index, custom) {
  273. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  274. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  275. //如果有自定义状态,可以按需传入
  276. if (typeof custom !== 'undefined') {
  277. colorArr = $.extend(colorArr, custom);
  278. }
  279. value = value.toString();
  280. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  281. value = value.charAt(0).toUpperCase() + value.slice(1);
  282. //渲染状态
  283. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  284. return html;
  285. },
  286. url: function (value, row, index) {
  287. return '<a href="' + value + '" target="_blank" class="label bg-green">' + value + '</a>';
  288. },
  289. search: function (value, row, index) {
  290. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  291. },
  292. addtabs: function (value, row, index, url) {
  293. return '<a href="' + url + '" class="addtabsit" title="' + __("Search %s", value) + '">' + value + '</a>';
  294. },
  295. flag: function (value, row, index, custom) {
  296. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  297. //如果有自定义状态,可以按需传入
  298. if (typeof custom !== 'undefined') {
  299. colorArr = $.extend(colorArr, custom);
  300. }
  301. //渲染Flag
  302. var html = [];
  303. var arr = value.split(',');
  304. $.each(arr, function (i, value) {
  305. value = value.toString();
  306. if (value == '')
  307. return true;
  308. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  309. value = value.charAt(0).toUpperCase() + value.slice(1);
  310. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  311. });
  312. return html.join(' ');
  313. },
  314. datetime: function (value, row, index) {
  315. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  316. },
  317. operate: function (value, row, index, table) {
  318. var showweigh = true;
  319. var showedit = true;
  320. var showdel = true;
  321. if (typeof table != 'undefined') {
  322. var options = table.bootstrapTable('getOptions');
  323. if (options.extend.del_url == '')
  324. showdel = false;
  325. if (options.extend.edit_url == '')
  326. showedit = false;
  327. }
  328. showweigh = typeof row[Table.config.dragsortfield] != 'undefined' ? true : false;
  329. //行操作
  330. var html = [];
  331. if (showweigh)
  332. html.push('<a href="javascript:;" class="btn btn-primary btn-dragsort btn-xs"><i class="fa fa-arrows"></i></a>');
  333. if (showedit)
  334. html.push('<a href="javascript:;" class="btn btn-success btn-editone btn-xs"><i class="fa fa-pencil"></i></a>');
  335. if (showdel)
  336. html.push('<a href="javascript:;" class="btn btn-danger btn-delone btn-xs"><i class="fa fa-trash"></i></a>');
  337. return html.join(' ');
  338. }
  339. },
  340. // 获取选中的条目ID集合
  341. selectedids: function (table) {
  342. var options = table.bootstrapTable('getOptions');
  343. return $.map(table.bootstrapTable('getSelections'), function (row) {
  344. return row[options.pk];
  345. });
  346. },
  347. // 切换复选框状态
  348. toggleattr: function (table) {
  349. $("input[type='checkbox']", table).trigger('click');
  350. }
  351. },
  352. };
  353. return Table;
  354. });