admin.js 47 KB

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