require-table.js 54 KB

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