admin.js 46 KB

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