common.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. var ns = window.ns_url;
  2. /**
  3. * 解析URL
  4. * @param {string} url 被解析的URL
  5. * @return {object} 解析后的数据
  6. */
  7. ns.parse_url = function (url) {
  8. var parse = url.match(/^(?:([0-9a-zA-Z]+):\/\/)?([\w-]+(?:\.[\w-]+)+)?(?::(\d+))?([\w-\/]+)?(?:\?((?:\w+=[^#&=\/]*)?(?:&\w+=[^#&=\/]*)*))?(?:#([\w-]+))?$/i);
  9. parse || $.error("url格式不正确!");
  10. return {
  11. "scheme": parse[1],
  12. "host": parse[2],
  13. "port": parse[3],
  14. "path": parse[4],
  15. "query": parse[5],
  16. "fragment": parse[6]
  17. };
  18. };
  19. ns.parse_str = function (str) {
  20. var value = str.split("&"), vars = {}, param;
  21. for (var i = 0; i < value.length; i++) {
  22. param = value[i].split("=");
  23. vars[param[0]] = param[1];
  24. }
  25. return vars;
  26. };
  27. ns.parse_name = function (name, type) {
  28. if (type) {
  29. /* 下划线转驼峰 */
  30. name = name.replace(/_([a-z])/g, function ($0, $1) {
  31. return $1.toUpperCase();
  32. });
  33. /* 首字母大写 */
  34. name = name.replace(/[a-z]/, function ($0) {
  35. return $0.toUpperCase();
  36. });
  37. } else {
  38. /* 大写字母转小写 */
  39. name = name.replace(/[A-Z]/g, function ($0) {
  40. return "_" + $0.toLowerCase();
  41. });
  42. /* 去掉首字符的下划线 */
  43. if (0 === name.indexOf("_")) {
  44. name = name.substr(1);
  45. }
  46. }
  47. return name;
  48. };
  49. //scheme://host:port/path?query#fragment
  50. ns.url = function (url, vars, suffix) {
  51. if (url.indexOf('http://') != -1 || url.indexOf('https://') != -1) {
  52. return url;
  53. }
  54. var info = this.parse_url(url), path = [], param = {}, reg;
  55. /* 验证info */
  56. info.path || alert("url格式错误!");
  57. url = info.path;
  58. /* 解析URL */
  59. path = url.split("/");
  60. path = [path.pop(), path.pop(), path.pop()].reverse();
  61. path[1] = path[1] || this.route[1];
  62. path[0] = path[0] || this.route[0];
  63. param[this.route[1]] = path[0];
  64. param[this.route[2]] = path[1];
  65. param[this.route[3]] = path[2].toLowerCase();
  66. url = param[this.route[1]] + '/' + param[this.route[2]] + '/' + param[this.route[3]];
  67. /* 解析参数 */
  68. if (typeof vars === "string") {
  69. vars = this.parse_str(vars);
  70. } else if (!$.isPlainObject(vars)) {
  71. vars = {};
  72. }
  73. /* 添加伪静态后缀 */
  74. if (false !== suffix) {
  75. suffix = suffix || 'html';
  76. if (suffix) {
  77. url += "." + suffix;
  78. }
  79. }
  80. /* 解析URL自带的参数 */
  81. info.query && $.extend(vars, this.parse_str(info.query));
  82. var addon = '';
  83. if (info.scheme != '' && info.scheme != undefined) {
  84. addon = info.scheme + '/';
  85. }
  86. url = addon + url;
  87. if (vars) {
  88. var param_str = $.param(vars);
  89. if ('' !== param_str) {
  90. url += ((this.baseUrl + url).indexOf('?') !== -1 ? '&' : '?') + param_str;
  91. }
  92. }
  93. // url = url.replace("shop", this.appModule);
  94. url = this.baseUrl + url;
  95. return url;
  96. };
  97. /**
  98. * 验证手机号
  99. * @param {string} mobile 被验证的mobile
  100. * @return {object} 验证后的结果
  101. **/
  102. ns.parse_mobile = function (mobile) {
  103. // var parse = /^1(3|4|5|6|7|8|9)\d{9}$/.test(mobile);
  104. var parse = /^\d{11}$/.test(mobile);
  105. return parse;
  106. };
  107. /**
  108. * 验证固定电话
  109. * @param {string} phone 被验证的mobile
  110. * @return {object} 验证后的结果
  111. **/
  112. ns.parse_telephone = function (phone) {
  113. var parse = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(phone);
  114. return parse;
  115. };
  116. /**
  117. * 处理图片路径
  118. * path 路径地址
  119. * type 类型 big、mid、small
  120. */
  121. ns.img = function (path, type = '') {
  122. if (path.indexOf(",") != -1) {
  123. path = path.split(',')[0];
  124. }
  125. var start = path.lastIndexOf('.');
  126. type = type ? '_' + type.toUpperCase() : '';
  127. var suffix = path.substring(start);
  128. path = path.substring(0, start);
  129. var first = path.split("/");
  130. path += type + suffix;
  131. if (path.indexOf("http://") == -1 && path.indexOf("https://") == -1) {
  132. var base_url = this.baseUrl.replace('/?s=', '');
  133. var base_url = base_url.replace('/index.php', '');
  134. if (isNaN(first[0])) {
  135. var true_path = base_url + path;
  136. } else {
  137. var true_path = base_url + 'attachment/' + path;
  138. }
  139. } else {
  140. var true_path = path;
  141. }
  142. return true_path;
  143. };
  144. /**
  145. * 时间戳转时间
  146. *
  147. */
  148. var default_time_format = 'YYYY-MM-DD h:m:s';
  149. ns.time_to_date = function (timeStamp, time_format = '') {
  150. time_format = time_format == '' ? default_time_format : time_format;
  151. if (timeStamp > 0) {
  152. var date = new Date();
  153. date.setTime(timeStamp * 1000);
  154. var y = date.getFullYear();
  155. var m = date.getMonth() + 1;
  156. m = m < 10 ? ('0' + m) : m;
  157. var d = date.getDate();
  158. d = d < 10 ? ('0' + d) : d;
  159. var h = date.getHours();
  160. h = h < 10 ? ('0' + h) : h;
  161. var minute = date.getMinutes();
  162. var second = date.getSeconds();
  163. minute = minute < 10 ? ('0' + minute) : minute;
  164. second = second < 10 ? ('0' + second) : second;
  165. var time = '';
  166. time += time_format.indexOf('Y') > -1 ? y : '';
  167. time += time_format.indexOf('M') > -1 ? '-' + m : '';
  168. time += time_format.indexOf('D') > -1 ? '-' + d : '';
  169. time += time_format.indexOf('h') > -1 ? ' ' + h : '';
  170. time += time_format.indexOf('m') > -1 ? ':' + minute : '';
  171. time += time_format.indexOf('s') > -1 ? ':' + second : '';
  172. return time;
  173. } else {
  174. return "";
  175. }
  176. };
  177. /**
  178. * 时间戳转时间(毫秒)
  179. */
  180. ns.millisecond_to_date = function (timeStamp) {
  181. if (timeStamp > 0) {
  182. var date = new Date();
  183. date.setTime(timeStamp);
  184. var y = date.getFullYear();
  185. var m = date.getMonth() + 1;
  186. m = m < 10 ? ('0' + m) : m;
  187. var d = date.getDate();
  188. d = d < 10 ? ('0' + d) : d;
  189. var h = date.getHours();
  190. h = h < 10 ? ('0' + h) : h;
  191. var minute = date.getMinutes();
  192. var second = date.getSeconds();
  193. minute = minute < 10 ? ('0' + minute) : minute;
  194. second = second < 10 ? ('0' + second) : second;
  195. return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  196. } else {
  197. return "";
  198. }
  199. };
  200. /**
  201. * 日期 转换为 Unix时间戳
  202. * @param <string> 2014-01-01 20:20:20 日期格式
  203. * @return <int> unix时间戳(秒)
  204. */
  205. ns.date_to_time = function (string) {
  206. var f = string.split(' ', 2);
  207. var d = (f[0] ? f[0] : '').split('-', 3);
  208. var t = (f[1] ? f[1] : '').split(':', 3);
  209. return (new Date(
  210. parseInt(d[0], 10) || null,
  211. (parseInt(d[1], 10) || 1) - 1,
  212. parseInt(d[2], 10) || null,
  213. parseInt(t[0], 10) || null,
  214. parseInt(t[1], 10) || null,
  215. parseInt(t[2], 10) || null
  216. )).getTime() / 1000;
  217. };
  218. /**
  219. * url 反转义
  220. * @param url
  221. */
  222. ns.urlReplace = function (url) {
  223. url = decodeURIComponent(url);
  224. var new_url = url.replace(/%2B/g, "+");//"+"转义
  225. new_url = new_url.replace(/%26/g, "&");//"&"
  226. new_url = new_url.replace(/%23/g, "#");//"#"
  227. new_url = new_url.replace(/%20/g, " ");//" "
  228. new_url = new_url.replace(/%3F/g, "?");//"#"
  229. new_url = new_url.replace(/%25/g, "%");//"#"
  230. new_url = new_url.replace(/&3D/g, "=");//"#"
  231. new_url = new_url.replace(/%2F/g, "/");//"#"
  232. return new_url;
  233. };
  234. /**
  235. * 需要定义APP_KEY,API_URL
  236. * method 插件名.控制器.方法
  237. * data json对象
  238. * async 是否异步,默认true 异步,false 同步
  239. */
  240. ns.api = function (method, param, callback, async) {
  241. // async true为异步请求 false为同步请求
  242. async = async != undefined ? async : true;
  243. param = param || {};
  244. param.port = 'platform';
  245. $.ajax({
  246. type: 'get',
  247. url: ns_url.baseUrl + '' + method + '?site_id=' + ns_url.siteId,
  248. data: param,
  249. dataType: "JSON",
  250. async: async,
  251. success: function (res) {
  252. if (callback) callback(eval("(" + res + ")"));
  253. }
  254. });
  255. };
  256. /**
  257. * url 反转义
  258. * @param url
  259. */
  260. ns.append_url_params = function (url, params) {
  261. if (params != undefined) {
  262. var url_params = '';
  263. for (var k in params) {
  264. url_params += "&" + k + "=" + params[k];
  265. }
  266. url += url_params;
  267. }
  268. return url;
  269. };
  270. /**
  271. * 生成随机不重复字符串
  272. * @param len
  273. * @returns {string}
  274. */
  275. ns.gen_non_duplicate = function (len) {
  276. return Number(Math.random().toString().substr(3, len) + Date.now()).toString(36);
  277. };
  278. /**
  279. * 获取分页参数
  280. * @param param 参数
  281. * @returns {{layout: string[]}}
  282. */
  283. ns.get_page_param = function (param) {
  284. var obj = {
  285. layout: ['count', 'limit', 'prev', 'page', 'next']
  286. };
  287. if (param != undefined) {
  288. if (param.limit != undefined) {
  289. obj.limit = param.limit;
  290. }
  291. }
  292. return obj;
  293. };
  294. /**
  295. * 弹出框,暂时没有使用
  296. * @param options 参数,参考layui:https://www.layui.com/doc/modules/layer.html
  297. */
  298. ns.open = function (options) {
  299. if (!options) options = {};
  300. options.type = options.type || 1;
  301. //宽高,小、中、大
  302. // options.size
  303. options.area = options.area || ['500px'];
  304. layer.open(options);
  305. };
  306. /**
  307. * 上传
  308. * @param id
  309. * @param method
  310. * @param param
  311. * @param callback
  312. * @param async
  313. */
  314. ns.upload_api = function (id, method, param, callback, async) {
  315. // async true为异步请求 false为同步请求
  316. async = async != undefined ? async : true;
  317. param.app_key = APP_KEY;
  318. var file = document.getElementById(id).files[0];
  319. var formData = new FormData();
  320. formData.append("file", file);
  321. formData.append("method", method);
  322. formData.append("param", JSON.stringify(param));
  323. $.ajax({
  324. url: API_URL + '?s=/api/index/get/method/' + method + '/version/1.0',
  325. type: "post",
  326. data: formData,
  327. dataType: "JSON",
  328. contentType: false,
  329. processData: false,
  330. async: async,
  331. mimeType: "multipart/form-data",
  332. success: function (res) {
  333. if (callback) callback(eval("(" + res + ")"));
  334. },
  335. // error: function (data) {
  336. // console.log(data);
  337. // }
  338. });
  339. };
  340. /**
  341. * 复制
  342. * @param dom
  343. * @param callback
  344. */
  345. ns.copy = function JScopy(dom, callback) {
  346. var url = document.getElementById(dom);
  347. var o = {
  348. url: url.value
  349. };
  350. var inputText = document.createElement('input');
  351. inputText.value = o.url;
  352. document.body.appendChild(inputText);
  353. inputText.select();
  354. document.execCommand("Copy");
  355. if (callback) callback.call(this, o);
  356. inputText.type = 'hidden';
  357. layer.msg('复制成功');
  358. };
  359. ns.int_to_float = function (val) {
  360. return new Number(val).toFixed(2);
  361. };
  362. var show_link_box_flag = true;
  363. /**
  364. * 弹出框-->选择链接
  365. * @param link
  366. * @param callback
  367. */
  368. ns.select_link = function (link, callback) {
  369. if (show_link_box_flag) {
  370. show_link_box_flag = false;
  371. $.post(ns.url("shop/diy/link"), {
  372. link: JSON.stringify(link),
  373. site_id:ns_url.siteId,
  374. app_module: ns_url.appModule,
  375. }, function (str) {
  376. window.linkIndex = layer.open({
  377. type: 1,
  378. title: "选择链接",
  379. content: str,
  380. btn: [],
  381. area: ['850px'], //宽高
  382. maxWidth: 1920,
  383. cancel: function (index, layero) {
  384. show_link_box_flag = true;
  385. },
  386. end: function () {
  387. if (window.linkData) {
  388. if (callback) callback(window.linkData);
  389. delete window.linkData;// 清空本次选择
  390. }
  391. show_link_box_flag = true;
  392. }
  393. });
  394. });
  395. }
  396. };
  397. /**
  398. * 打开iframe弹框
  399. * @param param
  400. */
  401. ns.open_iframe = function (param) {
  402. layui.use(['layer'], function () {
  403. var url = param.url || '';
  404. var success = param.success || null;
  405. var title = param.title || '弹框';
  406. var area = param.area || ['80%', '80%'];
  407. //iframe层-父子操作
  408. layer.open({
  409. title: title,
  410. type: 2,
  411. area: area,
  412. fixed: false, //不固定
  413. btn: ['保存', '返回'],
  414. content: url,
  415. yes: function (index, layero) {
  416. var iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象,执行iframe页的方法:
  417. iframeWin['getIframeRes'](function (obj) {
  418. if (typeof success == "string") {
  419. try {
  420. eval(success + '(obj)');
  421. layer.close(index);
  422. } catch (e) {
  423. console.error('回调函数' + success + '未定义');
  424. }
  425. } else if (typeof success == "function") {
  426. success(obj);
  427. layer.close(index);
  428. }
  429. });
  430. }
  431. });
  432. });
  433. }
  434. ns.compare = function (property) {
  435. return function (a, b) {
  436. var value1 = a[property];
  437. var value2 = b[property];
  438. return value1 - value2;
  439. }
  440. };
  441. //存储单元单位转换
  442. ns.sizeformat = function (limit) {
  443. if (limit == null || limit == "") {
  444. return "0KB"
  445. }
  446. var index = 0;
  447. var limit = limit.toUpperCase();//转换为小写
  448. if (limit.indexOf('B') == -1) { //如果无单位,加单位递归转换
  449. limit = limit + "B";
  450. //unitConver(limit);
  451. }
  452. var reCat = /[0-9]*[A-Z]B/;
  453. if (!reCat.test(limit) && limit.indexOf('B') != -1) { //如果单位是b,转换为kb加单位递归
  454. limit = limit.substring(0, limit.indexOf('B')); //去除单位,转换为数字格式
  455. limit = (limit / 1024) + 'KB'; //换算舍入加单位
  456. //unitConver(limit);
  457. }
  458. var array = new Array('KB', 'MB', 'GB', 'TB', 'PT');
  459. for (var i = 0; i < array.length; i++) { //记录所在的位置
  460. if (limit.indexOf(array[i]) != -1) {
  461. index = i;
  462. break;
  463. }
  464. }
  465. var limit = parseFloat(limit.substring(0, (limit.length - 2))); //得到纯数字
  466. while (limit >= 1024) {//数字部分1到1024之间
  467. limit /= 1024;
  468. index += 1;
  469. }
  470. limit = limit.toFixed(2) + array[index];
  471. return limit;
  472. };
  473. /**
  474. * 对象深度拷贝
  475. * @param options
  476. * @constructor
  477. */
  478. ns.deepclone = function (obj) {
  479. const isObject = function (obj) {
  480. return typeof obj == 'object';
  481. }
  482. if (!isObject(obj)) {
  483. throw new Error('obj 不是一个对象!')
  484. }
  485. //判断传进来的是对象还是数组
  486. let isArray = Array.isArray(obj)
  487. let cloneObj = isArray ? [] : {}
  488. //通过for...in来拷贝
  489. for (let key in obj) {
  490. cloneObj[key] = isObject(obj[key]) ? ns.deepclone(obj[key]) : obj[key]
  491. }
  492. return cloneObj
  493. }
  494. /**
  495. * 检测输入
  496. * @param dom
  497. * @param type
  498. */
  499. ns.checkInput = function (dom) {
  500. let new_val = $(dom).val();
  501. let reg = /^(0|[1-9][0-9]*)(.\d{0,2})?$/;
  502. let old_val = $(dom).attr('data-value');
  503. if (new_val === '' || reg.test(new_val)) {
  504. $(dom).attr('data-value', new_val);
  505. } else {
  506. $(dom).val(old_val);
  507. }
  508. }
  509. /**
  510. * 数据表格
  511. * layui官方文档:https://www.layui.com/doc/modules/table.html
  512. * @param options
  513. * @constructor
  514. */
  515. function Table(options) {
  516. if (!options) return;
  517. var _self = this;
  518. var fields = [];
  519. for (var i = 0; i < options.cols[0].length; i++) {
  520. if (options.cols[0][i].sort == true) {
  521. fields.push(options.cols[0][i].field);
  522. }
  523. }
  524. options.parseData = options.parseData || function (data) {
  525. $.each(data.data.list, function (index, item) {
  526. $.each(item, function (key, value) {
  527. if ($.inArray(key, fields) >= 0) {
  528. data.data.list[index][key] = Number(value);
  529. }
  530. });
  531. });
  532. return {
  533. "code": data.code,
  534. "msg": data.message,
  535. "count": data.data.count,
  536. "data": data.data.list
  537. };
  538. };
  539. options.request = options.request || {
  540. limitName: 'page_size' //每页数据量的参数名,默认:limit
  541. };
  542. var post_url = options.url || 0;
  543. var post_where = options.where;
  544. var domain = window.location.href + '/s' + (window.ns_url.siteid ? window.ns_url.siteid : 0)+post_url + JSON.stringify(post_where);
  545. if (options.page == undefined) {
  546. options.page = {
  547. layout: ['count', 'limit', 'prev', 'page', 'next'],
  548. limit: $.cookie('pageSize' + domain) || 10,
  549. curr: $.cookie('currPage' + domain) || 1
  550. };
  551. }
  552. options.defaultToolbar = options.defaultToolbar || [];//'filter', 'print', 'exports'
  553. options.toolbar = options.toolbar || "";//头工具栏事件
  554. options.skin = options.skin || 'line';
  555. options.size = options.size || 'lg';
  556. options.async = (options.async != undefined) ? options.async : true;
  557. options.done = function (res, curr, count) {
  558. //加载图片放大
  559. loadImgMagnify();
  560. $.cookie('currPage' + domain, curr, {path: window.location.pathname});
  561. $.cookie('pageSize' + domain, $('.layui-laypage-limits select[lay-ignore]').val(), {path: window.location.pathname});
  562. if (options.callback) options.callback(res, curr, count);
  563. };
  564. layui.use('table', function () {
  565. _self._table = layui.table;
  566. _self._table.render(options);
  567. });
  568. this.filter = options.filter || options.elem.replace(/#/g, "");
  569. this.elem = options.elem;
  570. //获取当前选中的数据
  571. this.checkStatus = function () {
  572. return this._table.checkStatus(_self.elem.replace(/#/g, ""));
  573. };
  574. }
  575. /**
  576. * 监听头工具栏事件
  577. * @param callback 回调
  578. */
  579. Table.prototype.toolbar = function (callback) {
  580. var _self = this;
  581. var interval = setInterval(function () {
  582. if (_self._table) {
  583. _self._table.on('toolbar(' + _self.filter + ')', function (obj) {
  584. var checkStatus = _self._table.checkStatus(obj.config.id);
  585. obj.data = checkStatus.data;
  586. obj.isAll = checkStatus.isAll;
  587. if (callback) callback.call(this, obj);
  588. });
  589. clearInterval(interval);
  590. }
  591. }, 50);
  592. };
  593. /**
  594. * 监听底部工具栏事件
  595. * @param callback 回调
  596. */
  597. Table.prototype.bottomToolbar = function (callback) {
  598. var _self = this;
  599. var interval = setInterval(function () {
  600. if (_self._table) {
  601. _self._table.on('bottomToolbar(' + _self.filter + ')', function (obj) {
  602. var checkStatus = _self._table.checkStatus(obj.config.id);
  603. obj.data = checkStatus.data;
  604. obj.isAll = checkStatus.isAll;
  605. if (callback) callback.call(this, obj);
  606. });
  607. clearInterval(interval);
  608. }
  609. }, 50);
  610. };
  611. /**
  612. * 绑定layui的on事件
  613. * @param name
  614. * @param callback
  615. */
  616. Table.prototype.on = function (name, callback) {
  617. var _self = this;
  618. var interval = setInterval(function () {
  619. if (_self._table) {
  620. _self._table.on(name + '(' + _self.filter + ')', function (obj) {
  621. if (callback) callback.call(this, obj);
  622. });
  623. clearInterval(interval);
  624. }
  625. }, 50);
  626. };
  627. /**
  628. * 表格重绘事件
  629. * @param {Object} callback
  630. */
  631. Table.prototype.resize = function (callback) {
  632. var _self = this;
  633. if (_self._table) {
  634. _self._table.resize(_self.filter);
  635. }
  636. };
  637. /**
  638. * //监听行工具事件
  639. * @param callback 回调
  640. */
  641. Table.prototype.tool = function (callback) {
  642. var _self = this;
  643. var interval = setInterval(function () {
  644. if (_self._table) {
  645. _self._table.on('tool(' + _self.filter + ')', function (obj) {
  646. if (callback) callback.call(this, obj);
  647. });
  648. clearInterval(interval);
  649. }
  650. }, 50);
  651. };
  652. /**
  653. * 刷新数据
  654. * @param options 参数,参考layui数据表格参数
  655. * @param callback 回调
  656. */
  657. Table.prototype.reload = function (options, callback) {
  658. var page = 1;
  659. if (options && options.page) {
  660. page = options.page.curr || 1;
  661. }
  662. options = options || {
  663. page: {
  664. curr: page
  665. }
  666. };
  667. var _self = this;
  668. var interval = setInterval(function () {
  669. if (_self._table) {
  670. _self._table.reload(_self.elem.replace(/#/g, ""), options);
  671. clearInterval(interval);
  672. }
  673. }, 50);
  674. if (callback) setTimeout(function () {
  675. callback()
  676. }, 500)
  677. };
  678. var layedit;
  679. /**
  680. * 富文本编辑器
  681. * https://www.layui.com/v1/doc/modules/layedit.html
  682. * @param id
  683. * @param options 参数,参考layui
  684. * @param callback 监听输入回调
  685. * @constructor
  686. */
  687. function Editor(id, options, callback) {
  688. options = options || {};
  689. this.id = id;
  690. var _self = this;
  691. layui.use(['layedit'], function () {
  692. layedit = layui.layedit;
  693. layedit.set({
  694. uploadImage: {
  695. url: ns.url("file://common/File/image")
  696. },
  697. callback: callback
  698. });
  699. _self.index = layedit.build(id, options);
  700. });
  701. }
  702. /**
  703. * 设置内容
  704. * @param content 内容
  705. * @param append 是否追加
  706. */
  707. Editor.prototype.setContent = function (content, append) {
  708. var _self = this;
  709. var time = setInterval(function () {
  710. layedit.setContent(_self.index, content, append);
  711. clearInterval(time);
  712. }, 150);
  713. };
  714. Editor.prototype.getContent = function () {
  715. return layedit.getContent(this.index);
  716. };
  717. Editor.prototype.getText = function () {
  718. return layedit.getText(this.index);
  719. };
  720. $(function () {
  721. loadImgMagnify();
  722. /* 处理日历图片点击问题 */
  723. $(function () {
  724. $(".calendar").parents(".layui-form-item").find("input").css({
  725. "background": 'transparent',
  726. 'z-index': 2,
  727. 'position': 'relative'
  728. });
  729. });
  730. });
  731. //图片最大递归次数
  732. var IMG_MAX_RECURSIVE_COUNT = 3;
  733. var count = 0;
  734. /**
  735. * 加载图片放大
  736. */
  737. function loadImgMagnify() {
  738. setTimeout(function () {
  739. try {
  740. if (layer) {
  741. $("img[src!=''][layer-src]").each(function () {
  742. var id = getId($(this).parent());
  743. layer.photos({
  744. photos: "#" + id,
  745. anim: 5
  746. });
  747. count = 0;
  748. });
  749. }
  750. } catch (e) {
  751. }
  752. }, 200);
  753. }
  754. function getId(o) {
  755. count++;
  756. var id = o.attr("id");
  757. // console.log("递归次数:", count,id);
  758. if (id == undefined && count < IMG_MAX_RECURSIVE_COUNT) {
  759. id = getId(o.parent());
  760. }
  761. if (id == undefined) {
  762. id = ns.gen_non_duplicate(10);
  763. o.attr("id", id);
  764. }
  765. return id;
  766. }
  767. // 返回(关闭弹窗)
  768. function back() {
  769. layer.closeAll('page');
  770. }
  771. /**
  772. * 自定义分页
  773. * @param options
  774. * @constructor
  775. */
  776. function Page(options) {
  777. if (!options) return;
  778. var _self = this;
  779. options.elem = options.elem.replace(/#/g, "");// 注意:这里不能加 # 号
  780. options.count = options.count || 0;// 数据总数。一般通过服务端得到
  781. options.limit = options.limit || 10;// 每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。
  782. options.limits = options.limits || [10,20,30,40,50,60,70,80,90];// 每页条数的选择项。如果 layout 参数开启了 limit,则会出现每页条数的select选择框
  783. options.curr = options.curr || location.hash.replace('#!page=', '');// 起始页。一般用于刷新类型的跳页以及HASH跳页
  784. // options.hash = options.hash || 'page';// 开启location.hash,并自定义 hash 值。如果开启,在触发分页时,会自动对url追加:#!hash值={curr} 利用这个,可以在页面载入时就定位到指定页
  785. options.groups = options.groups || 5;// 连续出现的页码个数
  786. options.prev = options.prev || '<i class="layui-icon layui-icon-left"></i>';// 自定义“上一页”的内容,支持传入普通文本和HTML
  787. options.next = options.next || '<i class="layui-icon layui-icon-right"></i>';// 自定义“下一页”的内容,同上
  788. options.first = options.first || 1;// 自定义“首页”的内容,同上
  789. options.request = options.request || {
  790. limitName: 'page_size' //每页数据量的参数名,默认:limit
  791. };
  792. // 自定义排版。可选值有:count(总条目输区域)、prev(上一页区域)、page(分页区域)、next(下一页区域)、limit(条目选项区域)、refresh(页面刷新区域。注意:layui 2.3.0 新增) 、skip(快捷跳页区域)
  793. options.layout = options.layout || ['count', 'limit','prev', 'page', 'next'];
  794. options.jump = function (obj, first) {
  795. //首次不执行,一定要加此判断,否则初始时会无限刷新
  796. if (!first) {
  797. obj.page = obj.curr;
  798. if (options.callback) options.callback.call(this, obj);
  799. }
  800. };
  801. layui.use('laypage', function () {
  802. _self._page = layui.laypage;
  803. _self._page.render(options);
  804. });
  805. }
  806. /**
  807. * 表单验证
  808. * @value options
  809. * @item
  810. */
  811. layui.use('form', function () {
  812. var form = layui.form;
  813. $(".layui-input").blur(function () {
  814. var val = $(this).val().trim();
  815. $(this).val(val);
  816. })
  817. $(".layui-textarea").blur(function () {
  818. var val = $(this).val().trim();
  819. $(this).val(val);
  820. })
  821. form.verify({
  822. required: function (value, item) {
  823. var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
  824. str = str.substring(0, str.length - 1);
  825. if (value == null || value.trim() == "" || value == undefined || value == null) return str + "不能为空";
  826. }
  827. });
  828. });
  829. /**
  830. * 面板折叠
  831. * @value options
  832. * @item
  833. */
  834. layui.use('element', function () {
  835. var element = layui.element;
  836. element.on('collapse(selection_panel)', function (data) {
  837. if (data.show) {
  838. $(data.title).find("i").removeClass("layui-icon-up").addClass("layui-icon-down");
  839. } else {
  840. $(data.title).find("i").removeClass("layui-icon-down").addClass("layui-icon-up");
  841. }
  842. $(data.title).find("i").text('');
  843. });
  844. });
  845. /**
  846. * 上传
  847. * layui官方文档:https://www.layui.com/doc/modules/upload.html
  848. * @param options
  849. * @constructor
  850. */
  851. function Upload(options) {
  852. if (!options) return;
  853. if (!options.size) {
  854. options.size = ns.upload_max_filesize;
  855. }
  856. var elemChildImg = $(options.elem).children('.preview_img')
  857. var _self = this;
  858. var $parent = $(options.elem).parent();
  859. options.post = options.post || "shop";
  860. if (options.post == 'store') options.post += '://store';
  861. this.post = options.post;
  862. options.url = options.url || ns.url(options.post + "/upload/image");
  863. options.accept = options.accept || "images";
  864. options.before = function (obj) {
  865. // console.log("before", obj)
  866. };
  867. //预览
  868. if (options.auto === false && options.bindAction) {
  869. options.choose = function (res) {
  870. var elemChildImg = $(options.elem).children('.preview_img');
  871. var $parent = $(options.elem).parent();
  872. res.preview(function (index, file, result) {
  873. $parent.find("input[type='hidden']").val(result);
  874. $parent.find(".del").addClass("show");
  875. $parent.addClass('hover');
  876. if (elemChildImg.length) {
  877. var tempId = $(options.elem).children('.preview_img').attr('id');
  878. var tempHtml = "<div id='" + tempId + "' class='preview_img'><img layer-src title='点击放大图片' src=" + result + " class='img_prev' data-prev='1' data-action-id='" + options.bindAction + "'></div>";
  879. $parent.children('.upload-default').html(tempHtml);
  880. } else {
  881. var tempId = $(options.elem).attr('id');
  882. var tempHtml = "<div id='preview_" + tempId + "' class='preview_img'><img layer-src title='点击放大图片' src=" + result + " class='img_prev' data-prev='1' data-action-id='" + options.bindAction + "'></div>";
  883. $parent.children('.upload-default').html(tempHtml);
  884. }
  885. });
  886. }
  887. }
  888. options.done = function (res, index, upload) {
  889. try {
  890. if (res.code >= 0) {
  891. $parent.find("input[type='hidden']").val(res.data.pic_path);
  892. $parent.find(".del").addClass("show");
  893. $parent.addClass('hover');
  894. if (res.data.pic_info) {
  895. res.data.pic_path = res.data.pic_info.pic_path;
  896. }
  897. if (options.accept == 'images') {
  898. if (elemChildImg.length) {
  899. var tempId = $(options.elem).children('.preview_img').attr('id');
  900. var tempHtml = "<div id='" + tempId + "' class='preview_img'><img layer-src title='点击放大图片' src=" + ns.img(res.data.pic_path) + " class='img_prev'></div>";
  901. $parent.children('.upload-default').html(tempHtml);
  902. } else {
  903. var tempId = $(options.elem).attr('id');
  904. var tempHtml = "<div id='preview_" + tempId + "' class='preview_img'><img layer-src title='点击放大图片' src=" + ns.img(res.data.pic_path) + " class='img_prev'></div>";
  905. $parent.children('.upload-default').html(tempHtml);
  906. }
  907. // var tempHtml = "<div id='imgId' class='preview_img'><img layer-src title='点击放大图片' src=" + ns.img(res.data.pic_path) + " class='img_prev'></div>";
  908. // $parent.children('.upload-default').html(tempHtml);
  909. }
  910. // $(options.elem).addClass("replace").removeClass("no-replace");
  911. typeof options.callback == "function" ? options.callback(res) : "";
  912. }
  913. } catch (e) {
  914. } finally {
  915. //加载图片放大
  916. if (options.accept == 'images') loadImgMagnify();
  917. // if (options.callback) options.callback(res, index, upload);
  918. }
  919. if (!options.callback) {
  920. return layer.msg(res.message);
  921. }
  922. };
  923. layui.use('upload', function () {
  924. _self._upload = layui.upload;
  925. _self._upload.render(options);
  926. });
  927. // this.elem = options.elem;
  928. this.parent = $parent;
  929. $parent.find(".js-delete").click(function () {
  930. var path = $parent.children('.operation').siblings("input[type='hidden']").val();
  931. if (!path) return;
  932. _self.path = path;
  933. $parent.children('.operation').siblings("input[type='hidden']").val("");
  934. $parent.removeClass("hover");
  935. $parent.find(".upload-default").html(`
  936. <div class="upload"><i class="iconfont iconshangchuan"></i>
  937. <p>点击上传</p></div>
  938. `);
  939. if (options.deleteCallback) options.deleteCallback();
  940. $(options.elem).removeClass("hover");
  941. });
  942. // 预览
  943. $parent.find(".js-preview").click(function (e) {
  944. var id = $parent.find('.preview_img').attr('id');
  945. $parent.find('.img_prev').click()
  946. return false;
  947. });
  948. // 替换
  949. $parent.find(".js-replace").click(function (e) {
  950. var id = $parent.find('.upload-default').attr('id')
  951. $parent.find('#' + id).click()
  952. });
  953. }
  954. // 删除物理文件
  955. Upload.prototype.delete = function () {
  956. var _self = this;
  957. $.ajax({
  958. url: ns.url(_self.post + "/upload/deleteFile"),
  959. data: {path: _self.path},
  960. dataType: 'JSON',
  961. type: 'POST',
  962. success: function (res) {
  963. $(_self).removeClass("show");
  964. }
  965. });
  966. };
  967. // 关闭组件编辑模块内容
  968. function closeBox(obj) {
  969. var elem = $(obj).parents(".template-edit-title").next();
  970. if ($(elem).hasClass("layui-hide")) {
  971. $(elem).removeClass("layui-hide");
  972. $(obj).removeClass("closed-right");
  973. } else {
  974. $(elem).addClass("layui-hide");
  975. $(obj).addClass("closed-right");
  976. }
  977. }
  978. /**
  979. * 日期时间选择
  980. * @param options
  981. * @constructor
  982. */
  983. function LayDate(options, judge) {
  984. // judge 判断是默认时间是否是当前~下月当天,还是上月上天~当前{nextmonth 下月 ;beformonth 上月}
  985. if (!options) return;
  986. var _self = this;
  987. options.type = options.type || 'datetime';
  988. if (options.type == "datetime") {
  989. options.range = options.range == false ? false : true;
  990. options.format = options.format || "yyyy-MM-dd HH:mm:ss";
  991. if (options.range) {
  992. var myDate = new Date();
  993. var startData = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate() + " 00:00:00",
  994. endData = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate() + " 23:59:59",
  995. time = startData + " - " + endData;
  996. options.value = options.value || time;
  997. }
  998. } else {
  999. options.format = options.format || "yyyy-MM-dd";
  1000. }
  1001. //获取当前时间 yy-MM-dd HH:mm:ss格式
  1002. var myDate = new Date();
  1003. let currentDate = myDate.toLocaleString('chinese', {hour12: false}).split('/').join('-');
  1004. let nextmonth = '';//获取下月当天时间
  1005. let beformonth = ''; //获取下月当天时间
  1006. let defaultTime = '';//默认时间
  1007. let dateTime = [];
  1008. currentDate.split(' ')[0].split('-').forEach((item, index) => {
  1009. if (item < 10) {
  1010. dateTime.push('0' + item)
  1011. } else {
  1012. dateTime.push(item)
  1013. }
  1014. })
  1015. //当天时间
  1016. currentDate = dateTime.join('-') + ' ' + currentDate.split(' ')[1]
  1017. // 下月当天时间
  1018. nextmonth = nextmonthTime() + ' ' + '23:59:59'
  1019. // 上月当天时间
  1020. beformonth = beformonthTime() + ' ' + '00:00:00'
  1021. if (judge == 'nextmonth') {
  1022. defaultTime = currentDate + ' - ' + nextmonth
  1023. } else if (judge == 'beformonth') {
  1024. defaultTime = beformonth + ' - ' + currentDate
  1025. } else {
  1026. defaultTime = options.value
  1027. }
  1028. options.min = options.min || '1900-1-1';
  1029. options.max = options.max || options.max == 0 ? options.max : '2099-12-31';
  1030. options.trigger = options.trigger || 'focus';
  1031. options.position = options.position || "absolute";
  1032. options.zIndex = options.zIndex || 66666666;
  1033. options.value = defaultTime;
  1034. layui.use('laydate', function () {
  1035. _self._laydate = layui.laydate;
  1036. _self._laydate.render(options);
  1037. });
  1038. }
  1039. // 获取下月时间
  1040. function nextmonthTime() {
  1041. var now = new Date();
  1042. var year = now.getFullYear();
  1043. var month = now.getMonth() + 1;
  1044. var day = now.getDate();
  1045. if (parseInt(month) < 10) {
  1046. month = "0" + month;
  1047. }
  1048. if (parseInt(day) < 10) {
  1049. day = "0" + day;
  1050. }
  1051. now = year + '-' + month + '-' + day;
  1052. // // 下月信息
  1053. let lastMonth = parseInt(month) + 1
  1054. if (parseInt(lastMonth) > 12) {
  1055. lastMonth = '01'
  1056. }
  1057. var lastSize = new Date(year, parseInt(lastMonth), 0).getDate();//下月总天数
  1058. // //十二月份取下年一月份
  1059. if (parseInt(month) == 12) {
  1060. return (parseInt(year) + 1) + '-01-' + day;
  1061. }
  1062. if (parseInt(lastSize) < parseInt(day)) {
  1063. return year + '-' + lastMonth + '-' + lastSize;
  1064. } else {
  1065. return year + '-' + lastMonth + '-' + day;
  1066. }
  1067. }
  1068. // 获取上月时间
  1069. function beformonthTime() {
  1070. var now = new Date();
  1071. var year = now.getFullYear();
  1072. var month = now.getMonth() + 1;
  1073. var day = now.getDate();
  1074. if (parseInt(month) < 10) {
  1075. month = "0" + month;
  1076. }
  1077. if (parseInt(day) < 10) {
  1078. day = "0" + day;
  1079. }
  1080. let preMonth = parseInt(month) - 1
  1081. if (parseInt(preMonth) < 1) {
  1082. preMonth = '12'
  1083. }
  1084. var preSize = new Date(year, parseInt(preMonth), 0).getDate();//上月总天数
  1085. // 1月份取上一年的12月,年份退一年
  1086. if (parseInt(month) == 1) {
  1087. return (parseInt(year) - 1) + '-12-' + day;
  1088. }
  1089. // 获取上月天数
  1090. if (parseInt(preSize) < parseInt(day)) {
  1091. return year + '-' + preMonth + '-' + preSize;
  1092. } else {
  1093. //没有特殊情况的话,就选择个
  1094. return year + '-' + preMonth + '-' + day;
  1095. }
  1096. }
  1097. /**
  1098. * 金额格式化输入
  1099. * @param money
  1100. */
  1101. function moneyFormat(money) {
  1102. if (isNaN(money)) return money;
  1103. return parseFloat(money).toFixed(2);
  1104. }
  1105. /**
  1106. * 颜色混合
  1107. * @param c1
  1108. * @param c2
  1109. * @param ratio
  1110. * @returns {string}
  1111. */
  1112. function colourBlend(c1, c2, ratio) {
  1113. ratio = Math.max(Math.min(Number(ratio), 1), 0)
  1114. let r1 = parseInt(c1.substring(1, 3), 16)
  1115. let g1 = parseInt(c1.substring(3, 5), 16)
  1116. let b1 = parseInt(c1.substring(5, 7), 16)
  1117. let r2 = parseInt(c2.substring(1, 3), 16)
  1118. let g2 = parseInt(c2.substring(3, 5), 16)
  1119. let b2 = parseInt(c2.substring(5, 7), 16)
  1120. let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
  1121. let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
  1122. let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
  1123. r = ('0' + (r || 0).toString(16)).slice(-2)
  1124. g = ('0' + (g || 0).toString(16)).slice(-2)
  1125. b = ('0' + (b || 0).toString(16)).slice(-2)
  1126. return '#' + r + g + b
  1127. }
  1128. //判空函数
  1129. ns.checkIsNotNull = function (param) {
  1130. if (param) {
  1131. if (typeof (param) == 'object') {
  1132. if (Array.isArray(param)) {
  1133. if (param.length > 0) return true
  1134. } else {
  1135. if (JSON.stringify(param) != '{}') return true
  1136. }
  1137. } else {
  1138. return true;
  1139. }
  1140. }
  1141. return false;
  1142. }