admin.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. // +----------------------------------------------------------------------
  2. // | ThinkAdmin
  3. // +----------------------------------------------------------------------
  4. // | 版权所有 2014~2021 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  5. // +----------------------------------------------------------------------
  6. // | 官方网站: https://thinkadmin.top
  7. // +----------------------------------------------------------------------
  8. // | 开源协议 ( https://mit-license.org )
  9. // | 免费声明 ( https://thinkadmin.top/disclaimer )
  10. // +----------------------------------------------------------------------
  11. // | gitee 代码仓库:https://gitee.com/zoujingli/ThinkAdmin
  12. // | github 代码仓库:https://github.com/zoujingli/ThinkAdmin
  13. // +----------------------------------------------------------------------
  14. /*! 数组兼容处理 */
  15. if (typeof Array.prototype.some !== 'function') {
  16. Array.prototype.some = function (callable) {
  17. for (var i in this) if (callable(this[i], i, this) === true) {
  18. return true;
  19. }
  20. return false;
  21. };
  22. }
  23. if (typeof Array.prototype.every !== 'function') {
  24. Array.prototype.every = function (callable) {
  25. for (var i in this) if (callable(this[i], i, this) === false) {
  26. return false;
  27. }
  28. return true;
  29. };
  30. }
  31. if (typeof Array.prototype.forEach !== 'function') {
  32. Array.prototype.forEach = function (callable, context) {
  33. typeof context === "undefined" ? context = window : null;
  34. for (var i in this) callable.call(context, this[i], i, this)
  35. };
  36. }
  37. /*! 脚本应用根路径 */
  38. window.appRoot = (function (src) {
  39. return src.pop(), src.pop(), src.join('/') + '/';
  40. })(document.scripts[document.scripts.length - 1].src.split('/'));
  41. /*! 静态插件库路径 */
  42. window.baseRoot = (function (src) {
  43. return src.substring(0, src.lastIndexOf("/") + 1);
  44. })(document.scripts[document.scripts.length - 1].src);
  45. /*! 动态插件库路径 */
  46. window.tapiRoot = window.tapiRoot || window.appRoot + "admin";
  47. /*! 配置 layui 插件 */
  48. layui.config({base: baseRoot + 'plugs/layui_exts/'});
  49. /*! 挂载 layui & jquery 对象 */
  50. if (typeof jQuery === 'undefined') window.$ = window.jQuery = layui.$;
  51. window.form = layui.form, window.layer = layui.layer, window.laydate = layui.laydate;
  52. /*! 配置 require 参数 */
  53. require.config({
  54. waitSeconds: 60,
  55. baseUrl: baseRoot,
  56. map: {'*': {css: baseRoot + 'plugs/require/css.js'}},
  57. paths: {
  58. 'vue': ['plugs/vue/vue.min'],
  59. 'md5': ['plugs/jquery/md5.min'],
  60. 'json': ['plugs/jquery/json.min'],
  61. 'xlsx': ['plugs/jquery/xlsx.min'],
  62. 'excel': ['plugs/jquery/excel.xlsx'],
  63. 'base64': ['plugs/jquery/base64.min'],
  64. 'upload': [tapiRoot + '/api.upload/index?'],
  65. 'angular': ['plugs/angular/angular.min'],
  66. 'cropper': ['plugs/cropper/cropper.min'],
  67. 'echarts': ['plugs/echarts/echarts.min'],
  68. 'ckeditor': ['plugs/ckeditor/ckeditor'],
  69. 'websocket': ['plugs/socket/websocket'],
  70. 'pcasunzips': ['plugs/jquery/pcasunzips'],
  71. 'sortablejs': ['plugs/sortable/sortable.min'],
  72. 'vue.sortable': ['plugs/sortable/vue.draggable.min'],
  73. 'jquery.ztree': ['plugs/ztree/ztree.all.min'],
  74. 'jquery.masonry': ['plugs/jquery/masonry.min'],
  75. 'jquery.cropper': ['plugs/cropper/cropper.min'],
  76. 'jquery.autocompleter': ['plugs/jquery/autocompleter.min'],
  77. },
  78. shim: {
  79. 'excel': {deps: [baseRoot + 'plugs/layui_exts/excel.js']},
  80. 'websocket': {deps: [baseRoot + 'plugs/socket/swfobject.min.js']},
  81. 'cropper': {deps: ['css!' + baseRoot + 'plugs/cropper/cropper.min.css']},
  82. 'vue.sortable': {deps: ['vue', 'sortablejs']},
  83. 'jquery.ztree': {deps: ['jquery', 'css!' + baseRoot + 'plugs/ztree/zTreeStyle/zTreeStyle.css']},
  84. 'jquery.autocompleter': {deps: ['jquery', 'css!' + baseRoot + 'plugs/jquery/autocompleter.css']},
  85. }
  86. });
  87. /*! 注册 jquery 组件 */
  88. define('jquery', [], function () {
  89. return layui.$;
  90. });
  91. $(function () {
  92. window.$body = $('body');
  93. /*! 注册单次事件 */
  94. function onEvent(event, select, callable) {
  95. return $body.off(event, select).on(event, select, callable);
  96. }
  97. /*! 读取 data-rule 绑定 table 值 */
  98. function applyRuleValue(elem, data) {
  99. // 新 tableId 规则兼容处理
  100. if (elem.dataset.tableId && elem.dataset.rule) {
  101. var idx1, idx2, temp, regx, field, rule = {};
  102. var json = layui.table.checkStatus(elem.dataset.tableId).data;
  103. layui.each(elem.dataset.rule.split(';'), function (idx, item, attr) {
  104. (attr = item.split('#', 2)), rule[attr[0]] = attr[1];
  105. });
  106. for (idx1 in rule) {
  107. temp = [], regx = new RegExp(/^{(.*?)}$/);
  108. if (regx.test(rule[idx1]) && (field = rule[idx1].replace(regx, '$1'))) {
  109. for (idx2 in json) if (json[idx2][field]) temp.push(json[idx2][field]);
  110. if (temp.length < 1) return $.msg.tips('请选择需要更改的数据!'), false;
  111. data[idx1] = temp.join(',');
  112. } else {
  113. data[idx1] = rule[idx1];
  114. }
  115. }
  116. return data;
  117. } else {
  118. var value = elem.dataset.value || (function (rule, array) {
  119. $(elem.dataset.target || 'input[type=checkbox].list-check-box').map(function () {
  120. this.checked && array.push(this.value);
  121. });
  122. return array.length > 0 ? rule.replace('{key}', array.join(',')) : '';
  123. })(elem.dataset.rule || '', []) || '';
  124. if (value.length < 1) return $.msg.tips('请选择需要更改的数据!'), false;
  125. return value.split(';').forEach(function (item) {
  126. data[item.split('#')[0]] = item.split('#')[1];
  127. }), data;
  128. }
  129. }
  130. /*! 消息组件实例 */
  131. $.msg = new function () {
  132. var that = this;
  133. this.idx = [], this.shade = [0.02, '#000'];
  134. /*! 关闭消息框 */
  135. this.close = function (index) {
  136. if (index !== null) return layer.close(index);
  137. for (var i in this.idx) that.close(this.idx[i]);
  138. this.idx = [];
  139. };
  140. /*! 弹出警告框 */
  141. this.alert = function (msg, call) {
  142. var idx = layer.alert(msg, {end: call, scrollbar: false});
  143. return that.idx.push(idx), idx;
  144. };
  145. /*! 显示成功类型的消息 */
  146. this.success = function (msg, time, call) {
  147. var idx = layer.msg(msg, {icon: 1, shade: this.shade, scrollbar: false, end: call, time: (time || 2) * 1000, shadeClose: true});
  148. return that.idx.push(idx), idx;
  149. };
  150. /*! 显示失败类型的消息 */
  151. this.error = function (msg, time, call) {
  152. var idx = layer.msg(msg, {icon: 2, shade: this.shade, scrollbar: false, time: (time || 3) * 1000, end: call, shadeClose: true});
  153. return that.idx.push(idx), idx;
  154. };
  155. /*! 状态消息提示 */
  156. this.tips = function (msg, time, call) {
  157. var idx = layer.msg(msg, {time: (time || 3) * 1000, shade: this.shade, end: call, shadeClose: true});
  158. return that.idx.push(idx), idx;
  159. };
  160. /*! 显示加载提示 */
  161. this.loading = function (msg, call) {
  162. var idx = msg ? layer.msg(msg, {icon: 16, scrollbar: false, shade: this.shade, time: 0, end: call}) : layer.load(2, {time: 0, scrollbar: false, shade: this.shade, end: call});
  163. return that.idx.push(idx), idx;
  164. };
  165. /*! 页面加载层 */
  166. this.page = new function () {
  167. this.$body = $('body>.think-page-loader');
  168. this.$main = $('.think-page-body+.think-page-loader');
  169. this.stat = function () {
  170. return this.$body.is(':visible');
  171. }, this.show = function () {
  172. this.stat() || this.$main.removeClass('layui-hide').show();
  173. }, this.hide = function () {
  174. if (this.time) clearTimeout(this.time);
  175. this.time = setTimeout(function () {
  176. (that.page.time = 0) || that.page.$main.fadeOut();
  177. }, 200);
  178. };
  179. };
  180. /*! 确认对话框 */
  181. this.confirm = function (msg, ok, no) {
  182. return layer.confirm(msg, {title: '操作确认', btn: ['确认', '取消']}, function (idx) {
  183. (typeof ok === 'function' && ok.call(this, idx)), that.close(idx);
  184. }, function (idx) {
  185. (typeof no === 'function' && no.call(this, idx)), that.close(idx);
  186. });
  187. };
  188. /*! 自动处理JSON数据 */
  189. this.auto = function (ret, time) {
  190. var url = ret.url || (typeof ret.data === 'string' ? ret.data : '');
  191. var msg = ret.msg || (typeof ret.info === 'string' ? ret.info : '');
  192. if (parseInt(ret.code) === 1 && time === 'false') {
  193. return url ? (location.href = url) : $.form.reload();
  194. }
  195. return (parseInt(ret.code) === 1) ? this.success(msg, time, function () {
  196. (url ? (location.href = url) : $.form.reload()), that.close(null);
  197. }) : this.error(msg, 3, function () {
  198. url ? location.href = url : '';
  199. });
  200. };
  201. };
  202. /*! 表单自动化组件 */
  203. $.form = new function () {
  204. var that = this;
  205. /*! 内容区选择器 */
  206. this.selecter = '.layui-layout-admin>.layui-body>.think-page-body';
  207. /*! 刷新当前页面 */
  208. this.reload = function (force) {
  209. if (force) top.location.reload();
  210. else if (self !== top) location.reload();
  211. else window.onhashchange.call(this);
  212. };
  213. /*! 内容区域动态加载后初始化 */
  214. this.reInit = function ($dom) {
  215. $(window).trigger('scroll'), $.vali.listen(this), $dom = $dom || $(this.selecter);
  216. return $dom.find('[required]').map(function ($parent) {
  217. if (($parent = $(this).parent()) && $parent.is('label')) {
  218. $parent.addClass('label-required-prev');
  219. } else {
  220. $parent.prevAll('label').addClass('label-required-next');
  221. }
  222. }), $dom.find('input[data-date-range]').map(function () {
  223. this.setAttribute('autocomplete', 'off'), laydate.render({
  224. type: this.dataset.dateRange || 'date', range: true, elem: this, done: function (value) {
  225. $(this.elem).val(value).trigger('change');
  226. }
  227. });
  228. }), $dom.find('input[data-date-input]').map(function () {
  229. this.setAttribute('autocomplete', 'off'), laydate.render({
  230. type: this.dataset.dateInput || 'date', range: false, elem: this, done: function (value) {
  231. $(this.elem).val(value).trigger('change');
  232. }
  233. });
  234. }), $dom.find('[data-lazy-src]:not([data-lazy-loaded])').each(function () {
  235. if (this.dataset.lazyLoaded !== 'true') {
  236. this.dataset.lazyLoaded = "true";
  237. if (this.nodeName === 'IMG') {
  238. this.src = this.dataset.lazySrc;
  239. } else {
  240. this.style.backgroundImage = 'url(' + this.dataset.lazySrc + ')';
  241. }
  242. }
  243. }), $dom;
  244. };
  245. /*! 在内容区显示视图 */
  246. this.show = function (html) {
  247. $(this.selecter).html(html), setTimeout(function () {
  248. that.reInit($(that.selecter));
  249. }, 500);
  250. };
  251. /*! 异步加载的数据 */
  252. this.load = function (url, data, method, callable, loading, tips, time, headers) {
  253. // 如果主页面 loader 显示中,绝对不显示 loading 图标
  254. loading = $('.layui-page-loader').is(':visible') ? false : loading;
  255. var loadidx = loading !== false ? $.msg.loading(tips) : 0;
  256. if (typeof data === 'object' && typeof data['_token_'] === 'string') {
  257. headers = headers || {}, headers['User-Form-Token'] = data['_token_'], delete data['_token_'];
  258. }
  259. $.ajax({
  260. data: data || {}, type: method || 'GET', url: $.menu.parseUri(url), beforeSend: function (xhr, i) {
  261. if (typeof Pace === 'object' && loading !== false) Pace.restart();
  262. if (typeof headers === 'object') for (i in headers) xhr.setRequestHeader(i, headers[i]);
  263. }, error: function (XMLHttpRequest, $dialog, layIdx, iframe) {
  264. if (parseInt(XMLHttpRequest.status) !== 200 && XMLHttpRequest.responseText.indexOf('Call Stack') > -1) try {
  265. layIdx = layer.open({title: XMLHttpRequest.status + ' - ' + XMLHttpRequest.statusText, type: 2, move: false, content: 'javascript:;'});
  266. layer.full(layIdx), $dialog = $('#layui-layer' + layIdx), iframe = $dialog.find('iframe').get(0);
  267. (iframe.contentDocument || iframe.contentWindow.document).write(XMLHttpRequest.responseText);
  268. $dialog.find('.layui-layer-setwin').css({right: '35px', top: '28px'}).find('a').css({marginLeft: 0});
  269. $dialog.find('.layui-layer-title').css({color: 'red', height: '70px', lineHeight: '70px', fontSize: '22px', textAlign: 'center', fontWeight: 700});
  270. } catch (e) {
  271. layer.close(layIdx);
  272. }
  273. layer.closeAll('loading');
  274. if (parseInt(XMLHttpRequest.status) !== 200) {
  275. $.msg.tips('E' + XMLHttpRequest.status + ' - 服务器繁忙,请稍候再试!');
  276. } else {
  277. this.success(XMLHttpRequest.responseText);
  278. }
  279. }, success: function (ret) {
  280. if (typeof callable === 'function' && callable.call(that, ret) === false) return false;
  281. return typeof ret === 'object' ? $.msg.auto(ret, time || ret.wait || undefined) : that.show(ret);
  282. }, complete: function () {
  283. $.msg.close(loadidx);
  284. }
  285. });
  286. };
  287. /*! 以 HASH 打开新网页 */
  288. this.href = function (url, ele) {
  289. // 重置表格页数缓存
  290. if (ele && ele.dataset.menuNode) layui.sessionData('pages', null);
  291. if (url !== '#') location.hash = $.menu.parseUri(url, ele);
  292. else if (ele && ele.dataset.menuNode) $('[data-menu-node^="' + ele.dataset.menuNode + '-"]:first').trigger('click');
  293. };
  294. /*! 加载 HTML 到 BODY 位置 */
  295. this.open = function (url, data, call, load, tips) {
  296. this.load(url, data, 'get', function (ret) {
  297. return (typeof ret === 'object' ? $.msg.auto(ret) : that.show(ret)), false;
  298. }, load, tips);
  299. };
  300. /*! 打开 IFRAME 窗口 */
  301. this.iframe = function (url, name, area, offset, destroy) {
  302. return layer.open({title: name || '窗口', type: 2, area: area || ['800px', '580px'], end: destroy || null, offset: offset, fixed: true, maxmin: false, content: url});
  303. };
  304. /*! 加载 HTML 到弹出层 */
  305. this.modal = function (url, data, name, call, load, tips, area, offset) {
  306. this.load(url, data, 'GET', function (res) {
  307. if (typeof (res) === 'object') return $.msg.auto(res), false;
  308. $.msg.idx.push(layer.open({
  309. type: 1, btn: false, area: area || "800px", resize: false, content: res, title: name || '', offset: offset || 'auto', success: function ($dom, idx) {
  310. $.form.reInit($dom.off('click', '[data-close]').on('click', '[data-close]', function () {
  311. (function (confirm, callable) {
  312. confirm ? $.msg.confirm(confirm, callable) : callable();
  313. })(this.dataset.confirm, function () {
  314. layer.close(idx);
  315. });
  316. }));
  317. }
  318. }));
  319. return (typeof call === 'function') && call.call(that);
  320. }, load, tips);
  321. };
  322. };
  323. /*! 后台菜单辅助插件 */
  324. $.menu = new function () {
  325. var that = this;
  326. /*! 计算 URL 地址中有效的 URI */
  327. this.getUri = function (uri) {
  328. uri = uri || location.href;
  329. uri = (uri.indexOf(location.host) > -1 ? uri.split(location.host)[1] : uri);
  330. return (uri.indexOf('#') > -1 ? uri.split('#')[1] : uri).split('?')[0];
  331. };
  332. /*! 通过 URI 查询最有可能的菜单 NODE */
  333. this.queryNode = function (url, node) {
  334. if (!/^m-/.test(node = node || location.href.replace(/.*spm=([\d\-m]+).*/ig, '$1'))) {
  335. var $menu = $('[data-menu-node][data-open*="' + url.replace(/\.html$/ig, '') + '"]');
  336. return $menu.size() ? $menu.get(0).dataset.menuNode : '';
  337. }
  338. return node;
  339. };
  340. /*! URL 转 URI */
  341. this.parseUri = function (uri, elem, vars, temp, attrs) {
  342. vars = {}, attrs = [], elem = elem || document.createElement('a');
  343. if (uri.indexOf('?') > -1) uri.split('?')[1].split('&').forEach(function (item) {
  344. if (item.indexOf('=') > -1 && (temp = item.split('=')) && typeof temp[0] === 'string' && temp[0].length > 0) {
  345. vars[temp[0]] = decodeURIComponent(temp[1].replace(/%2B/ig, '%20'));
  346. }
  347. });
  348. uri = this.getUri(uri);
  349. if (typeof vars.spm !== 'string') vars.spm = elem.dataset.menuNode || this.queryNode(uri) || '';
  350. if (typeof vars.spm !== 'string' || vars.spm.length < 1) delete vars.spm;
  351. for (var i in vars) attrs.push(i + '=' + vars[i]);
  352. return uri + (attrs.length > 0 ? '?' + attrs.join('&') : '');
  353. };
  354. /*! 后台菜单动作初始化 */
  355. this.listen = function () {
  356. /*! 菜单模式切换 */
  357. var $menu = $('.layui-layout-admin'), miniClass = 'layui-layout-left-mini';
  358. /*! Mini 菜单模式切换及显示 */
  359. if (layui.data('admin-menu-type')['type-mini']) $menu.addClass(miniClass);
  360. /*! 菜单切换事件处理 */
  361. onEvent('click', '[data-target-menu-type]', function () {
  362. layui.data('admin-menu-type', {key: 'type-mini', value: $menu.toggleClass(miniClass).hasClass(miniClass)});
  363. });
  364. /*! 监听窗口尺寸处理 */
  365. (function (callable) {
  366. $(window).on('resize', callable).trigger('resize');
  367. })(function () {
  368. (layui.data('admin-menu-type')['type-mini'] || $body.width() < 1000) ? $menu.addClass(miniClass) : $menu.removeClass(miniClass);
  369. });
  370. /*! Mini 菜单模式时TIPS文字显示 */
  371. $('[data-target-tips]').mouseenter(function () {
  372. if ($menu.hasClass(miniClass)) (function (idx) {
  373. $(this).mouseleave(function () {
  374. layer.close(idx);
  375. });
  376. }).call(this, layer.tips(this.dataset.targetTips || '', this, {time: 0}));
  377. });
  378. /*! 左则二级菜单展示 */
  379. $('[data-submenu-layout]>a').on('click', function () {
  380. that.syncOpenStatus(1);
  381. });
  382. /*! 同步二级菜单展示状态 */
  383. this.syncOpenStatus = function (mode) {
  384. $('[data-submenu-layout]').map(function () {
  385. var node = this.dataset.submenuLayout;
  386. if (mode === 1) layui.data('admin-menu-stat', {key: node, value: $(this).hasClass('layui-nav-itemed') ? 2 : 1});
  387. else if ((layui.data('admin-menu-stat')[node] || 2) === 2) $(this).addClass('layui-nav-itemed');
  388. });
  389. };
  390. window.onhashchange = function () {
  391. var hash = location.hash || '', node;
  392. if (hash.length < 1) return $('[data-menu-node]:first').trigger('click');
  393. if (/^#(https?:)?(\/\/|\\\\)/.test(hash)) return $.msg.tips('禁止访问外部链接!');
  394. // $.msg.page.show(),$.form.load(hash, {}, 'get', $.msg.page.hide, true),that.syncOpenStatus(2);
  395. $.form.load(hash, {}, 'get', false, !$.msg.page.stat()), that.syncOpenStatus(2);
  396. /*! 菜单选择切换 */
  397. if (/^m-/.test(node = that.queryNode(that.getUri()))) {
  398. var $all = $('a[data-menu-node]').parent(), tmp = node.split('-'), tmpNode = tmp.shift();
  399. while (tmp.length > 0) {
  400. tmpNode = tmpNode + '-' + tmp.shift();
  401. $all = $all.not($('a[data-menu-node="' + tmpNode + '"]').parent().addClass('layui-this'));
  402. }
  403. $all.removeClass('layui-this');
  404. /*! 菜单模式切换 */
  405. if (node.split('-').length > 2) {
  406. var _tmp = node.split('-'), _node = _tmp.shift() + '-' + _tmp.shift();
  407. $('[data-menu-layout]').not($('[data-menu-layout="' + _node + '"]').removeClass('layui-hide')).addClass('layui-hide');
  408. $('[data-menu-node="' + node + '"]').parent().parent().parent().addClass('layui-nav-itemed');
  409. $('.layui-layout-admin').removeClass('layui-layout-left-hide');
  410. } else {
  411. $('.layui-layout-admin').addClass('layui-layout-left-hide');
  412. }
  413. that.syncOpenStatus(1);
  414. }
  415. };
  416. /*! URI初始化动作 */
  417. window.onhashchange.call(this);
  418. };
  419. };
  420. /*! 注册对象到Jq */
  421. $.vali = function (form, callable) {
  422. return $(form).data('validate') || new Validate();
  423. function Validate() {
  424. var that = this;
  425. /* 绑定表单元素 */
  426. this.form = $(form);
  427. /* 绑定元素事件, 筛选表单元素 */
  428. this.evts = 'blur change', this.tags = 'input,select,textarea';
  429. /* 预设检测规则 */
  430. this.patterns = {
  431. phone: '^1[3-9][0-9]{9}$',
  432. email: '^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$'
  433. };
  434. /*! 检测属性是否有定义 */
  435. this.hasProp = function (ele, prop) {
  436. var attrProp = ele.getAttribute(prop);
  437. return typeof attrProp !== 'undefined' && attrProp !== null && attrProp !== false;
  438. }, this.isRegex = function (ele) {
  439. var real = $.trim($(ele).val());
  440. var regexp = ele.getAttribute('pattern');
  441. regexp = this.patterns[regexp] || regexp;
  442. if (real === "" || !regexp) return true;
  443. return new RegExp(regexp, 'i').test(real);
  444. }, this.checkAllInput = function () {
  445. var status = true;
  446. return that.form.find(this.tags).each(function () {
  447. if (that.checkInput(this) === false) return $(this).focus(), status = false;
  448. }), status;
  449. }, this.checkInput = function (input) {
  450. if (this.hasProp(input, 'data-auto-none')) return true;
  451. var type = (input.getAttribute('type') || '').replace(/\W+/, "").toLowerCase();
  452. var ingores = ['file', 'reset', 'image', 'radio', 'checkbox', 'submit', 'hidden'];
  453. if (ingores.length > 0) for (var i in ingores) if (type === ingores[i]) return true;
  454. if (this.hasProp(input, 'required') && $.trim($(input).val()) === '') return this.remind(input);
  455. return this.isRegex(input) ? (this.hideError(input), true) : this.remind(input);
  456. }, this.remind = function (input) {
  457. if (!$(input).is(':visible')) return true;
  458. return this.showError(input, input.getAttribute('title') || input.getAttribute('placeholder') || '输入错误'), false;
  459. }, this.showError = function (ele, tip) {
  460. $(ele).addClass('validate-error');
  461. this.insertError(ele).addClass('layui-anim-fadein').css({width: 'auto'}).html(tip);
  462. }, this.hideError = function (ele) {
  463. $(ele).removeClass('validate-error');
  464. this.insertError(ele).removeClass('layui-anim-fadein').css({width: '30px'}).html('');
  465. }, this.insertError = function (ele) {
  466. if ($(ele).data('input-info')) return $(ele).data('input-info');
  467. var $html = $('<span class="absolute block layui-anim text-center font-s12 notselect" style="color:#A44;z-index:2"></span>');
  468. var $next = $(ele).nextAll('.input-right-icon'), right = ($next ? $next.width() + parseFloat($next.css('right') || '0') : 0) + 10;
  469. var style = {top: $(ele).position().top + 'px', right: right + 'px', lineHeight: ele.nodeName === 'TEXTAREA' ? '32px' : $(ele).css('height')};
  470. return $(ele).data('input-info', $html.css(style).insertAfter(ele)), $html;
  471. };
  472. /*! 表单元素验证 */
  473. this.form.attr({onsubmit: 'return false;', novalidate: 'novalidate'});
  474. this.form.off(this.evts, this.tags).on(this.evts, this.tags, function () {
  475. that.checkInput(this);
  476. }).attr('novalidate', 'novalidate').data('validate', this).bind("submit", function (evt) {
  477. evt.button = that.form.find('button[type=submit],button:not([type=button])');
  478. /* 检查所有表单元素是否通过H5的规则验证 */
  479. if (that.checkAllInput() && typeof callable === 'function') {
  480. if (typeof CKEDITOR === 'object' && typeof CKEDITOR.instances === 'object') {
  481. for (var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
  482. }
  483. /* 触发表单提交后,锁定三秒不能再次提交表单 */
  484. if (that.form.attr('submit-locked')) return false;
  485. that.form.attr('submit-locked', 1), evt.button.addClass('submit-button-loading');
  486. callable.call(this, that.form.formToJson()), setTimeout(function () {
  487. that.form.removeAttr('submit-locked'), evt.button.removeClass('submit-button-loading');
  488. }, 3000);
  489. }
  490. return evt.preventDefault(), false;
  491. }).find('[data-form-loaded]').map(function () {
  492. $(this).html(this.dataset.formLoaded || this.innerHTML);
  493. $(this).removeAttr('data-form-loaded').removeClass('layui-disabled');
  494. });
  495. }
  496. };
  497. /*! 自动监听规则内表单 */
  498. $.vali.listen = function () {
  499. $('form[data-auto]').map(function (index, form) {
  500. $(this).vali(function (data) {
  501. var type = form.method || 'POST', href = form.action || location.href;
  502. var call = window[form.dataset.callable || '_default_callable'] || undefined;
  503. var tips = form.dataset.tips || undefined, time = form.dataset.time || undefined;
  504. (function (confirm, callable) {
  505. confirm ? $.msg.confirm(confirm, callable) : callable();
  506. })(form.dataset.confirm, function () {
  507. $.form.load(href, data, type, call, true, tips, time);
  508. });
  509. });
  510. });
  511. };
  512. /*! 注册对象到JqFn */
  513. $.fn.vali = function (callable) {
  514. return this.each(function () {
  515. $.vali(this, callable);
  516. });
  517. };
  518. /*! 表单转JSON */
  519. $.fn.formToJson = function () {
  520. var self = this, data = {}, push = {};
  521. var rules = {key: /[a-zA-Z0-9_]+|(?=\[])/g, push: /^$/, fixed: /^\d+$/, named: /^[a-zA-Z0-9_]+$/};
  522. this.build = function (base, key, value) {
  523. return (base[key] = value), base;
  524. };
  525. this.pushCounter = function (name) {
  526. if (push[name] === undefined) push[name] = 0;
  527. return push[name]++;
  528. };
  529. $.each($(this).serializeArray(), function () {
  530. var key, keys = this.name.match(rules.key), merge = this.value, name = this.name;
  531. while ((key = keys.pop()) !== undefined) {
  532. name = name.replace(new RegExp("\\[" + key + "\\]$"), '');
  533. if (key.match(rules.push)) merge = self.build([], self.pushCounter(name), merge);
  534. else if (key.match(rules.fixed)) merge = self.build([], key, merge);
  535. else if (key.match(rules.named)) merge = self.build({}, key, merge);
  536. }
  537. data = $.extend(true, data, merge);
  538. });
  539. return data;
  540. };
  541. /*! 全局文件上传插件 */
  542. $.fn.uploadFile = function (callable, initialize) {
  543. return this.each(function () {
  544. if ($(this).data('inited')) return false;
  545. var that = $(this), mult = '|one|btn|'.indexOf(that.data('file') || 'one') > -1 ? 0 : 1;
  546. that.data('inited', true).data('multiple', mult), require(['upload'], function (apply) {
  547. apply(that, callable), (typeof initialize === 'function' && setTimeout(initialize, 100));
  548. });
  549. });
  550. };
  551. /*! 上传单张图片 */
  552. $.fn.uploadOneImage = function () {
  553. return this.each(function () {
  554. if ($(this).data('inited')) return true; else $(this).data('inited', true);
  555. var $in = $(this), $bt = $('<a data-file class="uploadimage transition"><span class="layui-icon">&#x1006;</span></a>').data('input', this);
  556. $bt.attr('data-size', $in.data('size') || 0).attr('data-type', $in.data('type') || 'png,jpg,gif').find('span').on('click', function (event) {
  557. event.stopPropagation(), $bt.attr('style', ''), $in.val('');
  558. }), $in.on('change', function () {
  559. if (this.value) $bt.css('backgroundImage', 'url(' + encodeURI(this.value) + ')');
  560. }).after($bt).trigger('change');
  561. });
  562. };
  563. /*! 上传多张图片 */
  564. $.fn.uploadMultipleImage = function () {
  565. return this.each(function () {
  566. if ($(this).data('inited')) return true; else $(this).data('inited', true);
  567. var $in = $(this), $bt = $('<a data-file="mul" class="uploadimage"></a>'), imgs = this.value ? this.value.split('|') : []
  568. $in.after($bt.attr('data-size', $in.data('size') || 0).attr('data-type', $in.data('type') || 'png,jpg,gif').uploadFile(function (src) {
  569. imgs.push(src), $in.val(imgs.join('|')), showImageContainer([src]);
  570. })), (imgs.length > 0 && showImageContainer(imgs));
  571. function showImageContainer(srcs) {
  572. $(srcs).each(function (idx, src, $image) {
  573. $image = $('<div class="uploadimage uploadimagemtl transition"><div><a class="layui-icon">&#xe603;</a><a class="layui-icon">&#x1006;</a><a class="layui-icon">&#xe602;</a></div></div>');
  574. $image.attr('data-tips-image', encodeURI(src)).css('backgroundImage', 'url(' + encodeURI(src) + ')').on('click', 'a', function (event, index, prevs, $item) {
  575. event.stopPropagation(), $item = $(this).parent().parent(), index = $(this).index();
  576. if (index === 2 && $item.index() !== $bt.prevAll('div.uploadimage').length) $item.next().after($item);
  577. else if (index === 0 && $item.index() > 1) $item.prev().before($item); else if (index === 1) $item.remove();
  578. imgs = [], $bt.prevAll('.uploadimage').map(function () {
  579. imgs.push($(this).attr('data-tips-image'));
  580. });
  581. imgs.reverse(), $in.val(imgs.join('|'));
  582. }), $bt.before($image);
  583. });
  584. }
  585. });
  586. };
  587. /*! 标签输入插件 */
  588. $.fn.initTagInput = function () {
  589. return this.each(function () {
  590. var $this = $(this), tags = this.value ? this.value.split(',') : [];
  591. var $text = $('<textarea class="layui-input layui-input-inline layui-tag-input"></textarea>');
  592. var $tags = $('<div class="layui-tags"></div>').append($text);
  593. $this.parent().append($tags), $text.off('keydown blur'), (tags.length > 0 && showTags(tags));
  594. $text.on('keydown blur', function (event, value) {
  595. if (event.keyCode === 13 || event.type === 'blur') {
  596. event.preventDefault(), (value = $text.val().replace(/^\s*|\s*$/g, ''));
  597. if (tags.indexOf($(this).val()) > -1) return layer.msg('该标签已经存在!');
  598. if (value.length > 0) tags.push(value), $this.val(tags.join(',')), showTags([value]), this.focus(), $text.val('');
  599. }
  600. });
  601. function showTags(tagsArr) {
  602. $(tagsArr).each(function (idx, text, elem) {
  603. elem = $('<div class="layui-tag"></div>').html(text + '<i class="layui-icon">&#x1006;</i>');
  604. elem.on('click', 'i', function (tagText, tagIdx) {
  605. tagText = $(this).parent().text(), tagIdx = tags.indexOf(tagText);
  606. tags.splice(tagIdx, 1), $(this).parent().remove(), $this.val(tags.join(','));
  607. }), $tags.append(elem, $text);
  608. });
  609. }
  610. });
  611. };
  612. /*! 文本框插入内容 */
  613. $.fn.insertAtCursor = function (value) {
  614. return this.each(function () {
  615. this.focus();
  616. if (document.selection) {
  617. var selection = document.selection.createRange();
  618. (selection.text = value), selection.select(), selection.unselect();
  619. } else if (this.selectionStart || this.selectionStart === 0) {
  620. var spos = this.selectionStart, apos = this.selectionEnd || spos;
  621. this.value = this.value.substring(0, spos) + value + this.value.substring(apos, this.value.length);
  622. this.selectionEnd = this.selectionStart = spos + value.length;
  623. } else {
  624. this.value += value;
  625. }
  626. this.focus();
  627. });
  628. }
  629. /*! 组件 layui.table 封装 */
  630. $.fn.layTable = function (params) {
  631. return this.each(function (idx, elem) {
  632. // 动态初始化数据表
  633. this.id = this.id || 't' + Math.random().toString().replace('.', '');
  634. this.setAttribute('lay-filter', this.dataset.id = this.getAttribute('lay-filter') || this.id);
  635. // 插件初始化参数
  636. var opt = params || {}, data = opt.where || {}, sort = opt.initSort || opt.sort || {};
  637. opt.id = elem.id, opt.elem = elem, opt.url = params.url || elem.dataset.url || location.href;
  638. opt.page = params.page !== false ? (params.page || true) : false, opt.limit = params.limit || 20;
  639. opt.loading = params.loading === true, opt.autoSort = params.autoSort === true, opt.cols = params.cols || [[]];
  640. // 默认动态设置页数, 动态设置最大高度
  641. if (opt.page === true) opt.page = {curr: layui.sessionData('pages')[opt.id] || 1}
  642. if (opt.height === 'full') if ($(elem).parents('.iframe-pagination').size()) {
  643. $(elem).parents('.iframe-pagination').addClass('not-footer');
  644. opt.height = $(window).height() - $(elem).removeClass('layui-hide').offset().top - 20;
  645. } else {
  646. opt.height = $(window).height() - $(elem).removeClass('layui-hide').offset().top - 35;
  647. }
  648. // 动态计算最大页数
  649. opt.done = function () {
  650. layui.sessionData('pages', {key: elem.id, value: this.page.curr || 1}), (this.loading = true);
  651. this.elem.next().find('[data-load],[data-queue],[data-action],[data-iframe]').not('[data-table-id]').attr('data-table-id', elem.id);
  652. }, opt.parseData = function (res) {
  653. var maxPage = Math.ceil(res.count / this.limit), curPage = layui.sessionData('pages')[opt.id] || 1;
  654. if (curPage > maxPage && curPage > 1) this.elem.trigger('reload', {page: {curr: maxPage}});
  655. };
  656. // 实例并绑定的对象
  657. $(this).data('this', layui.table.render(bindData(opt)));
  658. // 绑定实例重载事件
  659. $(this).bind('reload', function (evt, opts) {
  660. opts = opts || {}, opts.loading = true;
  661. data = $.extend({}, data, opts.where || {});
  662. layui.table.reload(elem.id, bindData(opts || {}));
  663. }).bind('row sort tool edit radio toolbar checkbox rowDouble', function (evt, call) {
  664. layui.table.on(evt.type + '(' + elem.dataset.id + ')', call)
  665. }).bind('setFullHeight', function () {
  666. $(elem).trigger('reload', {height: $(window).height() - $(elem).next().offset().top - 35})
  667. }).trigger('sort', function (object) {
  668. (sort = object), $(elem).trigger('reload')
  669. });
  670. // 搜索表单关联对象
  671. var search = params.search || this.dataset.targetSearch;
  672. if (search) $body.find(search).map(function () {
  673. $(this).attr('data-table-id', elem.id);
  674. });
  675. // 绑定选择项关联对象
  676. var checked = params.checked || this.dataset.targetChecked;
  677. if (checked) $body.find(checked).map(function () {
  678. $(this).attr('data-table-id', elem.id);
  679. });
  680. // 生成初始化参数
  681. function bindData(opts) {
  682. data['output'] = 'layui.table';
  683. if (sort.field && sort.type) {
  684. data['_order_'] = sort.type, data['_field_'] = sort.field;
  685. opts.initSort = {type: sort.type.split(',')[0].split(' ')[0], field: sort.field.split(',')[0].split(' ')[0]};
  686. }
  687. return (opts['where'] = data), opts;
  688. }
  689. });
  690. }
  691. /*! 弹出图片层 */
  692. $.previewImage = function (src, area) {
  693. var img = new Image(), defer = $.Deferred(), loaded = $.msg.loading();
  694. img.style.background = '#FFF', img.referrerPolicy = 'no-referrer';
  695. img.style.height = 'auto', img.style.width = area || '100%', img.style.display = 'none';
  696. document.body.appendChild(img), img.onerror = function () {
  697. $.msg.close(loaded), defer.reject();
  698. }, img.onload = function () {
  699. layer.open({
  700. type: 1, title: false, shadeClose: true, content: $(img), success: function ($elem, idx) {
  701. $.msg.close(loaded), defer.notify($elem, idx);
  702. }, area: area || '480px', skin: 'layui-layer-nobg', closeBtn: 1, end: function () {
  703. document.body.removeChild(img), defer.resolve()
  704. }
  705. });
  706. };
  707. return (img.src = src), defer.resolve();
  708. };
  709. /*! 以手机模式显示内容 */
  710. $.previewPhonePage = function (href, title) {
  711. var template = '<div class="mobile-preview"><div class="mobile-header">{{d.title}}</div><div class="mobile-body"><iframe src="{{d.url}}"></iframe></div></div>';
  712. layer.style(layer.open({type: true, resize: false, scrollbar: false, area: ['320px', '600px'], title: false, closeBtn: true, shadeClose: false, skin: 'layui-layer-nobg', content: layui.laytpl(template).render({title: title || '公众号', url: href})}), {boxShadow: 'none'});
  713. };
  714. /*! 显示任务进度消息 */
  715. $.loadQueue = function (code, doScript, element) {
  716. var doAjax = true, doReload = false;
  717. layui.layer.open({
  718. type: 1, title: false, area: ['560px', '315px'], anim: 2, shadeClose: false, end: function () {
  719. doAjax = false;
  720. if (doReload && doScript) {
  721. if (element && element.dataset && element.dataset.tableId) {
  722. $('#' + element.dataset.tableId).trigger('reload');
  723. } else {
  724. $.form.reload();
  725. }
  726. }
  727. }, content: '' +
  728. '<div class="padding-30 padding-bottom-0" data-queue-load="' + code + '">' +
  729. ' <div class="layui-elip notselect nowrap" data-message-title></div>' +
  730. ' <div class="margin-top-15 layui-progress layui-progress-big" lay-showPercent="yes"><div class="layui-progress-bar transition" lay-percent="0.00%"></div></div>' +
  731. ' <div class="margin-top-15"><code class="layui-textarea layui-bg-black border-0" disabled style="resize:none;overflow:hidden;height:190px"></code></div>' +
  732. '</div>',
  733. success: function ($elem) {
  734. new function () {
  735. var that = this;
  736. this.$box = $elem.find('[data-queue-load=' + code + ']');
  737. if (doAjax === false || this.$box.length < 1) return false;
  738. this.$coder = this.$box.find('code'), this.$name = this.$box.find('[data-message-title]');
  739. this.$percent = this.$box.find('.layui-progress div'), this.SetCache = function (code, index, value) {
  740. var ckey = code + '_' + index, ctype = 'admin-queue-script';
  741. return value !== undefined ? layui.data(ctype, {key: ckey, value: value}) : layui.data(ctype)[ckey] || 0;
  742. }, this.SetState = function (status, message) {
  743. if (message.indexOf('javascript:') === -1) if (status === 1) {
  744. that.$name.html('<b class="color-text">' + message + '</b>').addClass('text-center');
  745. that.$percent.addClass('layui-bg-blue').removeClass('layui-bg-green layui-bg-red');
  746. } else if (status === 2) {
  747. if (message.indexOf('>>>') > -1) {
  748. that.$name.html('<b class="color-blue">' + message + '</b>').addClass('text-center');
  749. } else {
  750. that.$name.html('<b class="color-blue">正在处理:</b>' + message).removeClass('text-center');
  751. }
  752. that.$percent.addClass('layui-bg-blue').removeClass('layui-bg-green layui-bg-red');
  753. } else if (status === 3) {
  754. doReload = true;
  755. that.$name.html('<b class="color-green">' + message + '</b>').addClass('text-center');
  756. that.$percent.addClass('layui-bg-green').removeClass('layui-bg-blue layui-bg-red');
  757. } else if (status === 4) {
  758. that.$name.html('<b class="color-red">' + message + '</b>').addClass('text-center');
  759. that.$percent.addClass('layui-bg-red').removeClass('layui-bg-blue layui-bg-green');
  760. }
  761. }, (this.LoadProgress = function () {
  762. if (doAjax === false || that.$box.length < 1) return false;
  763. $.form.load(tapiRoot + '/api.queue/progress', {code: code}, 'post', function (ret) {
  764. if (ret.code) {
  765. var lines = [];
  766. for (var idx in ret.data.history) {
  767. var line = ret.data.history[idx], percent = '[ ' + line.progress + '% ] ';
  768. if (line.message.indexOf('javascript:') === -1) lines.push(line.message.indexOf('>>>') > -1 ? line.message : percent + line.message);
  769. else if (!that.SetCache(code, idx) && doScript !== false) that.SetCache(code, idx, 1), location.href = line.message;
  770. }
  771. if (ret.data.status > 0) {
  772. that.SetState(parseInt(ret.data.status), ret.data.message);
  773. that.$percent.attr('lay-percent', (parseFloat(ret.data.progress || '0.00').toFixed(2)) + '%'), layui.element.render();
  774. that.$coder.html('<p class="layui-elip">' + lines.join('</p><p class="layui-elip">') + '</p>').animate({scrollTop: that.$coder[0].scrollHeight + 'px'}, 200);
  775. return parseInt(ret.data.status) === 3 || parseInt(ret.data.status) === 4 || setTimeout(that.LoadProgress, Math.floor(Math.random() * 200)), false;
  776. } else return setTimeout(that.LoadProgress, Math.floor(Math.random() * 500) + 200), false;
  777. }
  778. }, false);
  779. })();
  780. };
  781. }
  782. });
  783. };
  784. /*! 注册 data-search 表单搜索行为 */
  785. onEvent('submit', 'form.form-search', function () {
  786. var tableId = this.dataset.tableId;
  787. if (tableId) return $('table#' + tableId).trigger('reload', {
  788. page: {curr: 1}, where: $(this).formToJson()
  789. });
  790. var url = $(this).attr('action').replace(/&?page=\d+/g, '');
  791. if ((this.method || 'get').toLowerCase() === 'get') {
  792. var split = url.indexOf('?') > -1 ? '&' : '?';
  793. var stype = location.href.indexOf('spm=') > -1 ? '#' : '';
  794. return location.href = stype + $.menu.parseUri(url + split + $(this).serialize());
  795. }
  796. return $.form.load(url, this, 'post');
  797. });
  798. /*! 注册 data-file 事件行为 */
  799. onEvent('click', '[data-file]', function () {
  800. if ($(this).data('inited') !== true) (function (that) {
  801. that.uploadFile(undefined, function () {
  802. that.trigger('upload.start');
  803. });
  804. })($(this));
  805. });
  806. /*! 注册 data-load 事件行为 */
  807. onEvent('click', '[data-load]', function () {
  808. var emap = this.dataset, data = {};
  809. if (this.dataset.rule && (applyRuleValue(this, data)) === false) return false;
  810. (function (confirm, callable) {
  811. confirm ? $.msg.confirm(confirm, callable) : callable();
  812. })(emap.confirm, function () {
  813. var call = !emap.tableId ? false : function (ret) {
  814. if (ret.code > 0) return $.msg.success(ret.info, 3, function () {
  815. $('#' + emap.tableId).trigger('reload');
  816. }), false;
  817. }
  818. $.form.load(emap.load, data, 'get', call, true, emap.tips, emap.time);
  819. });
  820. });
  821. /*! 注册 data-reload 事件行为 */
  822. onEvent('click', '[data-reload]', function () {
  823. this.dataset.tableId ? $('#' + this.dataset.tableId).trigger('reload') : $.form.reload();
  824. });
  825. /*! 注册 data-dbclick 事件行为 */
  826. onEvent('dblclick', '[data-dbclick]', function () {
  827. $(this).find(this.dataset.dbclick || '[data-dbclick]').trigger('click');
  828. });
  829. /*! 注册 data-check 事件行为 */
  830. onEvent('click', '[data-check-target]', function () {
  831. var target = this;
  832. $(this.dataset.checkTarget).map(function () {
  833. (this.checked = !!target.checked), $(this).trigger('change');
  834. });
  835. });
  836. /*! 表单元素失去焦点时数字 */
  837. onEvent('blur', '[data-blur-number]', function () {
  838. var emap = this.dataset, min = emap.valueMin, max = emap.valueMax;
  839. var value = parseFloat(this.value) || 0, fiexd = parseInt(emap.blurNumber || 0);
  840. if (typeof min !== 'undefined' && value < min) value = min;
  841. if (typeof max !== 'undefined' && value > max) value = max;
  842. this.value = parseFloat(value).toFixed(fiexd);
  843. });
  844. /*! 表单元素失焦时提交 */
  845. onEvent('blur', '[data-action-blur],[data-blur-action]', function () {
  846. var that = $(this), emap = this.dataset, data = {'_token_': emap.token || emap.csrf || '--'};
  847. var attrs = (emap.value || '').replace('{value}', that.val()).split(';');
  848. for (var i in attrs) data[attrs[i].split('#')[0]] = attrs[i].split('#')[1];
  849. (function (confirm, callable) {
  850. confirm ? $.msg.confirm(confirm, callable) : callable();
  851. })(emap.confirm, function () {
  852. $.form.load(emap.actionBlur || emap.blurAction, data, emap.method || 'post', function (ret) {
  853. return that.css('border', (ret && ret.code) ? '1px solid #e6e6e6' : '1px solid red'), false;
  854. }, emap.loading !== 'false', emap.loading, emap.time)
  855. });
  856. });
  857. /*! 注册 data-href 事件行为 */
  858. onEvent('click', '[data-href]', function () {
  859. if (this.dataset.href && this.dataset.href.indexOf('#') !== 0) {
  860. location.href = this.dataset.href;
  861. }
  862. });
  863. /*! 注册 data-open 事件行为 */
  864. onEvent('click', '[data-open]', function () {
  865. if (this.dataset.open.match(/^https?:/)) {
  866. location.href = this.dataset.open;
  867. } else {
  868. $.form.href(this.dataset.open, this);
  869. }
  870. });
  871. /*! 注册 data-action 事件行为 */
  872. onEvent('click', '[data-action]', function () {
  873. var emap = this.dataset, data = {'_token_': emap.token || emap.csrf || '--'};
  874. var load = emap.loading !== 'false', tips = typeof load === 'string' ? load : undefined;
  875. if ((applyRuleValue(this, data)) === false) return false;
  876. (function (confirm, callable) {
  877. confirm ? $.msg.confirm(confirm, callable) : callable();
  878. })(emap.confirm, function () {
  879. var call = !emap.tableId ? false : function (ret) {
  880. if (ret.code > 0) return $.msg.success(ret.info, 3, function () {
  881. $('#' + emap.tableId).trigger('reload');
  882. }), false;
  883. }
  884. $.form.load(emap.action, data, emap.method || 'post', call, load, tips, emap.time)
  885. });
  886. });
  887. /*! 注册 data-modal 事件行为 */
  888. onEvent('click', '[data-modal]', function () {
  889. var emap = this.dataset, data = {open_type: 'modal'}, un = undefined;
  890. if (emap.rule && (applyRuleValue(this, data)) === false) return false;
  891. return $.form.modal(emap.modal, data, emap.title || this.innerText || '编辑', un, un, un, emap.area || emap.width || '800px', emap.offset || 'auto');
  892. });
  893. /*! 注册 data-iframe 事件行为 */
  894. onEvent('click', '[data-iframe]', function () {
  895. var emap = this.dataset, data = {open_type: 'iframe'};
  896. if (emap.rule && (applyRuleValue(this, data)) === false) return false;
  897. var name = emap.title || this.innerText || 'IFRAME 窗口';
  898. var area = emap.area || [emap.width || '800px', emap.height || '580px'];
  899. var frame = emap.iframe + (emap.iframe.indexOf('?') > -1 ? '&' : '?') + $.param(data);
  900. $(this).attr('data-index', $.form.iframe(frame, name, area, emap.offset || 'auto', emap.tableId ? function () {
  901. typeof emap.refresh !== 'undefined' && $('#' + emap.tableId).trigger('reload');
  902. } : function () {
  903. typeof emap.refresh !== 'undefined' && $.form.reload();
  904. }));
  905. });
  906. /*! 注册 data-icon 事件行为 */
  907. onEvent('click', '[data-icon]', function () {
  908. var location = tapiRoot + '/api.plugs/icon', field = this.dataset.icon || this.dataset.field || 'icon';
  909. $.form.iframe(location + (location.indexOf('?') > -1 ? '&' : '?') + 'field=' + field, '图标选择', ['900px', '700px']);
  910. });
  911. /*! 注册 data-copy 事件行为 */
  912. onEvent('click', '[data-copy]', function () {
  913. (function (content, $textarea) {
  914. $body.append($textarea.val(content)), $textarea.select();
  915. document.execCommand('Copy') ? $.msg.tips('已复制到剪贴板!') : $.msg.tips('请使用鼠标操作复制!');
  916. $textarea.remove(), $textarea.unselect();
  917. })(this.dataset.copy, $('<textarea style="position:fixed;top:-500px"></textarea>'));
  918. });
  919. /*! 异步任务状态监听与展示 */
  920. onEvent('click', '[data-queue]', function () {
  921. var that = this;
  922. (function (confirm, callable) {
  923. confirm ? $.msg.confirm(confirm, callable) : callable();
  924. })(this.dataset.confirm, function () {
  925. $.form.load(that.dataset.queue, {}, 'post', function (ret) {
  926. if (typeof ret.data === 'string' && ret.data.indexOf('Q') === 0) {
  927. return $.loadQueue(ret.data, true, that), false;
  928. }
  929. });
  930. });
  931. });
  932. /*! 注册 data-tips-text 事件行为 */
  933. onEvent('mouseenter', '[data-tips-text]', function () {
  934. var opts = {tips: [$(this).attr('data-tips-type') || 3, '#78BA32'], time: 0};
  935. var layidx = layer.tips($(this).attr('data-tips-text') || this.innerText, this, opts);
  936. $(this).off('mouseleave').on('mouseleave', function () {
  937. setTimeout("layui.layer.close('" + layidx + "')", 100);
  938. });
  939. });
  940. /*! 注册 data-tips-hover 事件行为 */
  941. onEvent('mouseenter', '[data-tips-image][data-tips-hover]', function () {
  942. var img = new Image(), ele = $(this);
  943. if ((img.src = this.dataset.tipsImage || this.dataset.lazySrc || this.src)) {
  944. img.layopt = {time: 0, skin: 'layui-layer-image', anim: 5, isOutAnim: false, scrollbar: false};
  945. img.referrerPolicy = 'no-referrer', img.style.maxWidth = '260px', img.style.maxHeight = '260px';
  946. ele.data('layidx', layer.tips(img.outerHTML, this, img.layopt)).off('mouseleave').on('mouseleave', function () {
  947. layui.layer.close(ele.data('layidx'));
  948. });
  949. }
  950. });
  951. /*! 注册 data-tips-image 事件行为 */
  952. onEvent('click', '[data-tips-image]', function () {
  953. $.previewImage(this.dataset.tipsImage || this.dataset.lazySrc || this.src, this.dataset.with);
  954. });
  955. /*! 注册 data-phone-view 事件行为 */
  956. onEvent('click', '[data-phone-view]', function () {
  957. $.previewPhonePage(this.dataset.phoneView || this.href);
  958. });
  959. /*! 表单编辑返回操作 */
  960. onEvent('click', '[data-history-back]', function () {
  961. $.msg.confirm(this.dataset.historyBack || '确定要返回吗?', function () {
  962. history.back();
  963. })
  964. });
  965. /*! 延时关闭加载动画 */
  966. window.addEventListener('load', function () {
  967. setTimeout("$('body>.think-page-loader').fadeOut()", 200);
  968. }, true);
  969. /*! 图片加载异常处理 */
  970. document.addEventListener('error', function (event) {
  971. var elem = event.target;
  972. if (elem.nodeName === 'IMG') {
  973. elem.src = baseRoot + 'theme/img/404_icon.png';
  974. }
  975. }, true);
  976. /*! 系统菜单表单页面初始化 */
  977. $.menu.listen(), $.vali.listen(), $.form.reInit($body);
  978. });