require-table.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. singleSelect: false, //是否启用单选
  24. showRefresh: false,
  25. locale: 'zh-CN',
  26. showToggle: true,
  27. showColumns: true,
  28. pk: 'id',
  29. sortName: 'id',
  30. sortOrder: 'desc',
  31. paginationFirstText: __("First"),
  32. paginationPreText: __("Previous"),
  33. paginationNextText: __("Next"),
  34. paginationLastText: __("Last"),
  35. mobileResponsive: true, //是否自适应移动端
  36. cardView: false, //卡片视图
  37. checkOnInit: true, //是否在初始化时判断
  38. escape: true, //是否对内容进行转义
  39. extend: {
  40. index_url: '',
  41. add_url: '',
  42. edit_url: '',
  43. del_url: '',
  44. import_url: '',
  45. multi_url: '',
  46. dragsort_url: 'ajax/weigh',
  47. }
  48. },
  49. // Bootstrap-table 列配置
  50. columnDefaults: {
  51. align: 'center',
  52. valign: 'middle',
  53. },
  54. config: {
  55. firsttd: 'tbody tr td:first-child:not(:has(div.card-views))',
  56. toolbar: '.toolbar',
  57. refreshbtn: '.btn-refresh',
  58. addbtn: '.btn-add',
  59. editbtn: '.btn-edit',
  60. delbtn: '.btn-del',
  61. importbtn: '.btn-import',
  62. multibtn: '.btn-multi',
  63. disabledbtn: '.btn-disabled',
  64. editonebtn: '.btn-editone',
  65. dragsortfield: 'weigh',
  66. },
  67. api: {
  68. init: function (defaults, columnDefaults, locales) {
  69. defaults = defaults ? defaults : {};
  70. columnDefaults = columnDefaults ? columnDefaults : {};
  71. locales = locales ? locales : {};
  72. // 写入bootstrap-table默认配置
  73. $.extend(true, $.fn.bootstrapTable.defaults, Table.defaults, defaults);
  74. // 写入bootstrap-table column配置
  75. $.extend($.fn.bootstrapTable.columnDefaults, Table.columnDefaults, columnDefaults);
  76. // 写入bootstrap-table locale配置
  77. $.extend($.fn.bootstrapTable.locales[Table.defaults.locale], {
  78. formatCommonSearch: function () {
  79. return __('Common search');
  80. },
  81. formatCommonSubmitButton: function () {
  82. return __('Submit');
  83. },
  84. formatCommonResetButton: function () {
  85. return __('Reset');
  86. },
  87. formatCommonCloseButton: function () {
  88. return __('Close');
  89. },
  90. formatCommonChoose: function () {
  91. return __('Choose');
  92. }
  93. }, locales);
  94. },
  95. // 绑定事件
  96. bindevent: function (table) {
  97. //Bootstrap-table的父元素,包含table,toolbar,pagnation
  98. var parenttable = table.closest('.bootstrap-table');
  99. //Bootstrap-table配置
  100. var options = table.bootstrapTable('getOptions');
  101. //Bootstrap操作区
  102. var toolbar = $(options.toolbar, parenttable);
  103. //当刷新表格时
  104. table.on('load-error.bs.table', function (status, res) {
  105. Toastr.error(__('Unknown data format'));
  106. });
  107. //当刷新表格时
  108. table.on('refresh.bs.table', function (e, settings, data) {
  109. $(Table.config.refreshbtn, toolbar).find(".fa").addClass("fa-spin");
  110. });
  111. //当双击单元格时
  112. table.on('dbl-click-row.bs.table', function (e, row, element, field) {
  113. $(Table.config.editonebtn, element).trigger("click");
  114. });
  115. //当内容渲染完成后
  116. table.on('post-body.bs.table', function (e, settings, json, xhr) {
  117. $(Table.config.refreshbtn, toolbar).find(".fa").removeClass("fa-spin");
  118. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', true);
  119. if ($(Table.config.firsttd, table).find("input[type='checkbox'][data-index]").size() > 0) {
  120. // 挺拽选择,需要重新绑定事件
  121. require(['drag', 'drop'], function () {
  122. $(Table.config.firsttd, table).drag("start", function (ev, dd) {
  123. return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
  124. }).drag(function (ev, dd) {
  125. $(dd.proxy).css({
  126. top: Math.min(ev.pageY, dd.startY),
  127. left: Math.min(ev.pageX, dd.startX),
  128. height: Math.abs(ev.pageY - dd.startY),
  129. width: Math.abs(ev.pageX - dd.startX)
  130. });
  131. }).drag("end", function (ev, dd) {
  132. $(dd.proxy).remove();
  133. });
  134. $(Table.config.firsttd, table).drop("start", function () {
  135. Table.api.toggleattr(this);
  136. }).drop(function () {
  137. Table.api.toggleattr(this);
  138. }).drop("end", function () {
  139. Table.api.toggleattr(this);
  140. });
  141. $.drop({
  142. multi: true
  143. });
  144. });
  145. }
  146. });
  147. // 处理选中筛选框后按钮的状态统一变更
  148. table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
  149. var ids = Table.api.selectedids(table);
  150. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', !ids.length);
  151. });
  152. // 刷新按钮事件
  153. $(toolbar).on('click', Table.config.refreshbtn, function () {
  154. table.bootstrapTable('refresh');
  155. });
  156. // 添加按钮事件
  157. $(toolbar).on('click', Table.config.addbtn, function () {
  158. var ids = Table.api.selectedids(table);
  159. Fast.api.open(options.extend.add_url + (ids.length > 0 ? (options.extend.add_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ids.join(",") : ''), __('Add'), $(this).data() || {});
  160. });
  161. // 导入按钮事件
  162. if ($(Table.config.importbtn, toolbar).size() > 0) {
  163. require(['upload'], function (Upload) {
  164. Upload.api.plupload($(Table.config.importbtn, toolbar), function (data, ret) {
  165. Fast.api.ajax({
  166. url: options.extend.import_url,
  167. data: {file: data.url},
  168. }, function () {
  169. table.bootstrapTable('refresh');
  170. });
  171. });
  172. });
  173. }
  174. // 批量编辑按钮事件
  175. $(toolbar).on('click', Table.config.editbtn, function () {
  176. var ids = Table.api.selectedids(table);
  177. var that = this;
  178. //循环弹出多个编辑框
  179. $.each(ids, function (i, j) {
  180. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + j, __('Edit'), $(that).data() || {});
  181. });
  182. });
  183. // 批量操作按钮事件
  184. $(toolbar).on('click', Table.config.multibtn, function () {
  185. var ids = Table.api.selectedids(table);
  186. Table.api.multi($(this).data("action"), ids, table, this);
  187. });
  188. // 批量删除按钮事件
  189. $(toolbar).on('click', Table.config.delbtn, function () {
  190. var that = this;
  191. var ids = Table.api.selectedids(table);
  192. var index = Layer.confirm(
  193. __('Are you sure you want to delete the %s selected item?', ids.length),
  194. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  195. function () {
  196. Table.api.multi("del", ids, table, that);
  197. Layer.close(index);
  198. }
  199. );
  200. });
  201. // 拖拽排序
  202. require(['dragsort'], function () {
  203. //绑定拖动排序
  204. $("tbody", table).dragsort({
  205. itemSelector: 'tr',
  206. dragSelector: "a.btn-dragsort",
  207. dragEnd: function () {
  208. var data = table.bootstrapTable('getData');
  209. var current = data[parseInt($(this).data("index"))];
  210. var options = table.bootstrapTable('getOptions');
  211. //改变的值和改变的ID集合
  212. var ids = $.map($("tbody tr:visible", table), function (tr) {
  213. return data[parseInt($(tr).data("index"))][options.pk];
  214. });
  215. var changeid = current[options.pk];
  216. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  217. var params = {
  218. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  219. data: {
  220. ids: ids.join(','),
  221. changeid: changeid,
  222. pid: pid,
  223. field: Table.config.dragsortfield,
  224. orderway: options.sortOrder,
  225. table: options.extend.table
  226. }
  227. };
  228. Fast.api.ajax(params, function (data) {
  229. table.bootstrapTable('refresh');
  230. });
  231. },
  232. placeHolderTemplate: ""
  233. });
  234. });
  235. $(table).on("click", "input[data-id][name='checkbox']", function (e) {
  236. table.trigger('fa.event.check');
  237. });
  238. $(table).on("click", "[data-id].btn-change", function (e) {
  239. e.preventDefault();
  240. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  241. });
  242. $(table).on("click", "[data-id].btn-edit", function (e) {
  243. e.preventDefault();
  244. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + $(this).data("id"), __('Edit'), $(this).data() || {});
  245. });
  246. $(table).on("click", "[data-id].btn-del", function (e) {
  247. e.preventDefault();
  248. var id = $(this).data("id");
  249. var that = this;
  250. var index = Layer.confirm(
  251. __('Are you sure you want to delete this item?'),
  252. {icon: 3, title: __('Warning'), shadeClose: true},
  253. function () {
  254. Table.api.multi("del", id, table, that);
  255. Layer.close(index);
  256. }
  257. );
  258. });
  259. var id = table.attr("id");
  260. Table.list[id] = table;
  261. return table;
  262. },
  263. // 批量操作请求
  264. multi: function (action, ids, table, element) {
  265. var options = table.bootstrapTable('getOptions');
  266. var data = element ? $(element).data() : {};
  267. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  268. url = url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ($.isArray(ids) ? ids.join(",") : ids);
  269. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  270. var options = {url: url, data: {action: action, ids: ids, params: params}};
  271. Fast.api.ajax(options, function (data) {
  272. table.bootstrapTable('refresh');
  273. });
  274. },
  275. // 单元格元素事件
  276. events: {
  277. operate: {
  278. 'click .btn-editone': function (e, value, row, index) {
  279. e.stopPropagation();
  280. e.preventDefault();
  281. var options = $(this).closest('table').bootstrapTable('getOptions');
  282. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk], __('Edit'), $(this).data() || {});
  283. },
  284. 'click .btn-delone': function (e, value, row, index) {
  285. e.stopPropagation();
  286. e.preventDefault();
  287. var that = this;
  288. var top = $(that).offset().top - $(window).scrollTop();
  289. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  290. if (top + 154 > $(window).height()) {
  291. top = top - 154;
  292. }
  293. if ($(window).width() < 480) {
  294. top = left = undefined;
  295. }
  296. var index = Layer.confirm(
  297. __('Are you sure you want to delete this item?'),
  298. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  299. function () {
  300. var table = $(that).closest('table');
  301. var options = table.bootstrapTable('getOptions');
  302. Table.api.multi("del", row[options.pk], table, that);
  303. Layer.close(index);
  304. }
  305. );
  306. }
  307. }
  308. },
  309. // 单元格数据格式化
  310. formatter: {
  311. icon: function (value, row, index) {
  312. if (!value)
  313. return '';
  314. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  315. //渲染fontawesome图标
  316. return '<i class="' + value + '"></i> ' + value;
  317. },
  318. image: function (value, row, index) {
  319. value = value ? value : '/assets/img/blank.gif';
  320. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  321. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  322. },
  323. images: function (value, row, index) {
  324. value = value.toString();
  325. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  326. var arr = value.toString().split(',');
  327. var html = [];
  328. $.each(arr, function (i, value) {
  329. value = value ? value : '/assets/img/blank.gif';
  330. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  331. });
  332. return html.join(' ');
  333. },
  334. status: function (value, row, index) {
  335. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  336. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  337. //如果字段列有定义custom
  338. if (typeof this.custom !== 'undefined') {
  339. colorArr = $.extend(colorArr, this.custom);
  340. }
  341. value = value.toString();
  342. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  343. value = value.charAt(0).toUpperCase() + value.slice(1);
  344. //渲染状态
  345. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  346. return html;
  347. },
  348. url: function (value, row, index) {
  349. 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>';
  350. },
  351. search: function (value, row, index) {
  352. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  353. },
  354. addtabs: function (value, row, index) {
  355. var url = Table.api.replaceurl(this.url, value, row, this.table);
  356. var title = this.atitle ? this.atitle : __("Search %s", value);
  357. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  358. },
  359. dialog: function (value, row, index) {
  360. var url = Table.api.replaceurl(this.url, value, row, this.table);
  361. var title = this.atitle ? this.atitle : __("View %s", value);
  362. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  363. },
  364. flag: function (value, row, index) {
  365. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  366. //如果字段列有定义custom
  367. if (typeof this.custom !== 'undefined') {
  368. colorArr = $.extend(colorArr, this.custom);
  369. }
  370. if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
  371. value = row[this.customField];
  372. }
  373. //渲染Flag
  374. var html = [];
  375. var arr = value.toString().split(',');
  376. $.each(arr, function (i, value) {
  377. value = value.toString();
  378. if (value == '')
  379. return true;
  380. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  381. value = value.charAt(0).toUpperCase() + value.slice(1);
  382. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  383. });
  384. return html.join(' ');
  385. },
  386. label: function (value, row, index) {
  387. return Table.api.formatter.flag.call(this, value, row, index);
  388. },
  389. datetime: function (value, row, index) {
  390. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  391. },
  392. operate: function (value, row, index) {
  393. var table = this.table;
  394. // 操作配置
  395. var options = table ? table.bootstrapTable('getOptions') : {};
  396. // 默认按钮组
  397. var buttons = $.extend([], this.buttons || []);
  398. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  399. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone', url: options.extend.edit_url});
  400. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  401. var html = [];
  402. var url, classname, icon, text, title, extend;
  403. $.each(buttons, function (i, j) {
  404. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  405. return true;
  406. }
  407. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  408. return true;
  409. }
  410. var attr = table.data("operate-" + j.name);
  411. if (typeof attr === 'undefined' || attr) {
  412. url = j.url ? j.url : '';
  413. if (url.indexOf("{ids}") === -1) {
  414. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  415. }
  416. url = Table.api.replaceurl(url, value, row, table);
  417. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  418. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  419. icon = j.icon ? j.icon : '';
  420. text = j.text ? j.text : '';
  421. title = j.title ? j.title : text;
  422. extend = j.extend ? j.extend : '';
  423. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  424. }
  425. });
  426. return html.join(' ');
  427. },
  428. buttons: function (value, row, index) {
  429. var table = this.table;
  430. // 操作配置
  431. var options = table ? table.bootstrapTable('getOptions') : {};
  432. // 默认按钮组
  433. var buttons = $.extend([], this.buttons || []);
  434. var html = [];
  435. var url, classname, icon, text, title, extend;
  436. $.each(buttons, function (i, j) {
  437. var attr = table.data("buttons-" + j.name);
  438. if (typeof attr === 'undefined' || attr) {
  439. url = j.url ? j.url : '';
  440. if (url.indexOf("{ids}") === -1) {
  441. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  442. }
  443. url = Table.api.replaceurl(url, value, row, table);
  444. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  445. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  446. icon = j.icon ? j.icon : '';
  447. text = j.text ? j.text : '';
  448. title = j.title ? j.title : text;
  449. extend = j.extend ? j.extend : '';
  450. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  451. }
  452. });
  453. return html.join(' ');
  454. }
  455. },
  456. //替换URL中的{ids}和{value}
  457. replaceurl: function (url, value, row, table) {
  458. url = url ? url : '';
  459. url = url.replace(/\{value\}/ig, value);
  460. if (table) {
  461. var options = table.bootstrapTable('getOptions');
  462. url = url.replace(/\{ids\}/ig, row[options.pk]);
  463. } else {
  464. url = url.replace(/\{ids\}/ig, 0);
  465. }
  466. return url;
  467. },
  468. // 获取选中的条目ID集合
  469. selectedids: function (table) {
  470. var options = table.bootstrapTable('getOptions');
  471. if (options.templateView) {
  472. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  473. return $(dom).data("id");
  474. });
  475. } else {
  476. return $.map(table.bootstrapTable('getSelections'), function (row) {
  477. return row[options.pk];
  478. });
  479. }
  480. },
  481. // 切换复选框状态
  482. toggleattr: function (table) {
  483. $("input[type='checkbox']", table).trigger('click');
  484. }
  485. },
  486. };
  487. return Table;
  488. });