require-table.js 28 KB

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