require-table.js 17 KB

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