require-table.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. define(['jquery', 'bootstrap', 'moment', 'moment/locale/zh-cn', 'bootstrap-table', 'bootstrap-table-lang', 'bootstrap-table-export', 'bootstrap-table-commonsearch', 'bootstrap-table-template', 'bootstrap-table-jumpto', 'bootstrap-table-fixed-columns'], 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: "auto",
  18. exportTypes: ['json', 'xml', 'csv', 'txt', 'doc', 'excel'],
  19. exportOptions: {
  20. fileName: 'export_' + Moment().format("YYYY-MM-DD"),
  21. preventInjection: false,
  22. mso: {
  23. onMsoNumberFormat: function (cell, row, col) {
  24. return !isNaN($(cell).text()) ? '\\@' : '';
  25. },
  26. },
  27. ignoreColumn: [0, 'operate'] //默认不导出第一列(checkbox)与操作(operate)列
  28. },
  29. pageSize: Config.pagesize || localStorage.getItem("pagesize") || 10,
  30. pageList: [10, 15, 20, 25, 50, 'All'],
  31. pagination: true,
  32. clickToSelect: true, //是否启用点击选中
  33. dblClickToEdit: true, //是否启用双击编辑
  34. singleSelect: false, //是否启用单选
  35. showRefresh: false,
  36. showJumpto: true,
  37. locale: Config.language == 'zh-cn' ? 'zh-CN' : 'en-US',
  38. showToggle: true,
  39. showColumns: true,
  40. pk: 'id',
  41. sortName: 'id',
  42. sortOrder: 'desc',
  43. paginationFirstText: __("First"),
  44. paginationPreText: __("Previous"),
  45. paginationNextText: __("Next"),
  46. paginationLastText: __("Last"),
  47. cardView: false, //卡片视图
  48. iosCardView: true, //ios卡片视图
  49. checkOnInit: true, //是否在初始化时判断
  50. escape: true, //是否对内容进行转义
  51. fixDropdownPosition: true, //是否修复下拉的定位
  52. selectedIds: [],
  53. selectedData: [],
  54. extend: {
  55. index_url: '',
  56. add_url: '',
  57. edit_url: '',
  58. del_url: '',
  59. import_url: '',
  60. multi_url: '',
  61. dragsort_url: 'ajax/weigh',
  62. }
  63. },
  64. // Bootstrap-table 列配置
  65. columnDefaults: {
  66. align: 'center',
  67. valign: 'middle',
  68. },
  69. config: {
  70. checkboxtd: 'tbody>tr>td.bs-checkbox',
  71. toolbar: '.toolbar',
  72. refreshbtn: '.btn-refresh',
  73. addbtn: '.btn-add',
  74. editbtn: '.btn-edit',
  75. delbtn: '.btn-del',
  76. importbtn: '.btn-import',
  77. multibtn: '.btn-multi',
  78. disabledbtn: '.btn-disabled',
  79. editonebtn: '.btn-editone',
  80. restoreonebtn: '.btn-restoreone',
  81. destroyonebtn: '.btn-destroyone',
  82. restoreallbtn: '.btn-restoreall',
  83. destroyallbtn: '.btn-destroyall',
  84. dragsortfield: 'weigh',
  85. },
  86. button: {
  87. edit: {
  88. name: 'edit',
  89. icon: 'fa fa-pencil',
  90. title: __('Edit'),
  91. extend: 'data-toggle="tooltip"',
  92. classname: 'btn btn-xs btn-success btn-editone'
  93. },
  94. del: {
  95. name: 'del',
  96. icon: 'fa fa-trash',
  97. title: __('Del'),
  98. extend: 'data-toggle="tooltip"',
  99. classname: 'btn btn-xs btn-danger btn-delone'
  100. },
  101. dragsort: {
  102. name: 'dragsort',
  103. icon: 'fa fa-arrows',
  104. title: __('Drag to sort'),
  105. extend: 'data-toggle="tooltip"',
  106. classname: 'btn btn-xs btn-primary btn-dragsort'
  107. }
  108. },
  109. api: {
  110. init: function (defaults, columnDefaults, locales) {
  111. defaults = defaults ? defaults : {};
  112. columnDefaults = columnDefaults ? columnDefaults : {};
  113. locales = locales ? locales : {};
  114. $.fn.bootstrapTable.Constructor.prototype.getSelectItem = function () {
  115. return this.$selectItem;
  116. };
  117. var _onPageListChange = $.fn.bootstrapTable.Constructor.prototype.onPageListChange;
  118. $.fn.bootstrapTable.Constructor.prototype.onPageListChange = function () {
  119. _onPageListChange.apply(this, Array.prototype.slice.apply(arguments));
  120. localStorage.setItem('pagesize', this.options.pageSize);
  121. return false;
  122. };
  123. // 写入bootstrap-table默认配置
  124. $.extend(true, $.fn.bootstrapTable.defaults, Table.defaults, defaults);
  125. // 写入bootstrap-table column配置
  126. $.extend($.fn.bootstrapTable.columnDefaults, Table.columnDefaults, columnDefaults);
  127. // 写入bootstrap-table locale配置
  128. $.extend($.fn.bootstrapTable.locales[Table.defaults.locale], {
  129. formatCommonSearch: function () {
  130. return __('Common search');
  131. },
  132. formatCommonSubmitButton: function () {
  133. return __('Submit');
  134. },
  135. formatCommonResetButton: function () {
  136. return __('Reset');
  137. },
  138. formatCommonCloseButton: function () {
  139. return __('Close');
  140. },
  141. formatCommonChoose: function () {
  142. return __('Choose');
  143. },
  144. formatJumpto: function () {
  145. return __('Go');
  146. }
  147. }, locales);
  148. // 如果是iOS设备则判断是否启用卡片视图
  149. if ($.fn.bootstrapTable.defaults.iosCardView && navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
  150. Table.defaults.cardView = true;
  151. $.fn.bootstrapTable.defaults.cardView = true;
  152. }
  153. if (typeof defaults.exportTypes != 'undefined') {
  154. $.fn.bootstrapTable.defaults.exportTypes = defaults.exportTypes;
  155. }
  156. },
  157. // 绑定事件
  158. bindevent: function (table) {
  159. //Bootstrap-table的父元素,包含table,toolbar,pagnation
  160. var parenttable = table.closest('.bootstrap-table');
  161. //Bootstrap-table配置
  162. var options = table.bootstrapTable('getOptions');
  163. //Bootstrap操作区
  164. var toolbar = $(options.toolbar, parenttable);
  165. //跨页提示按钮
  166. var tipsBtn = $(".btn-selected-tips", parenttable);
  167. if (tipsBtn.length === 0) {
  168. tipsBtn = $('<a href="javascript:" class="btn btn-warning-light btn-selected-tips hide" data-animation="false" data-toggle="tooltip" data-title="' + __("Click to uncheck all") + '"><i class="fa fa-info-circle"></i> ' + __("Multiple selection mode: %s checked", "<b>0</b>") + '</a>').appendTo(toolbar);
  169. }
  170. //点击提示按钮
  171. tipsBtn.off("click").on("click", function (e) {
  172. table.trigger("uncheckbox");
  173. table.bootstrapTable("refresh");
  174. });
  175. //当刷新表格时
  176. table.on('uncheckbox', function (status, res, e) {
  177. options.selectedIds = [];
  178. options.selectedData = [];
  179. tipsBtn.tooltip('hide');
  180. tipsBtn.addClass('hide');
  181. });
  182. //表格加载出错时
  183. table.on('load-error.bs.table', function (status, res, e) {
  184. if (e.status === 0) {
  185. return;
  186. }
  187. Toastr.error(__('Unknown data format'));
  188. });
  189. //当加载数据成功时
  190. table.on('load-success.bs.table', function (e, data) {
  191. if (typeof data.rows === 'undefined' && typeof data.code != 'undefined') {
  192. Toastr.error(data.msg);
  193. }
  194. });
  195. //当刷新表格时
  196. table.on('refresh.bs.table', function (e, settings, data) {
  197. $(Table.config.refreshbtn, toolbar).find(".fa").addClass("fa-spin");
  198. });
  199. //当执行搜索时
  200. table.on('search.bs.table common-search.bs.table', function (e, settings, data) {
  201. table.trigger("uncheckbox");
  202. });
  203. if (options.dblClickToEdit) {
  204. //当双击单元格时
  205. table.on('dbl-click-row.bs.table', function (e, row, element, field) {
  206. $(Table.config.editonebtn, element).trigger("click");
  207. });
  208. }
  209. //渲染内容前
  210. table.on('pre-body.bs.table', function (e, data) {
  211. if (options.maintainSelected) {
  212. $.each(data, function (i, row) {
  213. row[options.stateField] = $.inArray(row[options.pk], options.selectedIds) > -1;
  214. });
  215. }
  216. });
  217. //当内容渲染完成后
  218. table.on('post-body.bs.table', function (e, data) {
  219. $(Table.config.refreshbtn, toolbar).find(".fa").removeClass("fa-spin");
  220. if ($(Table.config.checkboxtd + ":first", table).find("input[type='checkbox'][data-index]").length > 0) {
  221. // 拖拽选择,需要重新绑定事件
  222. require(['drag', 'drop'], function () {
  223. var checkboxtd = $(Table.config.checkboxtd, table);
  224. checkboxtd.drag("start", function (ev, dd) {
  225. return $('<div class="selection" />').css('opacity', .65).appendTo(document.body);
  226. }).drag(function (ev, dd) {
  227. $(dd.proxy).css({
  228. top: Math.min(ev.pageY, dd.startY),
  229. left: Math.min(ev.pageX, dd.startX),
  230. height: Math.abs(ev.pageY - dd.startY),
  231. width: Math.abs(ev.pageX - dd.startX)
  232. });
  233. }).drag("end", function (ev, dd) {
  234. $(dd.proxy).remove();
  235. });
  236. checkboxtd.drop("start", function () {
  237. Table.api.toggleattr(this);
  238. }).drop(function () {
  239. // Table.api.toggleattr(this);
  240. }).drop("end", function (e) {
  241. var that = this;
  242. setTimeout(function () {
  243. if (e.type === 'mousemove') {
  244. Table.api.toggleattr(that);
  245. }
  246. }, 0);
  247. });
  248. $.drop({
  249. multi: true
  250. });
  251. });
  252. }
  253. });
  254. var exportDataType = options.exportDataType;
  255. // 处理选中筛选框后按钮的状态统一变更
  256. table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table post-body.bs.table', function (e) {
  257. var allIds = [];
  258. $.each(table.bootstrapTable("getData"), function (i, item) {
  259. allIds.push(typeof item[options.pk] != 'undefined' ? item[options.pk] : '');
  260. });
  261. var selectedIds = Table.api.selectedids(table, true),
  262. selectedData = Table.api.selecteddata(table, true);
  263. //开启分页checkbox分页记忆
  264. if (options.maintainSelected) {
  265. options.selectedIds = options.selectedIds.filter(function (element, index, self) {
  266. return $.inArray(element, allIds) === -1;
  267. }).concat(selectedIds);
  268. options.selectedData = options.selectedData.filter(function (element, index, self) {
  269. return $.inArray(element[options.pk], allIds) === -1;
  270. }).concat(selectedData);
  271. if (options.selectedIds.length > selectedIds.length) {
  272. $("b", tipsBtn).text(options.selectedIds.length);
  273. tipsBtn.removeClass('hide');
  274. } else {
  275. tipsBtn.addClass('hide');
  276. }
  277. } else {
  278. options.selectedIds = selectedIds;
  279. options.selectedData = selectedData;
  280. }
  281. //如果导出类型为auto时则自动判断
  282. if (exportDataType === 'auto') {
  283. options.exportDataType = selectedIds.length > 0 ? 'selected' : 'all';
  284. }
  285. $(Table.config.disabledbtn, toolbar).toggleClass('disabled', !options.selectedIds.length);
  286. });
  287. // 绑定TAB事件
  288. $('.panel-heading [data-field] a[data-toggle="tab"]', table.closest(".panel-intro")).on('shown.bs.tab', function (e) {
  289. var field = $(this).closest("[data-field]").data("field");
  290. var value = $(this).data("value");
  291. var object = $("[name='" + field + "']", table.closest(".bootstrap-table").find(".commonsearch-table"));
  292. if (object.prop('tagName') == "SELECT") {
  293. $("option[value='" + value + "']", object).prop("selected", true);
  294. } else {
  295. object.val(value);
  296. }
  297. table.trigger("uncheckbox");
  298. table.bootstrapTable('refresh', {pageNumber: 1});
  299. return false;
  300. });
  301. // 修复重置事件
  302. $("form", table.closest(".bootstrap-table").find(".commonsearch-table")).on('reset', function () {
  303. setTimeout(function () {
  304. // $('.panel-heading [data-field] li.active a[data-toggle="tab"]').trigger('shown.bs.tab');
  305. }, 0);
  306. $('.panel-heading [data-field] li', table.closest(".panel-intro")).removeClass('active');
  307. $('.panel-heading [data-field] li:first', table.closest(".panel-intro")).addClass('active');
  308. });
  309. // 刷新按钮事件
  310. toolbar.on('click', Table.config.refreshbtn, function () {
  311. table.bootstrapTable('refresh');
  312. });
  313. // 添加按钮事件
  314. toolbar.on('click', Table.config.addbtn, function () {
  315. var ids = Table.api.selectedids(table);
  316. var url = options.extend.add_url;
  317. if (url.indexOf("{ids}") !== -1) {
  318. url = Table.api.replaceurl(url, {ids: ids.length > 0 ? ids.join(",") : 0}, table);
  319. }
  320. Fast.api.open(url, $(this).data("original-title") || $(this).attr("title") || __('Add'), $(this).data() || {});
  321. });
  322. // 导入按钮事件
  323. if ($(Table.config.importbtn, toolbar).length > 0) {
  324. require(['upload'], function (Upload) {
  325. Upload.api.upload($(Table.config.importbtn, toolbar), function (data, ret) {
  326. Fast.api.ajax({
  327. url: options.extend.import_url,
  328. data: {file: data.url},
  329. }, function (data, ret) {
  330. table.trigger("uncheckbox");
  331. table.bootstrapTable('refresh');
  332. });
  333. });
  334. });
  335. }
  336. // 批量编辑按钮事件
  337. toolbar.on('click', Table.config.editbtn, function () {
  338. var that = this;
  339. var ids = Table.api.selectedids(table);
  340. if (ids.length > 10) {
  341. return;
  342. }
  343. var title = $(that).data('title') || $(that).attr("title") || __('Edit');
  344. var data = $(that).data() || {};
  345. delete data.title;
  346. //循环弹出多个编辑框
  347. $.each(Table.api.selecteddata(table), function (index, row) {
  348. var url = options.extend.edit_url;
  349. row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
  350. url = Table.api.replaceurl(url, row, table);
  351. Fast.api.open(url, typeof title === 'function' ? title.call(table, row) : title, data);
  352. });
  353. });
  354. //清空回收站
  355. $(document).on('click', Table.config.destroyallbtn, function () {
  356. var that = this;
  357. Layer.confirm(__('Are you sure you want to truncate?'), function () {
  358. var url = $(that).data("url") ? $(that).data("url") : $(that).attr("href");
  359. Fast.api.ajax(url, function () {
  360. Layer.closeAll();
  361. table.trigger("uncheckbox");
  362. table.bootstrapTable('refresh');
  363. }, function () {
  364. Layer.closeAll();
  365. });
  366. });
  367. return false;
  368. });
  369. //全部还原
  370. $(document).on('click', Table.config.restoreallbtn, function () {
  371. var that = this;
  372. var url = $(that).data("url") ? $(that).data("url") : $(that).attr("href");
  373. Fast.api.ajax(url, function () {
  374. Layer.closeAll();
  375. table.trigger("uncheckbox");
  376. table.bootstrapTable('refresh');
  377. }, function () {
  378. Layer.closeAll();
  379. });
  380. return false;
  381. });
  382. //销毁或删除
  383. $(document).on('click', Table.config.restoreonebtn + ',' + Table.config.destroyonebtn, function () {
  384. var that = this;
  385. var url = $(that).data("url") ? $(that).data("url") : $(that).attr("href");
  386. var row = Fast.api.getrowbyindex(table, $(that).data("row-index"));
  387. Fast.api.ajax({
  388. url: url,
  389. data: {ids: row[options.pk]}
  390. }, function () {
  391. table.trigger("uncheckbox");
  392. table.bootstrapTable('refresh');
  393. });
  394. return false;
  395. });
  396. // 批量操作按钮事件
  397. toolbar.on('click', Table.config.multibtn, function () {
  398. var ids = Table.api.selectedids(table);
  399. Table.api.multi($(this).data("action"), ids, table, this);
  400. });
  401. // 批量删除按钮事件
  402. toolbar.on('click', Table.config.delbtn, function () {
  403. var that = this;
  404. var ids = Table.api.selectedids(table);
  405. Layer.confirm(
  406. __('Are you sure you want to delete the %s selected item?', ids.length),
  407. {icon: 3, title: __('Warning'), offset: 0, shadeClose: true, btn: [__('OK'), __('Cancel')]},
  408. function (index) {
  409. Table.api.multi("del", ids, table, that);
  410. Layer.close(index);
  411. }
  412. );
  413. });
  414. // 拖拽排序
  415. require(['dragsort'], function () {
  416. //绑定拖动排序
  417. $("tbody", table).dragsort({
  418. itemSelector: 'tr:visible',
  419. dragSelector: "a.btn-dragsort",
  420. dragEnd: function (a, b) {
  421. var element = $("a.btn-dragsort", this);
  422. var data = table.bootstrapTable('getData');
  423. var current = data[parseInt($(this).data("index"))];
  424. var options = table.bootstrapTable('getOptions');
  425. //改变的值和改变的ID集合
  426. var ids = $.map($("tbody tr:visible", table), function (tr) {
  427. return data[parseInt($(tr).data("index"))][options.pk];
  428. });
  429. var changeid = current[options.pk];
  430. var pid = typeof current.pid != 'undefined' ? current.pid : '';
  431. var params = {
  432. url: table.bootstrapTable('getOptions').extend.dragsort_url,
  433. data: {
  434. ids: ids.join(','),
  435. changeid: changeid,
  436. pid: pid,
  437. field: Table.config.dragsortfield,
  438. orderway: options.sortOrder,
  439. table: options.extend.table,
  440. pk: options.pk
  441. }
  442. };
  443. Fast.api.ajax(params, function (data, ret) {
  444. var success = $(element).data("success") || $.noop;
  445. if (typeof success === 'function') {
  446. if (false === success.call(element, data, ret)) {
  447. return false;
  448. }
  449. }
  450. table.bootstrapTable('refresh');
  451. }, function (data, ret) {
  452. var error = $(element).data("error") || $.noop;
  453. if (typeof error === 'function') {
  454. if (false === error.call(element, data, ret)) {
  455. return false;
  456. }
  457. }
  458. table.bootstrapTable('refresh');
  459. });
  460. },
  461. placeHolderTemplate: ""
  462. });
  463. });
  464. table.on("click", "input[data-id][name='checkbox']", function (e) {
  465. var ids = $(this).data("id");
  466. table.bootstrapTable($(this).prop("checked") ? 'checkBy' : 'uncheckBy', {field: options.pk, values: [ids]});
  467. });
  468. table.on("click", "[data-id].btn-change", function (e) {
  469. e.preventDefault();
  470. var changer = $.proxy(function () {
  471. Table.api.multi($(this).data("action") ? $(this).data("action") : '', [$(this).data("id")], table, this);
  472. }, this);
  473. if (typeof $(this).data("confirm") !== 'undefined') {
  474. Layer.confirm($(this).data("confirm"), function (index) {
  475. changer();
  476. Layer.close(index);
  477. });
  478. } else {
  479. changer();
  480. }
  481. });
  482. table.on("click", "[data-id].btn-edit", function (e) {
  483. e.preventDefault();
  484. var ids = $(this).data("id");
  485. var row = Table.api.getrowbyid(table, ids);
  486. row.ids = ids;
  487. var url = Table.api.replaceurl(options.extend.edit_url, row, table);
  488. Fast.api.open(url, $(this).data("original-title") || $(this).attr("title") || __('Edit'), $(this).data() || {});
  489. });
  490. table.on("click", "[data-id].btn-del", function (e) {
  491. e.preventDefault();
  492. var id = $(this).data("id");
  493. var that = this;
  494. Layer.confirm(
  495. __('Are you sure you want to delete this item?'),
  496. {icon: 3, title: __('Warning'), shadeClose: true, btn: [__('OK'), __('Cancel')]},
  497. function (index) {
  498. Table.api.multi("del", id, table, that);
  499. Layer.close(index);
  500. }
  501. );
  502. });
  503. //修复dropdown定位溢出的情况
  504. if (options.fixDropdownPosition) {
  505. var tableBody = table.closest(".fixed-table-body");
  506. table.on('show.bs.dropdown fa.event.refreshdropdown', ".btn-group", function (e) {
  507. var dropdownMenu = $(".dropdown-menu", this);
  508. var btnGroup = $(this);
  509. var isPullRight = dropdownMenu.hasClass("pull-right") || dropdownMenu.hasClass("dropdown-menu-right");
  510. var left, top, position;
  511. if (true || dropdownMenu.outerHeight() + btnGroup.outerHeight() > tableBody.outerHeight() - 41) {
  512. position = 'fixed';
  513. top = btnGroup.offset().top - $(window).scrollTop() + btnGroup.outerHeight();
  514. if ((top + dropdownMenu.outerHeight()) > $(window).height()) {
  515. top = btnGroup.offset().top - dropdownMenu.outerHeight() - 5;
  516. }
  517. left = isPullRight ? btnGroup.offset().left + btnGroup.outerWidth() - dropdownMenu.outerWidth() : btnGroup.offset().left;
  518. }
  519. if (left || top) {
  520. dropdownMenu.css({
  521. position: position, left: left, top: top, right: 'inherit'
  522. });
  523. }
  524. });
  525. var checkdropdown = function () {
  526. if ($(".btn-group.open", table).length > 0 && $(".btn-group.open .dropdown-menu", table).css("position") == 'fixed') {
  527. $(".btn-group.open", table).trigger("fa.event.refreshdropdown");
  528. }
  529. };
  530. $(window).on("scroll", function () {
  531. checkdropdown();
  532. });
  533. tableBody.on("scroll", function () {
  534. checkdropdown();
  535. });
  536. }
  537. var id = table.attr("id");
  538. Table.list[id] = table;
  539. return table;
  540. },
  541. // 设置全局分页的单页显示数
  542. pageSize: function (pageSize) {
  543. if (!isNaN(pageSize)) {
  544. localStorage.setItem('page-size', pageSize);
  545. }
  546. },
  547. // 批量操作请求
  548. multi: function (action, ids, table, element) {
  549. var options = table.bootstrapTable('getOptions');
  550. var data = element ? $(element).data() : {};
  551. ids = ($.isArray(ids) ? ids.join(",") : ids);
  552. var url = typeof data.url !== "undefined" ? data.url : (action == "del" ? options.extend.del_url : options.extend.multi_url);
  553. var params = typeof data.params !== "undefined" ? (typeof data.params == 'object' ? $.param(data.params) : data.params) : '';
  554. options = {url: url, data: {action: action, ids: ids, params: params}};
  555. Fast.api.ajax(options, function (data, ret) {
  556. table.trigger("uncheckbox");
  557. var success = $(element).data("success") || $.noop;
  558. if (typeof success === 'function') {
  559. if (false === success.call(element, data, ret)) {
  560. return false;
  561. }
  562. }
  563. table.bootstrapTable('refresh');
  564. }, function (data, ret) {
  565. var error = $(element).data("error") || $.noop;
  566. if (typeof error === 'function') {
  567. if (false === error.call(element, data, ret)) {
  568. return false;
  569. }
  570. }
  571. });
  572. },
  573. // 单元格元素事件
  574. events: {
  575. operate: {
  576. 'click .btn-editone': function (e, value, row, index) {
  577. e.stopPropagation();
  578. e.preventDefault();
  579. var table = $(this).closest('table');
  580. var options = table.bootstrapTable('getOptions');
  581. var ids = row[options.pk];
  582. row = $.extend({}, row ? row : {}, {ids: ids});
  583. var url = options.extend.edit_url;
  584. Fast.api.open(Table.api.replaceurl(url, row, table), $(this).data("original-title") || $(this).attr("title") || __('Edit'), $(this).data() || {});
  585. },
  586. 'click .btn-delone': function (e, value, row, index) {
  587. e.stopPropagation();
  588. e.preventDefault();
  589. var that = this;
  590. var top = $(that).offset().top - $(window).scrollTop();
  591. var left = $(that).offset().left - $(window).scrollLeft() - 260;
  592. if (top + 154 > $(window).height()) {
  593. top = top - 154;
  594. }
  595. if ($(window).width() < 480) {
  596. top = left = undefined;
  597. }
  598. Layer.confirm(
  599. __('Are you sure you want to delete this item?'),
  600. {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true, btn: [__('OK'), __('Cancel')]},
  601. function (index) {
  602. var table = $(that).closest('table');
  603. var options = table.bootstrapTable('getOptions');
  604. Table.api.multi("del", row[options.pk], table, that);
  605. Layer.close(index);
  606. }
  607. );
  608. }
  609. },//单元格图片预览
  610. image: {
  611. 'click .img-center': function (e, value, row, index) {
  612. var data = [];
  613. value = value === null ? '' : value.toString();
  614. var arr = value != '' ? value.split(",") : [];
  615. var url;
  616. $.each(arr, function (index, value) {
  617. url = Fast.api.cdnurl(value);
  618. data.push({
  619. src: url,
  620. thumb: url.match(/^(\/|data:image\\)/) ? url : url + Config.upload.thumbstyle
  621. });
  622. });
  623. Layer.photos({
  624. photos: {
  625. "start": $(this).parent().index(),
  626. "data": data
  627. },
  628. anim: 5 //0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
  629. });
  630. },
  631. }
  632. },
  633. // 单元格数据格式化
  634. formatter: {
  635. icon: function (value, row, index) {
  636. value = value === null ? '' : value.toString();
  637. value = value.indexOf(" ") > -1 ? value : "fa fa-" + value;
  638. //渲染fontawesome图标
  639. return '<i class="' + value + '"></i> ' + value;
  640. },
  641. image: function (value, row, index) {
  642. value = value == null || value.length === 0 ? '' : value.toString();
  643. value = value ? value : '/assets/img/blank.gif';
  644. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  645. var url = Fast.api.cdnurl(value, true);
  646. url = url.match(/^(\/|data:image\\)/) ? url : url + Config.upload.thumbstyle;
  647. return '<a href="javascript:"><img class="' + classname + '" src="' + url + '" /></a>';
  648. },
  649. images: function (value, row, index) {
  650. value = value == null || value.length === 0 ? '' : value.toString();
  651. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  652. var arr = value != '' ? value.split(',') : [];
  653. var html = [];
  654. var url;
  655. $.each(arr, function (i, value) {
  656. value = value ? value : '/assets/img/blank.gif';
  657. url = Fast.api.cdnurl(value, true);
  658. url = url.match(/^(\/|data:image\\)/) ? url : url + Config.upload.thumbstyle;
  659. html.push('<a href="javascript:"><img class="' + classname + '" src="' + url + '" /></a>');
  660. });
  661. return html.join(' ');
  662. },
  663. file: function (value, row, index) {
  664. value = value == null || value.length === 0 ? '' : value.toString();
  665. value = Fast.api.cdnurl(value, true);
  666. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  667. var suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(value);
  668. suffix = suffix ? suffix[1] : 'file';
  669. var url = Fast.api.fixurl("ajax/icon?suffix=" + suffix);
  670. return '<a href="' + value + '" target="_blank"><img src="' + url + '" class="' + classname + '"></a>';
  671. },
  672. files: function (value, row, index) {
  673. value = value == null || value.length === 0 ? '' : value.toString();
  674. var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
  675. var arr = value != '' ? value.split(',') : [];
  676. var html = [];
  677. var suffix, url;
  678. $.each(arr, function (i, value) {
  679. value = Fast.api.cdnurl(value, true);
  680. suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(value);
  681. suffix = suffix ? suffix[1] : 'file';
  682. url = Fast.api.fixurl("ajax/icon?suffix=" + suffix);
  683. html.push('<a href="' + value + '" target="_blank"><img src="' + url + '" class="' + classname + '"></a>');
  684. });
  685. return html.join(' ');
  686. },
  687. content: function (value, row, index) {
  688. var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "250px";
  689. return "<div style='white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:" + width + ";'>" + value + "</div>";
  690. },
  691. status: function (value, row, index) {
  692. var custom = {normal: 'success', hidden: 'gray', deleted: 'danger', locked: 'info'};
  693. if (typeof this.custom !== 'undefined') {
  694. custom = $.extend(custom, this.custom);
  695. }
  696. this.custom = custom;
  697. this.icon = 'fa fa-circle';
  698. return Table.api.formatter.normal.call(this, value, row, index);
  699. },
  700. normal: function (value, row, index) {
  701. var colorArr = ["primary", "success", "danger", "warning", "info", "gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];
  702. var custom = {};
  703. if (typeof this.custom !== 'undefined') {
  704. custom = $.extend(custom, this.custom);
  705. }
  706. value = value == null || value.length === 0 ? '' : value.toString();
  707. var keys = typeof this.searchList === 'object' ? Object.keys(this.searchList) : [];
  708. var index = keys.indexOf(value);
  709. var color = value && typeof custom[value] !== 'undefined' ? custom[value] : null;
  710. var display = index > -1 ? this.searchList[value] : null;
  711. var icon = typeof this.icon !== 'undefined' ? this.icon : null;
  712. if (!color) {
  713. color = index > -1 && typeof colorArr[index] !== 'undefined' ? colorArr[index] : 'primary';
  714. }
  715. if (!display) {
  716. display = __(value.charAt(0).toUpperCase() + value.slice(1));
  717. }
  718. var html = '<span class="text-' + color + '">' + (icon ? '<i class="' + icon + '"></i> ' : '') + display + '</span>';
  719. if (this.operate != false) {
  720. html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + this.field + '" data-value="' + value + '">' + html + '</a>';
  721. }
  722. return html;
  723. },
  724. toggle: function (value, row, index) {
  725. var table = this.table;
  726. var options = table ? table.bootstrapTable('getOptions') : {};
  727. var pk = options.pk || "id";
  728. var color = typeof this.color !== 'undefined' ? this.color : 'success';
  729. var yes = typeof this.yes !== 'undefined' ? this.yes : 1;
  730. var no = typeof this.no !== 'undefined' ? this.no : 0;
  731. var url = typeof this.url !== 'undefined' ? this.url : '';
  732. var confirm = '';
  733. var disable = false;
  734. if (typeof this.confirm !== "undefined") {
  735. confirm = typeof this.confirm === "function" ? this.confirm.call(this, value, row, index) : this.confirm;
  736. }
  737. if (typeof this.disable !== "undefined") {
  738. disable = typeof this.disable === "function" ? this.disable.call(this, value, row, index) : this.disable;
  739. }
  740. return "<a href='javascript:;' data-toggle='tooltip' title='" + __('Click to toggle') + "' class='btn-change " + (disable ? 'btn disabled no-padding' : '') + "' data-index='" + index + "' data-id='"
  741. + row[pk] + "' " + (url ? "data-url='" + url + "'" : "") + (confirm ? "data-confirm='" + confirm + "'" : "") + " data-params='" + this.field + "=" + (value == yes ? no : yes) + "'><i class='fa fa-toggle-on text-success text-" + color + " " + (value == yes ? '' : 'fa-flip-horizontal text-gray') + " fa-2x'></i></a>";
  742. },
  743. url: function (value, row, index) {
  744. value = value == null || value.length === 0 ? '' : value.toString();
  745. return '<div class="input-group input-group-sm" style="width:250px;margin:0 auto;"><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>';
  746. },
  747. search: function (value, row, index) {
  748. var field = this.field;
  749. if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
  750. value = row[this.customField];
  751. field = this.customField;
  752. }
  753. return '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', value) + '" data-field="' + field + '" data-value="' + value + '">' + value + '</a>';
  754. },
  755. addtabs: function (value, row, index) {
  756. var url = Table.api.replaceurl(this.url || '', row, this.table);
  757. var title = this.atitle ? this.atitle : __("Search %s", value);
  758. return '<a href="' + Fast.api.fixurl(url) + '" class="addtabsit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  759. },
  760. dialog: function (value, row, index) {
  761. var url = Table.api.replaceurl(this.url || '', row, this.table);
  762. var title = this.atitle ? this.atitle : __("View %s", value);
  763. return '<a href="' + Fast.api.fixurl(url) + '" class="dialogit" data-value="' + value + '" title="' + title + '">' + value + '</a>';
  764. },
  765. flag: function (value, row, index) {
  766. var that = this;
  767. value = value == null || value.length === 0 ? '' : value.toString();
  768. var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
  769. //如果字段列有定义custom
  770. if (typeof this.custom !== 'undefined') {
  771. colorArr = $.extend(colorArr, this.custom);
  772. }
  773. var field = this.field;
  774. if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
  775. value = row[this.customField];
  776. field = this.customField;
  777. }
  778. if (typeof that.searchList === 'object' && typeof that.custom === 'undefined') {
  779. var i = 0;
  780. var searchValues = Object.values(colorArr);
  781. $.each(that.searchList, function (key, val) {
  782. if (typeof colorArr[key] == 'undefined') {
  783. colorArr[key] = searchValues[i];
  784. i = typeof searchValues[i + 1] === 'undefined' ? 0 : i + 1;
  785. }
  786. });
  787. }
  788. //渲染Flag
  789. var html = [];
  790. var arr = value != '' ? value.split(',') : [];
  791. var color, display, label;
  792. $.each(arr, function (i, value) {
  793. value = value == null || value.length === 0 ? '' : value.toString();
  794. if (value == '')
  795. return true;
  796. color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
  797. display = typeof that.searchList !== 'undefined' && typeof that.searchList[value] !== 'undefined' ? that.searchList[value] : __(value.charAt(0).toUpperCase() + value.slice(1));
  798. label = '<span class="label label-' + color + '">' + display + '</span>';
  799. if (that.operate) {
  800. html.push('<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + label + '</a>');
  801. } else {
  802. html.push(label);
  803. }
  804. });
  805. return html.join(' ');
  806. },
  807. label: function (value, row, index) {
  808. return Table.api.formatter.flag.call(this, value, row, index);
  809. },
  810. datetime: function (value, row, index) {
  811. var datetimeFormat = typeof this.datetimeFormat === 'undefined' ? 'YYYY-MM-DD HH:mm:ss' : this.datetimeFormat;
  812. if (isNaN(value)) {
  813. return value ? Moment(value).format(datetimeFormat) : __('None');
  814. } else {
  815. return value ? Moment(parseInt(value) * 1000).format(datetimeFormat) : __('None');
  816. }
  817. },
  818. operate: function (value, row, index) {
  819. var table = this.table;
  820. // 操作配置
  821. var options = table ? table.bootstrapTable('getOptions') : {};
  822. // 默认按钮组
  823. var buttons = $.extend([], this.buttons || []);
  824. // 所有按钮名称
  825. var names = [];
  826. buttons.forEach(function (item) {
  827. names.push(item.name);
  828. });
  829. if (options.extend.dragsort_url !== '' && names.indexOf('dragsort') === -1) {
  830. buttons.push(Table.button.dragsort);
  831. }
  832. if (options.extend.edit_url !== '' && names.indexOf('edit') === -1) {
  833. Table.button.edit.url = options.extend.edit_url;
  834. buttons.push(Table.button.edit);
  835. }
  836. if (options.extend.del_url !== '' && names.indexOf('del') === -1) {
  837. buttons.push(Table.button.del);
  838. }
  839. return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
  840. }
  841. ,
  842. buttons: function (value, row, index) {
  843. // 默认按钮组
  844. var buttons = $.extend([], this.buttons || []);
  845. return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
  846. }
  847. },
  848. buttonlink: function (column, buttons, value, row, index, type) {
  849. var table = column.table;
  850. column.clickToSelect = false;
  851. type = typeof type === 'undefined' ? 'buttons' : type;
  852. var options = table ? table.bootstrapTable('getOptions') : {};
  853. var html = [];
  854. var hidden, visible, disable, url, classname, icon, text, title, refresh, confirm, extend,
  855. dropdown, link;
  856. var fieldIndex = column.fieldIndex;
  857. var dropdowns = {};
  858. $.each(buttons, function (i, j) {
  859. if (type === 'operate') {
  860. if (j.name === 'dragsort' && typeof row[Table.config.dragsortfield] === 'undefined') {
  861. return true;
  862. }
  863. if (['add', 'edit', 'del', 'multi', 'dragsort'].indexOf(j.name) > -1 && !options.extend[j.name + "_url"]) {
  864. return true;
  865. }
  866. }
  867. var attr = table.data(type + "-" + j.name);
  868. if (typeof attr === 'undefined' || attr) {
  869. hidden = typeof j.hidden === 'function' ? j.hidden.call(table, row, j) : (typeof j.hidden !== 'undefined' ? j.hidden : false);
  870. if (hidden) {
  871. return true;
  872. }
  873. visible = typeof j.visible === 'function' ? j.visible.call(table, row, j) : (typeof j.visible !== 'undefined' ? j.visible : true);
  874. if (!visible) {
  875. return true;
  876. }
  877. dropdown = j.dropdown ? j.dropdown : '';
  878. url = j.url ? j.url : '';
  879. url = typeof url === 'function' ? url.call(table, row, j) : (url ? Fast.api.fixurl(Table.api.replaceurl(url, row, table)) : 'javascript:;');
  880. classname = j.classname ? j.classname : (dropdown ? 'btn-' + name + 'one' : 'btn-primary btn-' + name + 'one');
  881. icon = j.icon ? j.icon : '';
  882. text = typeof j.text === 'function' ? j.text.call(table, row, j) : j.text ? j.text : '';
  883. title = typeof j.title === 'function' ? j.title.call(table, row, j) : j.title ? j.title : text;
  884. refresh = j.refresh ? 'data-refresh="' + j.refresh + '"' : '';
  885. confirm = typeof j.confirm === 'function' ? j.confirm.call(table, row, j) : (typeof j.confirm !== 'undefined' ? j.confirm : false);
  886. confirm = confirm ? 'data-confirm="' + confirm + '"' : '';
  887. extend = j.extend ? j.extend : '';
  888. disable = typeof j.disable === 'function' ? j.disable.call(table, row, j) : (typeof j.disable !== 'undefined' ? j.disable : false);
  889. if (disable) {
  890. classname = classname + ' disabled';
  891. }
  892. link = '<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>';
  893. if (dropdown) {
  894. if (typeof dropdowns[dropdown] == 'undefined') {
  895. dropdowns[dropdown] = [];
  896. }
  897. dropdowns[dropdown].push(link);
  898. } else {
  899. html.push(link);
  900. }
  901. }
  902. });
  903. if (!$.isEmptyObject(dropdowns)) {
  904. var dropdownHtml = [];
  905. $.each(dropdowns, function (i, j) {
  906. dropdownHtml.push('<div class="btn-group"><button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown">' + i + '</button><button type="button" class="btn btn-primary dropdown-toggle btn-xs" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right"><li>' + j.join('</li><li>') + '</li></ul></div>');
  907. });
  908. html.unshift(dropdownHtml);
  909. }
  910. return html.join(' ');
  911. },
  912. //替换URL中的数据
  913. replaceurl: function (url, row, table) {
  914. var options = table ? table.bootstrapTable('getOptions') : null;
  915. var ids = options ? row[options.pk] : 0;
  916. row.ids = ids ? ids : (typeof row.ids !== 'undefined' ? row.ids : 0);
  917. url = url == null || url.length === 0 ? '' : url.toString();
  918. //自动添加ids参数
  919. url = !url.match(/\{ids\}/i) ? url + (url.match(/(\?|&)+/) ? "&ids=" : "/ids/") + '{ids}' : url;
  920. url = url.replace(/\{(.*?)\}/gi, function (matched) {
  921. matched = matched.substring(1, matched.length - 1);
  922. if (matched.indexOf(".") !== -1) {
  923. var temp = row;
  924. var arr = matched.split(/\./);
  925. for (var i = 0; i < arr.length; i++) {
  926. if (typeof temp[arr[i]] !== 'undefined') {
  927. temp = temp[arr[i]];
  928. }
  929. }
  930. return typeof temp === 'object' ? '' : temp;
  931. }
  932. return row[matched];
  933. });
  934. return url;
  935. },
  936. // 获取选中的条目ID集合
  937. selectedids: function (table, current) {
  938. var options = table.bootstrapTable('getOptions');
  939. //如果有设置翻页记忆模式
  940. if (!current && options.maintainSelected) {
  941. return options.selectedIds;
  942. }
  943. return $.map(table.bootstrapTable('getSelections'), function (row) {
  944. return row[options.pk];
  945. });
  946. },
  947. //获取选中的数据
  948. selecteddata: function (table, current) {
  949. var options = table.bootstrapTable('getOptions');
  950. //如果有设置翻页记忆模式
  951. if (!current && options.maintainSelected) {
  952. return options.selectedData;
  953. }
  954. return table.bootstrapTable('getSelections');
  955. },
  956. // 切换复选框状态
  957. toggleattr: function (table) {
  958. $("input[type='checkbox']", table).trigger('click');
  959. },
  960. // 根据行索引获取行数据
  961. getrowdata: function (table, index) {
  962. index = parseInt(index);
  963. var data = table.bootstrapTable('getData');
  964. return typeof data[index] !== 'undefined' ? data[index] : null;
  965. },
  966. // 根据行索引获取行数据
  967. getrowbyindex: function (table, index) {
  968. return Table.api.getrowdata(table, index);
  969. },
  970. // 根据主键ID获取行数据
  971. getrowbyid: function (table, id) {
  972. var row = {};
  973. var options = table.bootstrapTable("getOptions");
  974. $.each(Table.api.selecteddata(table), function (i, j) {
  975. if (j[options.pk] == id) {
  976. row = j;
  977. return false;
  978. }
  979. });
  980. return row;
  981. }
  982. },
  983. };
  984. return Table;
  985. });