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. console.log($(Table.config.importbtn, toolbar));
  165. Upload.api.plupload($(Table.config.importbtn, toolbar), function (data, ret) {
  166. Fast.api.ajax({
  167. url: options.extend.import_url,
  168. data: {file: data.url},
  169. }, function () {
  170. table.bootstrapTable('refresh');
  171. });
  172. });
  173. });
  174. }
  175. // 批量编辑按钮事件
  176. $(toolbar).on('click', Table.config.editbtn, function () {
  177. var ids = Table.api.selectedids(table);
  178. var that = this;
  179. //循环弹出多个编辑框
  180. $.each(ids, function (i, j) {
  181. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + j, __('Edit'), $(that).data() || {});
  182. });
  183. });
  184. // 批量操作按钮事件
  185. $(toolbar).on('click', Table.config.multibtn, function () {
  186. var ids = Table.api.selectedids(table);
  187. Table.api.multi($(this).data("action"), ids, table, this);
  188. });
  189. // 批量删除按钮事件
  190. $(toolbar).on('click', Table.config.delbtn, function () {
  191. var that = this;
  192. var ids = Table.api.selectedids(table);
  193. var index = Layer.confirm(
  194. __('Are you sure you want to delete the %s selected item?', ids.length),
  195. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  196. function () {
  197. Table.api.multi("del", ids, table, that);
  198. Layer.close(index);
  199. }
  200. );
  201. });
  202. // 拖拽排序
  203. require(['dragsort'], function () {
  204. //绑定拖动排序
  205. $("tbody", table).dragsort({
  206. itemSelector: 'tr',
  207. dragSelector: "a.btn-dragsort",
  208. dragEnd: function () {
  209. var data = table.bootstrapTable('getData');
  210. var current = data[parseInt($(this).data("index"))];
  211. var options = table.bootstrapTable('getOptions');
  212. //改变的值和改变的ID集合
  213. var ids = $.map($("tbody tr:visible", table), function (tr) {
  214. return data[parseInt($(tr).data("index"))][options.pk];
  215. });
  216. var changeid = current[options.pk];
  217. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  218. var params = {
  219. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  220. data: {
  221. ids: ids.join(','),
  222. changeid: changeid,
  223. pid: pid,
  224. field: Table.config.dragsortfield,
  225. orderway: options.sortOrder,
  226. table: options.extend.table
  227. }
  228. };
  229. Fast.api.ajax(params, function (data) {
  230. table.bootstrapTable('refresh');
  231. });
  232. },
  233. placeHolderTemplate: ""
  234. });
  235. });
  236. $(table).on("click", "input[data-id][name='checkbox']", function (e) {
  237. table.trigger('fa.event.check');
  238. });
  239. $(table).on("click", "[data-id].btn-change", function (e) {
  240. e.preventDefault();
  241. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  242. });
  243. $(table).on("click", "[data-id].btn-edit", function (e) {
  244. e.preventDefault();
  245. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + $(this).data("id"), __('Edit'), $(this).data() || {});
  246. });
  247. $(table).on("click", "[data-id].btn-del", function (e) {
  248. e.preventDefault();
  249. var id = $(this).data("id");
  250. var that = this;
  251. var index = Layer.confirm(
  252. __('Are you sure you want to delete this item?'),
  253. {icon: 3, title: __('Warning'), shadeClose: true},
  254. function () {
  255. Table.api.multi("del", id, table, that);
  256. Layer.close(index);
  257. }
  258. );
  259. });
  260. var id = table.attr("id");
  261. Table.list[id] = table;
  262. return table;
  263. },
  264. // 批量操作请求
  265. multi: function (action, ids, table, element) {
  266. var options = table.bootstrapTable('getOptions');
  267. var data = element ? $(element).data() : {};
  268. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  269. url = url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + ($.isArray(ids) ? ids.join(",") : ids);
  270. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  271. var options = {url: url, data: {action: action, ids: ids, params: params}};
  272. Fast.api.ajax(options, function (data) {
  273. table.bootstrapTable('refresh');
  274. });
  275. },
  276. // 单元格元素事件
  277. events: {
  278. operate: {
  279. 'click .btn-editone': function (e, value, row, index) {
  280. e.stopPropagation();
  281. e.preventDefault();
  282. var options = $(this).closest('table').bootstrapTable('getOptions');
  283. Fast.api.open(options.extend.edit_url + (options.extend.edit_url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk], __('Edit'), $(this).data() || {});
  284. },
  285. 'click .btn-delone': function (e, value, row, index) {
  286. e.stopPropagation();
  287. e.preventDefault();
  288. var that = this;
  289. var top = $(that).offset().top - $(window).scrollTop();
  290. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  291. if (top + 154 > $(window).height()) {
  292. top = top - 154;
  293. }
  294. if ($(window).width() < 480) {
  295. top = left = undefined;
  296. }
  297. var index = Layer.confirm(
  298. __('Are you sure you want to delete this item?'),
  299. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  300. function () {
  301. var table = $(that).closest('table');
  302. var options = table.bootstrapTable('getOptions');
  303. Table.api.multi("del", row[options.pk], table, that);
  304. Layer.close(index);
  305. }
  306. );
  307. }
  308. }
  309. },
  310. // 单元格数据格式化
  311. formatter: {
  312. icon: function (value, row, index) {
  313. if (!value)
  314. return '';
  315. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  316. //渲染fontawesome图标
  317. return '<i class="' + value + '"></i> ' + value;
  318. },
  319. image: function (value, row, index) {
  320. value = value ? value : '/assets/img/blank.gif';
  321. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  322. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  323. },
  324. images: function (value, row, index) {
  325. value = value.toString();
  326. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  327. var arr = value.toString().split(',');
  328. var html = [];
  329. $.each(arr, function (i, value) {
  330. value = value ? value : '/assets/img/blank.gif';
  331. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  332. });
  333. return html.join(' ');
  334. },
  335. status: function (value, row, index) {
  336. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  337. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  338. //如果字段列有定义custom
  339. if (typeof this.custom !== 'undefined') {
  340. colorArr = $.extend(colorArr, this.custom);
  341. }
  342. value = value.toString();
  343. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  344. value = value.charAt(0).toUpperCase() + value.slice(1);
  345. //渲染状态
  346. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  347. return html;
  348. },
  349. url: function (value, row, index) {
  350. 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>';
  351. },
  352. search: function (value, row, index) {
  353. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  354. },
  355. addtabs: function (value, row, index) {
  356. var url = Table.api.replaceurl(this.url, value, row, this.table);
  357. var title = this.atitle ? this.atitle : __("Search %s", value);
  358. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  359. },
  360. dialog: function (value, row, index) {
  361. var url = Table.api.replaceurl(this.url, value, row, this.table);
  362. var title = this.atitle ? this.atitle : __("View %s", value);
  363. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  364. },
  365. flag: function (value, row, index) {
  366. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  367. //如果字段列有定义custom
  368. if (typeof this.custom !== 'undefined') {
  369. colorArr = $.extend(colorArr, this.custom);
  370. }
  371. if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
  372. value = row[this.customField];
  373. }
  374. //渲染Flag
  375. var html = [];
  376. var arr = value.toString().split(',');
  377. $.each(arr, function (i, value) {
  378. value = value.toString();
  379. if (value == '')
  380. return true;
  381. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  382. value = value.charAt(0).toUpperCase() + value.slice(1);
  383. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  384. });
  385. return html.join(' ');
  386. },
  387. label: function (value, row, index) {
  388. return Table.api.formatter.flag.call(this, value, row, index);
  389. },
  390. datetime: function (value, row, index) {
  391. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  392. },
  393. operate: function (value, row, index) {
  394. var table = this.table;
  395. // 操作配置
  396. var options = table ? table.bootstrapTable('getOptions') : {};
  397. // 默认按钮组
  398. var buttons = $.extend([], this.buttons || []);
  399. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  400. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone', url: options.extend.edit_url});
  401. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  402. var html = [];
  403. var url, classname, icon, text, title, extend;
  404. $.each(buttons, function (i, j) {
  405. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  406. return true;
  407. }
  408. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  409. return true;
  410. }
  411. var attr = table.data("operate-" + j.name);
  412. if (typeof attr === 'undefined' || attr) {
  413. url = j.url ? j.url : '';
  414. if (url.indexOf("{ids}") === -1) {
  415. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  416. }
  417. url = Table.api.replaceurl(url, value, row, table);
  418. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  419. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  420. icon = j.icon ? j.icon : '';
  421. text = j.text ? j.text : '';
  422. title = j.title ? j.title : text;
  423. extend = j.extend ? j.extend : '';
  424. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  425. }
  426. });
  427. return html.join(' ');
  428. },
  429. buttons: function (value, row, index) {
  430. var table = this.table;
  431. // 操作配置
  432. var options = table ? table.bootstrapTable('getOptions') : {};
  433. // 默认按钮组
  434. var buttons = $.extend([], this.buttons || []);
  435. var html = [];
  436. var url, classname, icon, text, title, extend;
  437. $.each(buttons, function (i, j) {
  438. var attr = table.data("buttons-" + j.name);
  439. if (typeof attr === 'undefined' || attr) {
  440. url = j.url ? j.url : '';
  441. if (url.indexOf("{ids}") === -1) {
  442. url = url ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + row[options.pk] : '';
  443. }
  444. url = Table.api.replaceurl(url, value, row, table);
  445. url = url ? Fast.api.fixurl(url) : 'javascript:;';
  446. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  447. icon = j.icon ? j.icon : '';
  448. text = j.text ? j.text : '';
  449. title = j.title ? j.title : text;
  450. extend = j.extend ? j.extend : '';
  451. html.push('<a href="' + url + '" class="' + classname + '" ' + extend + ' title="' + title + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  452. }
  453. });
  454. return html.join(' ');
  455. }
  456. },
  457. //替换URL中的{ids}和{value}
  458. replaceurl: function (url, value, row, table) {
  459. url = url ? url : '';
  460. url = url.replace(/\{value\}/ig, value);
  461. if (table) {
  462. var options = table.bootstrapTable('getOptions');
  463. url = url.replace(/\{ids\}/ig, row[options.pk]);
  464. } else {
  465. url = url.replace(/\{ids\}/ig, 0);
  466. }
  467. return url;
  468. },
  469. // 获取选中的条目ID集合
  470. selectedids: function (table) {
  471. var options = table.bootstrapTable('getOptions');
  472. if (options.templateView) {
  473. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  474. return $(dom).data("id");
  475. });
  476. } else {
  477. return $.map(table.bootstrapTable('getSelections'), function (row) {
  478. return row[options.pk];
  479. });
  480. }
  481. },
  482. // 切换复选框状态
  483. toggleattr: function (table) {
  484. $("input[type='checkbox']", table).trigger('click');
  485. }
  486. },
  487. };
  488. return Table;
  489. });