require-table.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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, e) {
  105. if (e.status === 0) {
  106. return;
  107. }
  108. Toastr.error(__('Unknown data format'));
  109. });
  110. //当刷新表格时
  111. table.on('refresh.bs.table', function (e, settings, data) {
  112. $(Table.config.refreshbtn, toolbar).find(".fa").addClass("fa-spin");
  113. });
  114. //当双击单元格时
  115. table.on('dbl-click-row.bs.table', function (e, row, element, field) {
  116. $(Table.config.editonebtn, element).trigger("click");
  117. });
  118. //当内容渲染完成后
  119. table.on('post-body.bs.table', function (e, settings, json, xhr) {
  120. $(Table.config.refreshbtn, toolbar).find(".fa").removeClass("fa-spin");
  121. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', true);
  122. if ($(Table.config.firsttd, table).find("input[type='checkbox'][data-index]").size() > 0) {
  123. // 挺拽选择,需要重新绑定事件
  124. require(['drag', 'drop'], function () {
  125. $(Table.config.firsttd, table).drag("start", function (ev, dd) {
  126. return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
  127. }).drag(function (ev, dd) {
  128. $(dd.proxy).css({
  129. top: Math.min(ev.pageY, dd.startY),
  130. left: Math.min(ev.pageX, dd.startX),
  131. height: Math.abs(ev.pageY - dd.startY),
  132. width: Math.abs(ev.pageX - dd.startX)
  133. });
  134. }).drag("end", function (ev, dd) {
  135. $(dd.proxy).remove();
  136. });
  137. $(Table.config.firsttd, table).drop("start", function () {
  138. Table.api.toggleattr(this);
  139. }).drop(function () {
  140. Table.api.toggleattr(this);
  141. }).drop("end", function () {
  142. Table.api.toggleattr(this);
  143. });
  144. $.drop({
  145. multi: true
  146. });
  147. });
  148. }
  149. });
  150. // 处理选中筛选框后按钮的状态统一变更
  151. table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table fa.event.check', function () {
  152. var ids = Table.api.selectedids(table);
  153. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', !ids.length);
  154. });
  155. // 刷新按钮事件
  156. $(toolbar).on('click', Table.config.refreshbtn, function () {
  157. table.bootstrapTable('refresh');
  158. });
  159. // 添加按钮事件
  160. $(toolbar).on('click', Table.config.addbtn, function () {
  161. var ids = Table.api.selectedids(table);
  162. var url = options.extend.add_url;
  163. url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
  164. Fast.api.open(url, __('Add'), $(this).data() || {});
  165. });
  166. // 导入按钮事件
  167. if ($(Table.config.importbtn, toolbar).size() > 0) {
  168. require(['upload'], function (Upload) {
  169. Upload.api.plupload($(Table.config.importbtn, toolbar), function (data, ret) {
  170. Fast.api.ajax({
  171. url: options.extend.import_url,
  172. data: {file: data.url},
  173. }, function () {
  174. table.bootstrapTable('refresh');
  175. });
  176. });
  177. });
  178. }
  179. // 批量编辑按钮事件
  180. $(toolbar).on('click', Table.config.editbtn, function () {
  181. var that = this;
  182. //循环弹出多个编辑框
  183. $.each(table.bootstrapTable('getSelections'), function (index, row) {
  184. var url = options.extend.edit_url;
  185. row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
  186. var url = Table.api.replaceurl(url, row, table);
  187. Fast.api.open(url, __('Edit'), $(that).data() || {});
  188. });
  189. });
  190. // 批量操作按钮事件
  191. $(toolbar).on('click', Table.config.multibtn, function () {
  192. var ids = Table.api.selectedids(table);
  193. Table.api.multi($(this).data("action"), ids, table, this);
  194. });
  195. // 批量删除按钮事件
  196. $(toolbar).on('click', Table.config.delbtn, function () {
  197. var that = this;
  198. var ids = Table.api.selectedids(table);
  199. Layer.confirm(
  200. __('Are you sure you want to delete the %s selected item?', ids.length),
  201. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
  202. function (index) {
  203. Table.api.multi("del", ids, table, that);
  204. Layer.close(index);
  205. }
  206. );
  207. });
  208. // 拖拽排序
  209. require(['dragsort'], function () {
  210. //绑定拖动排序
  211. $("tbody", table).dragsort({
  212. itemSelector: 'tr:visible',
  213. dragSelector: "a.btn-dragsort",
  214. dragEnd: function () {
  215. var data = table.bootstrapTable('getData');
  216. var current = data[parseInt($(this).data("index"))];
  217. var options = table.bootstrapTable('getOptions');
  218. //改变的值和改变的ID集合
  219. var ids = $.map($("tbody tr:visible", table), function (tr) {
  220. return data[parseInt($(tr).data("index"))][options.pk];
  221. });
  222. var changeid = current[options.pk];
  223. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  224. var params = {
  225. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  226. data: {
  227. ids: ids.join(','),
  228. changeid: changeid,
  229. pid: pid,
  230. field: Table.config.dragsortfield,
  231. orderway: options.sortOrder,
  232. table: options.extend.table
  233. }
  234. };
  235. Fast.api.ajax(params, function (data) {
  236. table.bootstrapTable('refresh');
  237. });
  238. },
  239. placeHolderTemplate: ""
  240. });
  241. });
  242. $(table).on("click", "input[data-id][name='checkbox']", function (e) {
  243. table.trigger('fa.event.check');
  244. });
  245. $(table).on("click", "[data-id].btn-change", function (e) {
  246. e.preventDefault();
  247. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  248. });
  249. $(table).on("click", "[data-id].btn-edit", function (e) {
  250. e.preventDefault();
  251. var ids = $(this).data("id");
  252. var row = {};
  253. var options = table.bootstrapTable("getOptions");
  254. $.each(table.bootstrapTable('getData'), function (i, j) {
  255. if (j[options.pk] == ids) {
  256. row = j;
  257. return false;
  258. }
  259. });
  260. row.ids = ids;
  261. var url = Table.api.replaceurl(options.extend.edit_url, row, table);
  262. Fast.api.open(url, __('Edit'), $(this).data() || {});
  263. });
  264. $(table).on("click", "[data-id].btn-del", function (e) {
  265. e.preventDefault();
  266. var id = $(this).data("id");
  267. var that = this;
  268. Layer.confirm(
  269. __('Are you sure you want to delete this item?'),
  270. {icon: 3, title: __('Warning'), shadeClose: true},
  271. function (index) {
  272. Table.api.multi("del", id, table, that);
  273. Layer.close(index);
  274. }
  275. );
  276. });
  277. var id = table.attr("id");
  278. Table.list[id] = table;
  279. return table;
  280. },
  281. // 批量操作请求
  282. multi: function (action, ids, table, element) {
  283. var options = table.bootstrapTable('getOptions');
  284. var data = element ? $(element).data() : {};
  285. var ids = ($.isArray(ids) ? ids.join(",") : ids);
  286. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  287. url = this.replaceurl(url, {ids: ids}, table);
  288. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  289. var options = {url: url, data: {action: action, ids: ids, params: params}};
  290. Fast.api.ajax(options, function (data) {
  291. table.bootstrapTable('refresh');
  292. });
  293. },
  294. // 单元格元素事件
  295. events: {
  296. operate: {
  297. 'click .btn-editone': function (e, value, row, index) {
  298. e.stopPropagation();
  299. e.preventDefault();
  300. var table = $(this).closest('table');
  301. var options = table.bootstrapTable('getOptions');
  302. var ids = row[options.pk];
  303. row = $.extend({}, row ? row : {}, {ids: ids});
  304. var url = options.extend.edit_url;
  305. Fast.api.open(Table.api.replaceurl(url, row, table), __('Edit'), $(this).data() || {});
  306. },
  307. 'click .btn-delone': function (e, value, row, index) {
  308. e.stopPropagation();
  309. e.preventDefault();
  310. var that = this;
  311. var top = $(that).offset().top - $(window).scrollTop();
  312. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  313. if (top + 154 > $(window).height()) {
  314. top = top - 154;
  315. }
  316. if ($(window).width() < 480) {
  317. top = left = undefined;
  318. }
  319. Layer.confirm(
  320. __('Are you sure you want to delete this item?'),
  321. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
  322. function (index) {
  323. var table = $(that).closest('table');
  324. var options = table.bootstrapTable('getOptions');
  325. Table.api.multi("del", row[options.pk], table, that);
  326. Layer.close(index);
  327. }
  328. );
  329. }
  330. }
  331. },
  332. // 单元格数据格式化
  333. formatter: {
  334. icon: function (value, row, index) {
  335. if (!value)
  336. return '';
  337. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  338. //渲染fontawesome图标
  339. return '<i class="' + value + '"></i> ' + value;
  340. },
  341. image: function (value, row, index) {
  342. value = value ? value : '/assets/img/blank.gif';
  343. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  344. return '<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />';
  345. },
  346. images: function (value, row, index) {
  347. value = value === null ? '' : value.toString();
  348. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  349. var arr = value.split(',');
  350. var html = [];
  351. $.each(arr, function (i, value) {
  352. value = value ? value : '/assets/img/blank.gif';
  353. html.push('<img class="' + classname + '" src="' + Fast.api.cdnurl(value) + '" />');
  354. });
  355. return html.join(' ');
  356. },
  357. status: function (value, row, index) {
  358. //颜色状态数组,可使用red/yellow/aqua/blue/navy/teal/olive/lime/fuchsia/purple/maroon
  359. var colorArr = {normal: 'success', hidden: 'grey', deleted: 'danger', locked: 'info'};
  360. //如果字段列有定义custom
  361. if (typeof this.custom !== 'undefined') {
  362. colorArr = $.extend(colorArr, this.custom);
  363. }
  364. value = value === null ? '' : value.toString();
  365. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  366. value = value.charAt(0).toUpperCase() + value.slice(1);
  367. //渲染状态
  368. var html = '<span class="text-' + color + '"><i class="fa fa-circle"></i> ' + __(value) + '</span>';
  369. return html;
  370. },
  371. url: function (value, row, index) {
  372. 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>';
  373. },
  374. search: function (value, row, index) {
  375. return '<a href="javascript:;" class="searchit" data-field="' + this.field + '" data-value="' + value + '">' + value + '</a>';
  376. },
  377. addtabs: function (value, row, index) {
  378. var url = Table.api.replaceurl(this.url, row, this.table);
  379. var title = this.atitle ? this.atitle : __("Search %s", value);
  380. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  381. },
  382. dialog: function (value, row, index) {
  383. var url = Table.api.replaceurl(this.url, row, this.table);
  384. var title = this.atitle ? this.atitle : __("View %s", value);
  385. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  386. },
  387. flag: function (value, row, index) {
  388. value = value === null ? '' : value.toString();
  389. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  390. //如果字段列有定义custom
  391. if (typeof this.custom !== 'undefined') {
  392. colorArr = $.extend(colorArr, this.custom);
  393. }
  394. if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
  395. value = row[this.customField];
  396. }
  397. //渲染Flag
  398. var html = [];
  399. var arr = value.split(',');
  400. $.each(arr, function (i, value) {
  401. value = value === null ? '' : value.toString();
  402. if (value == '')
  403. return true;
  404. var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  405. value = value.charAt(0).toUpperCase() + value.slice(1);
  406. html.push('<span class="label label-' + color + '">' + __(value) + '</span>');
  407. });
  408. return html.join(' ');
  409. },
  410. label: function (value, row, index) {
  411. return Table.api.formatter.flag.call(this, value, row, index);
  412. },
  413. datetime: function (value, row, index) {
  414. return value ? Moment(parseInt(value) * 1000).format("YYYY-MM-DD HH:mm:ss") : __('None');
  415. },
  416. operate: function (value, row, index) {
  417. var table = this.table;
  418. // 操作配置
  419. var options = table ? table.bootstrapTable('getOptions') : {};
  420. // 默认按钮组
  421. var buttons = $.extend([], this.buttons || []);
  422. if (options.extend.dragsort_url !== '') {
  423. buttons.push({name: 'dragsort', icon: 'fa fa-arrows', classname: 'btn btn-xs btn-primary btn-dragsort'});
  424. }
  425. if (options.extend.edit_url !== '') {
  426. buttons.push({name: 'edit', icon: 'fa fa-pencil', classname: 'btn btn-xs btn-success btn-editone', url: options.extend.edit_url});
  427. }
  428. if (options.extend.del_url !== '') {
  429. buttons.push({name: 'del', icon: 'fa fa-trash', classname: 'btn btn-xs btn-danger btn-delone'});
  430. }
  431. return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
  432. },
  433. buttons: function (value, row, index) {
  434. // 默认按钮组
  435. var buttons = $.extend([], this.buttons || []);
  436. return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
  437. }
  438. },
  439. buttonlink: function (column, buttons, value, row, index, type) {
  440. var table = column.table;
  441. type = typeof type === 'undefined' ? 'buttons' : type;
  442. var options = table ? table.bootstrapTable('getOptions') : {};
  443. var html = [];
  444. var url, classname, icon, text, title, extend;
  445. var fieldIndex = column.fieldIndex;
  446. $.each(buttons, function (i, j) {
  447. if (type === 'operate') {
  448. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  449. return true;
  450. }
  451. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  452. return true;
  453. }
  454. }
  455. var attr = table.data(type + "-" + j.name);
  456. if (typeof attr === 'undefined' || attr) {
  457. url = j.url ? j.url : '';
  458. url = url ? Fast.api.fixurl(Table.api.replaceurl(url, row, table)) : 'javascript:;';
  459. classname = j.classname ? j.classname : 'btn-primary btn-' + name + 'one';
  460. icon = j.icon ? j.icon : '';
  461. text = j.text ? j.text : '';
  462. title = j.title ? j.title : text;
  463. refresh = j.refresh ? 'data-refresh="' + j.refresh + '"' : '';
  464. confirm = j.confirm ? 'data-confirm="' + j.confirm + '"' : '';
  465. extend = j.extend ? j.extend : '';
  466. html.push('<a href="' + url + '" class="' + classname + '" ' + (confirm ? confirm + ' ' : '') + (refresh ? refresh + ' ' : '') + extend + ' title="' + title + '" data-table-id="' + (table ? table.attr("id") : '') + '" data-field-index="' + fieldIndex + '" data-row-index="' + index + '" data-button-index="' + i + '"><i class="' + icon + '"></i>' + (text ? ' ' + text : '') + '</a>');
  467. }
  468. });
  469. return html.join(' ');
  470. },
  471. //替换URL中的数据
  472. replaceurl: function (url, row, table) {
  473. var options = table ? table.bootstrapTable('getOptions') : null;
  474. var ids = options ? row[options.pk] : 0;
  475. row.ids = ids ? ids : (typeof row.ids !== 'undefined' ? row.ids : 0);
  476. //自动添加ids参数
  477. url = !url.match(/\{ids\}/i) ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + '{ids}' : url;
  478. url = url.replace(/\{(.*?)\}/gi, function (matched) {
  479. matched = matched.substring(1, matched.length - 1);
  480. if (matched.indexOf(".") !== -1) {
  481. var temp = row;
  482. var arr = matched.split(/\./);
  483. for (var i = 0; i < arr.length; i++) {
  484. if (typeof temp[arr[i]] !== 'undefined') {
  485. temp = temp[arr[i]];
  486. }
  487. }
  488. return typeof temp === 'object' ? '' : temp;
  489. }
  490. return row[matched];
  491. });
  492. return url;
  493. },
  494. // 获取选中的条目ID集合
  495. selectedids: function (table) {
  496. var options = table.bootstrapTable('getOptions');
  497. if (options.templateView) {
  498. return $.map($("input[data-id][name='checkbox']:checked"), function (dom) {
  499. return $(dom).data("id");
  500. });
  501. } else {
  502. return $.map(table.bootstrapTable('getSelections'), function (row) {
  503. return row[options.pk];
  504. });
  505. }
  506. },
  507. // 切换复选框状态
  508. toggleattr: function (table) {
  509. $("input[type='checkbox']", table).trigger('click');
  510. },
  511. // 根据行索引获取行数据
  512. getrowdata: function (table, index) {
  513. index = parseInt(index);
  514. var data = table.bootstrapTable('getData');
  515. return typeof data[index] !== 'undefined' ? data[index] : null;
  516. }
  517. },
  518. };
  519. return Table;
  520. });