require-table.js 27 KB

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