require-table.js 28 KB

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