admin.js 50 KB

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