require-table.js 28 KB

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