common.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. /**
  2. * 基础函数
  3. */
  4. (function (window, $, undefined) {
  5. let serverUrl = window.location.origin + '/';
  6. /**
  7. * =============================================================================
  8. * ************************** 基础函数类 **************************
  9. * =============================================================================
  10. */
  11. $.extend({
  12. /**
  13. * 身份识别码
  14. * @param text
  15. * @returns {*|string}
  16. */
  17. token: function (text) {
  18. let token = this.storage('token') || '';
  19. if (typeof text === 'string') {
  20. this.storage('token', text);
  21. token = text;
  22. }
  23. return token;
  24. },
  25. /**
  26. * 随机获取范围
  27. * @param Min
  28. * @param Max
  29. * @returns {*}
  30. */
  31. randNum(Min,Max){
  32. let Range = Max - Min;
  33. let Rand = Math.random();
  34. return Min + Math.round(Rand * Range); //四舍五入
  35. },
  36. /**
  37. * 获取数组最后一个值
  38. * @param array
  39. * @returns {boolean}
  40. */
  41. last: function (array) {
  42. let str = false;
  43. if (typeof array === 'object' && array.length > 0) {
  44. str = array[array.length - 1];
  45. }
  46. return str;
  47. },
  48. /**
  49. * 字符串是否包含
  50. * @param string
  51. * @param find
  52. * @param lower
  53. * @returns {boolean}
  54. */
  55. strExists: function (string, find, lower = false) {
  56. string += "";
  57. find += "";
  58. if (lower !== true) {
  59. string = string.toLowerCase();
  60. find = find.toLowerCase();
  61. }
  62. return (string.indexOf(find) !== -1);
  63. },
  64. /**
  65. * 字符串是否左边包含
  66. * @param string
  67. * @param find
  68. * @param lower
  69. * @returns {boolean}
  70. */
  71. leftExists: function (string, find, lower = false) {
  72. string += "";
  73. find += "";
  74. if (lower !== true) {
  75. string = string.toLowerCase();
  76. find = find.toLowerCase();
  77. }
  78. return (string.substring(0, find.length) === find);
  79. },
  80. /**
  81. * 删除左边字符串
  82. * @param string
  83. * @param find
  84. * @param lower
  85. * @returns {string}
  86. */
  87. leftDelete: function (string, find, lower = false) {
  88. string += "";
  89. find += "";
  90. if (this.leftExists(string, find, lower)) {
  91. string = string.substring(find.length)
  92. }
  93. return string ? string : '';
  94. },
  95. /**
  96. * 字符串是否右边包含
  97. * @param string
  98. * @param find
  99. * @param lower
  100. * @returns {boolean}
  101. */
  102. rightExists: function (string, find, lower = false) {
  103. string += "";
  104. find += "";
  105. if (lower !== true) {
  106. string = string.toLowerCase();
  107. find = find.toLowerCase();
  108. }
  109. return (string.substring(string.length - find.length) === find);
  110. },
  111. /**
  112. * 取字符串中间
  113. * @param string
  114. * @param start
  115. * @param end
  116. * @returns {*}
  117. */
  118. getMiddle: function (string, start, end) {
  119. string = string.toString();
  120. if (this.ishave(start) && this.strExists(string, start)) {
  121. string = string.substring(string.indexOf(start) + start.length);
  122. }
  123. if (this.ishave(end) && this.strExists(string, end)) {
  124. string = string.substring(0, string.indexOf(end));
  125. }
  126. return string;
  127. },
  128. /**
  129. * 截取字符串
  130. * @param string
  131. * @param start
  132. * @param end
  133. * @returns {string}
  134. */
  135. subString: function(string, start, end) {
  136. string += "";
  137. if (!this.ishave(end)) {
  138. end = string.length;
  139. }
  140. return string.substring(start, end);
  141. },
  142. /**
  143. * 随机字符
  144. * @param len
  145. * @returns {string}
  146. */
  147. randomString: function (len) {
  148. len = len || 32;
  149. let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678oOLl9gqVvUuI1';
  150. let maxPos = $chars.length;
  151. let pwd = '';
  152. for (let i = 0; i < len; i++) {
  153. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  154. }
  155. return pwd;
  156. },
  157. /**
  158. * 判断是否有
  159. * @param set
  160. * @returns {boolean}
  161. */
  162. ishave: function (set) {
  163. return !!(set !== null && set !== "null" && set !== undefined && set !== "undefined" && set);
  164. },
  165. /**
  166. * 相当于 intval
  167. * @param str
  168. * @param fixed
  169. * @returns {number}
  170. */
  171. runNum: function (str, fixed) {
  172. let _s = Number(str);
  173. if (_s + "" === "NaN") {
  174. _s = 0;
  175. }
  176. if (/^[0-9]*[1-9][0-9]*$/.test(fixed)) {
  177. _s = _s.toFixed(fixed);
  178. let rs = _s.indexOf('.');
  179. if (rs < 0) {
  180. _s += ".";
  181. for (let i = 0; i < fixed; i++) {
  182. _s += "0";
  183. }
  184. }
  185. }
  186. return _s;
  187. },
  188. /**
  189. * 服务器地址
  190. * @param str
  191. * @returns {string}
  192. */
  193. serverUrl: function (str) {
  194. if (str.substring(0, 2) === "//" ||
  195. str.substring(0, 7) === "http://" ||
  196. str.substring(0, 8) === "https://" ||
  197. str.substring(0, 6) === "ftp://" ||
  198. str.substring(0, 1) === "/") {
  199. return str;
  200. }
  201. return serverUrl + str;
  202. },
  203. /**
  204. * 获取IP地址详情
  205. * @param ip
  206. * @param callback
  207. */
  208. getIpInfo: function(ip, callback) {
  209. if (!this.strExists(ip, ".")) {
  210. return;
  211. }
  212. let keyName = '__ip' + ip.substring(0, 1) + '__';
  213. let key = this.getMiddle(ip, '', '.');
  214. let res = this.loadFromlLocal(key, ip, '', keyName);
  215. if (typeof res == "object") {
  216. if (typeof callback == "function") {
  217. callback(res);
  218. }
  219. return;
  220. }
  221. $A.ajax({
  222. url: $A.serverUrl('api/system/get/ipinfo'),
  223. data: { ip: ip },
  224. timeout: 8000,
  225. success: (res) => {
  226. this.savaToLocal(key, ip, res, keyName);
  227. if (typeof callback == "function") {
  228. callback(res);
  229. }
  230. }
  231. });
  232. },
  233. /**
  234. * 新增&&获取缓存数据
  235. * @param key
  236. * @param value
  237. * @returns {*}
  238. */
  239. storage: function(key, value) {
  240. let keyName = 'app';
  241. switch (window.location.pathname) {
  242. case "/admin":
  243. keyName+= ":" + window.location.pathname.substr(1);
  244. break;
  245. }
  246. if (typeof value === 'undefined') {
  247. return this.loadFromlLocal('__::', key, '', '__' + keyName + '__');
  248. }else{
  249. this.savaToLocal('__::', key, value, '__' + keyName + '__');
  250. }
  251. },
  252. /**
  253. * 新增&&修改本地缓存
  254. * @param {string} id 唯一id
  255. * @param {string} key 标示
  256. * @param value 新增&修改的值
  257. * @param keyName 主键名称
  258. */
  259. savaToLocal: function(id, key, value, keyName) {
  260. try {
  261. if (typeof keyName === 'undefined') keyName = '__seller__';
  262. let seller = window.localStorage[keyName];
  263. if (!seller) {
  264. seller = {};
  265. seller[id] = {};
  266. } else {
  267. seller = JSON.parse(seller);
  268. if (!seller[id]) {
  269. seller[id] = {};
  270. }
  271. }
  272. seller[id][key] = value;
  273. window.localStorage[keyName] = JSON.stringify(seller);
  274. } catch(e) { }
  275. },
  276. /**
  277. * 查询本地缓存
  278. * @param {string} id 唯一id
  279. * @param {string} key 标示
  280. * @param def 如果查询不到显示的值
  281. * @param keyName 主键名称
  282. */
  283. loadFromlLocal: function(id, key, def, keyName) {
  284. if (typeof keyName === 'undefined') keyName = '__seller__';
  285. let seller = window.localStorage[keyName];
  286. if (!seller) {
  287. return def;
  288. }
  289. seller = JSON.parse(seller)[id];
  290. if (!seller) {
  291. return def;
  292. }
  293. let ret = seller[key];
  294. return ret || def;
  295. },
  296. /**
  297. * 补零
  298. * @param str
  299. * @param length
  300. * @param after
  301. * @returns {*}
  302. */
  303. zeroFill: function(str, length, after) {
  304. str+= "";
  305. if (str.length >= length) {
  306. return str;
  307. }
  308. let _str = '', _ret = '';
  309. for (let i = 0; i < length; i++) {
  310. _str += '0';
  311. }
  312. if (after || typeof after === 'undefined') {
  313. _ret = (_str + "" + str).substr(length * -1);
  314. } else {
  315. _ret = (str + "" + _str).substr(0, length);
  316. }
  317. return _ret;
  318. },
  319. /**
  320. * 时间戳转时间格式
  321. * @param format
  322. * @param v
  323. * @returns {string}
  324. */
  325. formatDate: function(format, v) {
  326. if (format === '') {
  327. format = 'Y-m-d H:i:s';
  328. }
  329. let dateObj;
  330. if (v instanceof Date) {
  331. dateObj = v;
  332. }else {
  333. if (typeof v === 'undefined') {
  334. v = new Date().getTime();
  335. }else if (/^(-)?\d{1,10}$/.test(v)) {
  336. v = v * 1000;
  337. } else if (/^(-)?\d{1,13}$/.test(v)) {
  338. v = v * 1000;
  339. } else if (/^(-)?\d{1,14}$/.test(v)) {
  340. v = v * 100;
  341. } else if (/^(-)?\d{1,15}$/.test(v)) {
  342. v = v * 10;
  343. } else if (/^(-)?\d{1,16}$/.test(v)) {
  344. v = v * 1;
  345. } else {
  346. return v;
  347. }
  348. dateObj = new Date(v);
  349. }
  350. //
  351. format = format.replace(/Y/g, dateObj.getFullYear());
  352. format = format.replace(/m/g, this.zeroFill(dateObj.getMonth() + 1, 2));
  353. format = format.replace(/d/g, this.zeroFill(dateObj.getDate(), 2));
  354. format = format.replace(/H/g, this.zeroFill(dateObj.getHours(), 2));
  355. format = format.replace(/i/g, this.zeroFill(dateObj.getMinutes(), 2));
  356. format = format.replace(/s/g, this.zeroFill(dateObj.getSeconds(), 2));
  357. return format;
  358. },
  359. /**
  360. * 租用时间差(不够1个小时算一个小时)
  361. * @param s
  362. * @param e
  363. * @returns {*}
  364. */
  365. timeDiff: function(s, e) {
  366. if (typeof e === 'undefined') {
  367. e = Math.round(new Date().getTime()/1000);
  368. }
  369. let d = e - s;
  370. if (d > 86400) {
  371. let day = Math.floor(d / 86400);
  372. let hour = Math.ceil((d - (day * 86400)) / 3600);
  373. if (hour > 0) {
  374. return day + '天' + hour + '小时';
  375. } else {
  376. return day + '天';
  377. }
  378. } else if (d > 3600) {
  379. return Math.ceil(d / 3600) + '小时';
  380. } else if (d > 60) {
  381. return Math.ceil(d / 60) + '分钟';
  382. } else if (d > 10) {
  383. return d + '秒';
  384. } else {
  385. return '刚刚';
  386. }
  387. },
  388. /**
  389. * 检测手机号码格式
  390. * @param str
  391. * @returns {boolean}
  392. */
  393. isMobile: function(str) {
  394. return /^1([3456789])\d{9}$/.test(str);
  395. },
  396. /**
  397. * 是否手机号码
  398. * @param phone
  399. * @returns {boolean}
  400. */
  401. isPhone: function (phone) {
  402. return this.isMobile(phone);
  403. },
  404. /**
  405. * 根据两点间的经纬度计算距离
  406. * @param lng1
  407. * @param lat1
  408. * @param lng2
  409. * @param lat2
  410. * @returns {string|*}
  411. */
  412. getDistance: function (lng1, lat1, lng2, lat2) {
  413. let DEF_PI = 3.14159265359; // PI
  414. let DEF_2PI = 6.28318530712; // 2*PI
  415. let DEF_PI180 = 0.01745329252; // PI/180.0
  416. let DEF_R = 6370693.5; // radius of earth
  417. //
  418. let ew1, ns1, ew2, ns2;
  419. let dx, dy, dew;
  420. let distance;
  421. // 角度转换为弧度
  422. ew1 = lng1 * DEF_PI180;
  423. ns1 = lat1 * DEF_PI180;
  424. ew2 = lng2 * DEF_PI180;
  425. ns2 = lat2 * DEF_PI180;
  426. // 经度差
  427. dew = ew1 - ew2;
  428. // 若跨东经和西经180 度,进行调整
  429. if (dew > DEF_PI)
  430. dew = DEF_2PI - dew;
  431. else if (dew < -DEF_PI)
  432. dew = DEF_2PI + dew;
  433. dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
  434. dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
  435. // 勾股定理求斜边长
  436. distance = Math.sqrt(dx * dx + dy * dy).toFixed(0);
  437. return distance;
  438. },
  439. /**
  440. * 设置网页标题
  441. * @param title
  442. */
  443. setTile(title) {
  444. document.title = title;
  445. let mobile = navigator.userAgent.toLowerCase();
  446. if (/iphone|ipad|ipod/.test(mobile)) {
  447. let iframe = document.createElement('iframe');
  448. iframe.style.display = 'none';
  449. iframe.setAttribute('src', '/favicon.ico');
  450. let iframeCallback = function () {
  451. setTimeout(function () {
  452. iframe.removeEventListener('load', iframeCallback);
  453. document.body.removeChild(iframe)
  454. }, 0)
  455. };
  456. iframe.addEventListener('load', iframeCallback);
  457. document.body.appendChild(iframe)
  458. }
  459. },
  460. /**
  461. * 克隆对象
  462. * @param myObj
  463. * @returns {*}
  464. */
  465. cloneData(myObj) {
  466. if(typeof(myObj) !== 'object') return myObj;
  467. if(myObj === null) return myObj;
  468. //
  469. if (typeof myObj.length === 'number') {
  470. let [ ...myNewObj ] = myObj;
  471. return myNewObj;
  472. }else{
  473. let { ...myNewObj } = myObj;
  474. return myNewObj;
  475. }
  476. },
  477. /**
  478. * 将一个 JSON 字符串转换为对象(已try)
  479. * @param str
  480. * @param defaultVal
  481. * @returns {*}
  482. */
  483. jsonParse(str, defaultVal) {
  484. if (str === null) {
  485. return defaultVal ? defaultVal : {};
  486. }
  487. if (typeof str === "object") {
  488. return str;
  489. }
  490. try {
  491. return JSON.parse(str);
  492. } catch (e) {
  493. return defaultVal ? defaultVal : {};
  494. }
  495. },
  496. /**
  497. * 将 JavaScript 值转换为 JSON 字符串(已try)
  498. * @param json
  499. * @param defaultVal
  500. * @returns {string}
  501. */
  502. jsonStringify(json, defaultVal) {
  503. if (typeof json !== 'object') {
  504. return json;
  505. }
  506. try{
  507. return JSON.stringify(json);
  508. }catch (e) {
  509. return defaultVal ? defaultVal : "";
  510. }
  511. },
  512. /**
  513. * 监听对象尺寸发生改变
  514. * @param obj
  515. * @param callback
  516. */
  517. resize(obj, callback) {
  518. let myObj = $A(obj);
  519. if (myObj.length === 0) return;
  520. let height = parseInt(myObj.outerHeight()),
  521. width = parseInt(myObj.outerWidth());
  522. let inter = setInterval(()=>{
  523. if (myObj.length === 0) clearInterval(inter);
  524. let tmpHeight = parseInt(myObj.outerHeight()),
  525. tmpWidth = parseInt(myObj.outerWidth());
  526. if (height !== tmpHeight || width !== tmpWidth) {
  527. height = tmpHeight;
  528. width = tmpWidth;
  529. console.log(width, height);
  530. if (typeof callback === 'function') callback();
  531. }
  532. }, 250);
  533. },
  534. /**
  535. * 是否IOS
  536. * @returns {boolean|string}
  537. */
  538. isIos() {
  539. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  540. return ua && /iphone|ipad|ipod|ios/.test(ua);
  541. },
  542. /**
  543. * 是否安卓
  544. * @returns {boolean|string}
  545. */
  546. isAndroid() {
  547. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  548. return ua && ua.indexOf('android') > 0;
  549. },
  550. /**
  551. * 是否微信
  552. * @returns {boolean}
  553. */
  554. isWeixin() {
  555. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  556. return (ua.match(/MicroMessenger/i) + '' === 'micromessenger');
  557. },
  558. /**
  559. * 获取对象
  560. * @param obj
  561. * @param keys
  562. * @returns {string|*}
  563. */
  564. getObject(obj, keys) {
  565. let object = obj;
  566. if (this.count(obj) === 0 || this.count(keys) === 0) {
  567. return "";
  568. }
  569. let arr = keys.replace(/,/g, "|").replace(/\./g, "|").split("|");
  570. $A.each(arr, (index, key) => {
  571. object = typeof object[key] === "undefined" ? "" : object[key];
  572. });
  573. return object;
  574. },
  575. /**
  576. * 统计数组或对象长度
  577. * @param obj
  578. * @returns {number}
  579. */
  580. count(obj) {
  581. try {
  582. if (typeof obj === "undefined") {
  583. return 0;
  584. }
  585. if (typeof obj === "number") {
  586. obj+= "";
  587. }
  588. if (typeof obj.length === 'number') {
  589. return obj.length;
  590. } else {
  591. let i = 0, key;
  592. for (key in obj) {
  593. i++;
  594. }
  595. return i;
  596. }
  597. }catch (e) {
  598. return 0;
  599. }
  600. },
  601. /**
  602. * 将数组或对象内容部分拼成字符串
  603. * @param obj
  604. * @returns {string}
  605. */
  606. objImplode(obj) {
  607. if (obj === null) {
  608. return "";
  609. }
  610. let str = "";
  611. $A.each(obj, (key, val) => {
  612. if (val !== null) {
  613. if (typeof val === "object" && this.count(val) > 0) {
  614. str += this.objImplode(val);
  615. } else {
  616. str += String(val);
  617. }
  618. }
  619. });
  620. return str.replace(/\s/g, "").replace(/undefined/g, "");
  621. },
  622. /**
  623. * hash数组拼接
  624. * @param obj
  625. * @param filtrate
  626. * @returns {*}
  627. */
  628. hashSplice(obj, filtrate) {
  629. if (typeof obj !== 'object') {
  630. return obj;
  631. }
  632. let sObj = Object.keys(obj).sort(),
  633. text = "",
  634. sFiltrate = "," + filtrate + ",";
  635. for (let prop in sObj) {
  636. if (sObj.hasOwnProperty(prop)) {
  637. if (!$A.strExists(sFiltrate, "," + sObj[prop] + ",")) {
  638. if (text) text += "&";
  639. text += sObj[prop] + "=" + obj[sObj[prop]];
  640. }
  641. }
  642. }
  643. return text;
  644. },
  645. /**
  646. * 指定键获取hash参数
  647. * @param key
  648. * @returns {*}
  649. */
  650. hashParameter(key) {
  651. let params = this.hashParameterAll();
  652. return params[key];
  653. },
  654. hashParameterAll() {
  655. let hash = location.hash || "";
  656. let arr;
  657. if (this.strExists(hash, "?")) {
  658. arr = this.getMiddle(hash, "?").split("&");
  659. }else{
  660. arr = this.getMiddle(hash, "#").split("&");
  661. }
  662. let params = {};
  663. for (let i = 0; i < arr.length; i++) {
  664. let data = arr[i].split("=");
  665. if (data.length === 2) {
  666. params[data[0]] = data[1];
  667. }
  668. }
  669. return params;
  670. },
  671. /**
  672. * 删除地址中的参数
  673. * @param url
  674. * @param parameter
  675. * @returns {string|*}
  676. */
  677. removeURLParameter(url, parameter) {
  678. if (parameter instanceof Array) {
  679. parameter.forEach((key) => {
  680. url = $A.removeURLParameter(url, key)
  681. });
  682. return url;
  683. }
  684. var urlparts = url.split('?');
  685. if (urlparts.length >= 2) {
  686. //参数名前缀
  687. var prefix = encodeURIComponent(parameter) + '=';
  688. var pars = urlparts[1].split(/[&;]/g);
  689. //循环查找匹配参数
  690. for (var i = pars.length; i-- > 0;) {
  691. if (pars[i].lastIndexOf(prefix, 0) !== -1) {
  692. //存在则删除
  693. pars.splice(i, 1);
  694. }
  695. }
  696. return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
  697. }
  698. return url;
  699. },
  700. /**
  701. * 连接加上参数
  702. * @param url
  703. * @param params
  704. * @returns {*}
  705. */
  706. urlAddParams(url, params) {
  707. if (typeof params === "object" && params !== null) {
  708. url+= "";
  709. url+= url.indexOf("?") === -1 ? '?' : '';
  710. for (var key in params) {
  711. if (!params.hasOwnProperty(key)) {
  712. continue;
  713. }
  714. url+= '&' + key + '=' + params[key];
  715. }
  716. }
  717. return url.replace("?&", "?");
  718. },
  719. /**
  720. * 链接字符串
  721. * @param value 第一个参数为连接符
  722. * @returns {string}
  723. */
  724. stringConnect(...value) {
  725. let s = null;
  726. let text = "";
  727. value.forEach((val) => {
  728. if (s === null) {
  729. s = val;
  730. }else if (val){
  731. if (val && text) text+= s;
  732. text+= val;
  733. }
  734. });
  735. return text;
  736. },
  737. /**
  738. * 判断两个对象是否相等
  739. * @param x
  740. * @param y
  741. * @returns {boolean}
  742. */
  743. objEquals(x, y) {
  744. let f1 = x instanceof Object;
  745. let f2 = y instanceof Object;
  746. if (!f1 || !f2) {
  747. return x === y
  748. }
  749. if (Object.keys(x).length !== Object.keys(y).length) {
  750. return false
  751. }
  752. for (let p in x) {
  753. if (x.hasOwnProperty(p)) {
  754. let a = x[p] instanceof Object;
  755. let b = y[p] instanceof Object;
  756. if (a && b) {
  757. if (!this.objEquals(x[p], y[p])) {
  758. return false;
  759. }
  760. } else if (x[p] != y[p]) {
  761. return false;
  762. }
  763. }
  764. }
  765. return true;
  766. },
  767. /**
  768. * 输入框内插入文本
  769. * @param object
  770. * @param content
  771. */
  772. insert2Input (object, content) {
  773. if (object === null || typeof object !== "object") return;
  774. if (typeof object.length === 'number' && object.length > 0) object = object[0];
  775. let ele = typeof object.$el === "object" ? $A(object.$el) : $A(object);
  776. if (ele.length === 0) return;
  777. let eleDom = ele[0];
  778. if (eleDom.tagName != "INPUT" && eleDom.tagName != "TEXTAREA") {
  779. if (ele.find("input").length === 0) {
  780. ele = ele.find("textarea");
  781. }else{
  782. ele = ele.find("input");
  783. }
  784. }
  785. if (ele.length === 0) return;
  786. eleDom = ele[0];
  787. if (eleDom.tagName != "INPUT" && eleDom.tagName != "TEXTAREA") return;
  788. let text = ele.val();
  789. let { selectionStart, selectionEnd } = eleDom;
  790. ele.val(`${text.substring(0, selectionStart)}${content}${text.substring(selectionEnd, text.length)}`);
  791. eleDom.dispatchEvent(new Event('input'));
  792. setTimeout(() => {
  793. if (eleDom.setSelectionRange) {
  794. let pos = text.substring(0, selectionStart).length + content.length;
  795. eleDom.focus();
  796. eleDom.setSelectionRange(pos, pos);
  797. }
  798. }, 10);
  799. },
  800. /**
  801. * iOS上虚拟键盘引起的触控错位
  802. */
  803. iOSKeyboardFixer() {
  804. if (!this.isIos()) {
  805. return;
  806. }
  807. document.body.scrollTop = document.body.scrollTop + 1;
  808. document.body.scrollTop = document.body.scrollTop - 1;
  809. },
  810. autoDevwid(width) {
  811. let _width = width || 640;
  812. new function () {
  813. let _self = this;
  814. _self.width = _width; //设置默认最大宽度
  815. _self.fontSize = 30; //默认字体大小
  816. _self.widthProportion = function () {
  817. let p = (document.body && document.body.clientWidth || document.getElementsByTagName("html")[0].offsetWidth) / _self.width;
  818. return p > 1 ? 1 : p < 0.38 ? 0.38 : p;
  819. };
  820. _self.changePage = function () {
  821. document.getElementsByTagName("html")[0].setAttribute("style", "font-size:" + _self.widthProportion() * _self.fontSize + "px !important");
  822. };
  823. _self.changePage();
  824. window.addEventListener('resize', function () {
  825. _self.changePage();
  826. }, false);
  827. };
  828. //
  829. let scale = $A(window).width() / _width;
  830. $A(".__auto").each(function () {
  831. if ($A(this).attr("data-original") !== "1") {
  832. $A(this).attr("data-original-top", parseInt($A(this).css("top")));
  833. $A(this).attr("data-original-right", parseInt($A(this).css("right")));
  834. $A(this).attr("data-original-bottom", parseInt($A(this).css("bottom")));
  835. $A(this).attr("data-original-left", parseInt($A(this).css("left")));
  836. $A(this).attr("data-original-width", parseInt($A(this).css("width")));
  837. $A(this).attr("data-original-height", parseInt($A(this).css("height")));
  838. $A(this).attr("data-original-line-height", parseInt($A(this).css("line-height")));
  839. $A(this).attr("data-original", "1");
  840. }
  841. let _t = parseInt($A(this).attr("data-original-top"));
  842. let _r = parseInt($A(this).attr("data-original-right"));
  843. let _b = parseInt($A(this).attr("data-original-bottom"));
  844. let _l = parseInt($A(this).attr("data-original-left"));
  845. let _w = parseInt($A(this).attr("data-original-width"));
  846. let _h = parseInt($A(this).attr("data-original-height"));
  847. let _lh = parseInt($A(this).attr("data-original-line-height"));
  848. //
  849. let _css = {};
  850. if (_t > 0) _css['top'] = _t * scale;
  851. if (_r > 0) _css['right'] = _r * scale;
  852. if (_b > 0) _css['bottom'] = _b * scale;
  853. if (_l > 0) _css['left'] = _l * scale;
  854. if (_w > 0) _css['width'] = _w * scale;
  855. if (_h > 0) _css['height'] = _h * scale;
  856. if (_lh > 0) _css['line-height'] = (_lh * scale) + 'px';
  857. $A(this).css(_css);
  858. });
  859. return scale;
  860. }
  861. });
  862. /**
  863. * =============================================================================
  864. * **************************** ihttp ****************************
  865. * =============================================================================
  866. */
  867. $.extend({
  868. serializeObject (obj, parents) {
  869. if (typeof obj === 'string') return obj;
  870. let resultArray = [];
  871. let separator = '&';
  872. parents = parents || [];
  873. let newParents;
  874. function var_name(name) {
  875. if (parents.length > 0) {
  876. let _parents = '';
  877. for (let j = 0; j < parents.length; j++) {
  878. if (j === 0) _parents += parents[j];
  879. else _parents += '[' + encodeURIComponent(parents[j]) + ']';
  880. }
  881. return _parents + '[' + encodeURIComponent(name) + ']';
  882. }
  883. else {
  884. return encodeURIComponent(name);
  885. }
  886. }
  887. function var_value(value) {
  888. return encodeURIComponent(value);
  889. }
  890. for (let prop in obj) {
  891. if (obj.hasOwnProperty(prop)) {
  892. let toPush;
  893. if (Array.isArray(obj[prop])) {
  894. toPush = [];
  895. for (let i = 0; i < obj[prop].length; i++) {
  896. if (!Array.isArray(obj[prop][i]) && typeof obj[prop][i] === 'object') {
  897. newParents = parents.slice();
  898. newParents.push(prop);
  899. newParents.push(i + '');
  900. toPush.push($.serializeObject(obj[prop][i], newParents));
  901. }
  902. else {
  903. toPush.push(var_name(prop) + '[]=' + var_value(obj[prop][i]));
  904. }
  905. }
  906. if (toPush.length > 0) resultArray.push(toPush.join(separator));
  907. }
  908. else if (obj[prop] === null) {
  909. resultArray.push(var_name(prop) + '=');
  910. }
  911. else if (typeof obj[prop] === 'object') {
  912. // Object, convert to named array
  913. newParents = parents.slice();
  914. newParents.push(prop);
  915. toPush = $.serializeObject(obj[prop], newParents);
  916. if (toPush !== '') resultArray.push(toPush);
  917. }
  918. else if (typeof obj[prop] !== 'undefined' && obj[prop] !== '') {
  919. // Should be string or plain value
  920. resultArray.push(var_name(prop) + '=' + var_value(obj[prop]));
  921. }
  922. else if (obj[prop] === '') resultArray.push(var_name(prop));
  923. }
  924. }
  925. return resultArray.join(separator);
  926. },
  927. // Global Ajax Setup
  928. globalAjaxOptions: {},
  929. ajaxSetup (options) {
  930. if (options.type) options.method = options.type;
  931. $.each(options, function (optionName, optionValue) {
  932. $.globalAjaxOptions[optionName] = optionValue;
  933. });
  934. },
  935. // Ajax
  936. _jsonpRequests: 0,
  937. ihttp(options) {
  938. let defaults = {
  939. method: 'GET',
  940. data: false,
  941. async: true,
  942. cache: true,
  943. user: '',
  944. password: '',
  945. headers: {},
  946. xhrFields: {},
  947. statusCode: {},
  948. processData: true,
  949. dataType: 'text',
  950. contentType: 'application/x-www-form-urlencoded',
  951. timeout: 0
  952. };
  953. let callbacks = ['beforeSend', 'error', 'complete', 'success', 'statusCode'];
  954. //For jQuery guys
  955. if (options.type) options.method = options.type;
  956. // Merge global and defaults
  957. $.each($.globalAjaxOptions, function (globalOptionName, globalOptionValue) {
  958. if (callbacks.indexOf(globalOptionName) < 0) defaults[globalOptionName] = globalOptionValue;
  959. });
  960. // Function to run XHR callbacks and events
  961. function fireAjaxCallback(eventName, eventData, callbackName) {
  962. let a = arguments;
  963. if (eventName) $(document).trigger(eventName, eventData);
  964. if (callbackName) {
  965. // Global callback
  966. if (callbackName in $.globalAjaxOptions) $.globalAjaxOptions[callbackName](a[3], a[4], a[5], a[6]);
  967. // Options callback
  968. if (options[callbackName]) options[callbackName](a[3], a[4], a[5], a[6]);
  969. }
  970. }
  971. // Merge options and defaults
  972. $.each(defaults, function (prop, defaultValue) {
  973. if (!(prop in options)) options[prop] = defaultValue;
  974. });
  975. // Default URL
  976. if (!options.url) {
  977. options.url = window.location.toString();
  978. }
  979. // Parameters Prefix
  980. let paramsPrefix = options.url.indexOf('?') >= 0 ? '&' : '?';
  981. // UC method
  982. let _method = options.method.toUpperCase();
  983. // Data to modify GET URL
  984. if ((_method === 'GET' || _method === 'HEAD' || _method === 'OPTIONS' || _method === 'DELETE') && options.data) {
  985. let stringData;
  986. if (typeof options.data === 'string') {
  987. // Should be key=value string
  988. if (options.data.indexOf('?') >= 0) stringData = options.data.split('?')[1];
  989. else stringData = options.data;
  990. }
  991. else {
  992. // Should be key=value object
  993. stringData = $.serializeObject(options.data);
  994. }
  995. if (stringData.length) {
  996. options.url += paramsPrefix + stringData;
  997. if (paramsPrefix === '?') paramsPrefix = '&';
  998. }
  999. }
  1000. // JSONP
  1001. if (options.dataType === 'json' && options.url.indexOf('callback=') >= 0) {
  1002. let callbackName = 'f7jsonp_' + Date.now() + ($._jsonpRequests++);
  1003. let abortTimeout;
  1004. let callbackSplit = options.url.split('callback=');
  1005. let requestUrl = callbackSplit[0] + 'callback=' + callbackName;
  1006. if (callbackSplit[1].indexOf('&') >= 0) {
  1007. let addVars = callbackSplit[1].split('&').filter(function (el) {
  1008. return el.indexOf('=') > 0;
  1009. }).join('&');
  1010. if (addVars.length > 0) requestUrl += '&' + addVars;
  1011. }
  1012. // Create script
  1013. let script = document.createElement('script');
  1014. script.type = 'text/javascript';
  1015. script.onerror = function () {
  1016. clearTimeout(abortTimeout);
  1017. fireAjaxCallback(undefined, undefined, 'error', null, 'scripterror');
  1018. fireAjaxCallback('ajaxComplete ajax:complete', {scripterror: true}, 'complete', null, 'scripterror');
  1019. };
  1020. script.src = requestUrl;
  1021. // Handler
  1022. window[callbackName] = function (data) {
  1023. clearTimeout(abortTimeout);
  1024. fireAjaxCallback(undefined, undefined, 'success', data);
  1025. script.parentNode.removeChild(script);
  1026. script = null;
  1027. delete window[callbackName];
  1028. };
  1029. document.querySelector('head').appendChild(script);
  1030. if (options.timeout > 0) {
  1031. abortTimeout = setTimeout(function () {
  1032. script.parentNode.removeChild(script);
  1033. script = null;
  1034. fireAjaxCallback(undefined, undefined, 'error', null, 'timeout');
  1035. }, options.timeout);
  1036. }
  1037. return;
  1038. }
  1039. // Cache for GET/HEAD requests
  1040. if (_method === 'GET' || _method === 'HEAD' || _method === 'OPTIONS' || _method === 'DELETE') {
  1041. if (options.cache === false) {
  1042. options.url += (paramsPrefix + '_nocache=' + Date.now());
  1043. }
  1044. }
  1045. // Create XHR
  1046. let xhr = new XMLHttpRequest();
  1047. // Save Request URL
  1048. xhr.requestUrl = options.url;
  1049. xhr.requestParameters = options;
  1050. // Open XHR
  1051. xhr.open(_method, options.url, options.async, options.user, options.password);
  1052. // Create POST Data
  1053. let postData = null;
  1054. if ((_method === 'POST' || _method === 'PUT' || _method === 'PATCH') && options.data) {
  1055. if (options.processData) {
  1056. let postDataInstances = [ArrayBuffer, Blob, Document, FormData];
  1057. // Post Data
  1058. if (postDataInstances.indexOf(options.data.constructor) >= 0) {
  1059. postData = options.data;
  1060. }
  1061. else {
  1062. // POST Headers
  1063. let boundary = '---------------------------' + Date.now().toString(16);
  1064. if (options.contentType === 'multipart\/form-data') {
  1065. xhr.setRequestHeader('Content-Type', 'multipart\/form-data; boundary=' + boundary);
  1066. }
  1067. else {
  1068. xhr.setRequestHeader('Content-Type', options.contentType);
  1069. }
  1070. postData = '';
  1071. let _data = $.serializeObject(options.data);
  1072. if (options.contentType === 'multipart\/form-data') {
  1073. boundary = '---------------------------' + Date.now().toString(16);
  1074. _data = _data.split('&');
  1075. let _newData = [];
  1076. for (let i = 0; i < _data.length; i++) {
  1077. _newData.push('Content-Disposition: form-data; name="' + _data[i].split('=')[0] + '"\r\n\r\n' + _data[i].split('=')[1] + '\r\n');
  1078. }
  1079. postData = '--' + boundary + '\r\n' + _newData.join('--' + boundary + '\r\n') + '--' + boundary + '--\r\n';
  1080. }
  1081. else {
  1082. postData = _data;
  1083. }
  1084. }
  1085. }
  1086. else {
  1087. postData = options.data;
  1088. }
  1089. }
  1090. // Additional headers
  1091. if (options.headers) {
  1092. $.each(options.headers, function (headerName, headerCallback) {
  1093. xhr.setRequestHeader(headerName, headerCallback);
  1094. });
  1095. }
  1096. // Check for crossDomain
  1097. if (typeof options.crossDomain === 'undefined') {
  1098. options.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(options.url) && RegExp.$2 !== window.location.host;
  1099. }
  1100. if (!options.crossDomain) {
  1101. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  1102. }
  1103. if (options.xhrFields) {
  1104. $.each(options.xhrFields, function (fieldName, fieldValue) {
  1105. xhr[fieldName] = fieldValue;
  1106. });
  1107. }
  1108. let xhrTimeout;
  1109. // Handle XHR
  1110. xhr.onload = function (e) {
  1111. if (xhrTimeout) clearTimeout(xhrTimeout);
  1112. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
  1113. let responseData;
  1114. if (options.dataType === 'json') {
  1115. try {
  1116. responseData = JSON.parse(xhr.responseText);
  1117. fireAjaxCallback('ajaxSuccess ajax:success', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
  1118. }
  1119. catch (err) {
  1120. fireAjaxCallback('ajaxError ajax:error', {
  1121. xhr: xhr,
  1122. parseerror: true
  1123. }, 'error', xhr, 'parseerror');
  1124. }
  1125. }
  1126. else {
  1127. responseData = xhr.responseType === 'text' || xhr.responseType === '' ? xhr.responseText : xhr.response;
  1128. fireAjaxCallback('ajaxSuccess ajax:success', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
  1129. }
  1130. }
  1131. else {
  1132. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr}, 'error', xhr, xhr.status);
  1133. }
  1134. if (options.statusCode) {
  1135. if ($.globalAjaxOptions.statusCode && $.globalAjaxOptions.statusCode[xhr.status]) $.globalAjaxOptions.statusCode[xhr.status](xhr);
  1136. if (options.statusCode[xhr.status]) options.statusCode[xhr.status](xhr);
  1137. }
  1138. fireAjaxCallback('ajaxComplete ajax:complete', {xhr: xhr}, 'complete', xhr, xhr.status);
  1139. };
  1140. xhr.onerror = function (e) {
  1141. if (xhrTimeout) clearTimeout(xhrTimeout);
  1142. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr}, 'error', xhr, xhr.status);
  1143. fireAjaxCallback('ajaxComplete ajax:complete', {xhr: xhr, error: true}, 'complete', xhr, 'error');
  1144. };
  1145. // Ajax start callback
  1146. fireAjaxCallback('ajaxStart ajax:start', {xhr: xhr}, 'start', xhr);
  1147. fireAjaxCallback(undefined, undefined, 'beforeSend', xhr);
  1148. // Timeout
  1149. if (options.timeout > 0) {
  1150. xhr.onabort = function () {
  1151. if (xhrTimeout) clearTimeout(xhrTimeout);
  1152. };
  1153. xhrTimeout = setTimeout(function () {
  1154. xhr.abort();
  1155. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr, timeout: true}, 'error', xhr, 'timeout');
  1156. fireAjaxCallback('ajaxComplete ajax:complete', {
  1157. xhr: xhr,
  1158. timeout: true
  1159. }, 'complete', xhr, 'timeout');
  1160. }, options.timeout);
  1161. }
  1162. // Send XHR
  1163. xhr.send(postData);
  1164. // Return XHR object
  1165. return xhr;
  1166. }
  1167. });
  1168. /**
  1169. * =============================================================================
  1170. * ************************* Bootstrap extend ************************
  1171. * =============================================================================
  1172. */
  1173. $.extend({
  1174. toast(params, timeout, template) {
  1175. let _bg = function(num) {
  1176. let container = $A(".__bootstrap_toast_container");
  1177. if (container.length > 0) {
  1178. let bgobj = container.find(".alert-bg");
  1179. let bgnum = parseInt(bgobj.attr("data-num"));
  1180. bgnum+= num;
  1181. bgobj.attr("data-num", bgnum);
  1182. if (bgnum > 0) {
  1183. bgobj.show();
  1184. }else{
  1185. bgobj.hide();
  1186. }
  1187. }
  1188. };
  1189. if (!params) return false;
  1190. if (typeof params === 'object' && params.length > 0) {
  1191. if (params.attr("data-show-bg") === "true") _bg(-1);
  1192. params.css({width: Math.ceil(params.outerWidth())});
  1193. params.addClass("leave");
  1194. setTimeout(()=>{ params.remove() }, 300);
  1195. return;
  1196. }
  1197. if (typeof timeout === 'string') {
  1198. template = timeout;
  1199. timeout = 2500;
  1200. }
  1201. if (typeof params === 'string') params = { title: params };
  1202. if (typeof params.timeout === 'undefined') params.timeout = 2500;
  1203. if (typeof params.template === 'undefined') params.template = 'success';
  1204. if (typeof params.fixed === 'undefined') params.fixed = false;
  1205. if (typeof params.close === 'undefined') params.close = true;
  1206. if (typeof timeout !== 'undefined') params.timeout = timeout;
  1207. if (typeof template !== 'undefined') params.template = template;
  1208. //
  1209. let container = $A(".__bootstrap_toast_container");
  1210. if (container.length === 0) {
  1211. $A("<style>")
  1212. .attr({type: "text/css"})
  1213. .html(
  1214. ".__bootstrap_toast_container{position:fixed;z-index:99999;top:5%;right:5%;padding:0;text-align:right;}" +
  1215. ".__bootstrap_toast_container .alert-bg{position:fixed;display:none;z-index:1;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,0.6);}" +
  1216. ".__bootstrap_toast_container .alert-body{position:relative;z-index:2;display:block;min-width:180px;text-align:left;opacity:0;transform:translate3d(0,100px,0);-webkit-transform:translate3d(0,100px,0);transition-duration:300ms;-webkit-transition-duration:300ms;}" +
  1217. ".__bootstrap_toast_container .alert-body.enter{opacity:1;transform:translate3d(0,0,0);-webkit-transform:translate3d(0,0,0);}" +
  1218. ".__bootstrap_toast_container .alert-body.leave{position:absolute;top:0;right:0;z-index:3;opacity:0;transform:translate3d(100%,0,0);-webkit-transform:translate3d(100%,0,0);transition-duration:200ms;-webkit-transition-duration:300ms;}" +
  1219. "")
  1220. .appendTo("head");
  1221. $A("body").append("<div class='__bootstrap_toast_container'><div class='alert-bg' data-num='0'></div></div>");
  1222. container = $A(".__bootstrap_toast_container");
  1223. }
  1224. //
  1225. let $intemp = $A('<div class="alert-body alert alert-' + params.template + ' alert-dismissible" role="alert"><button type="button" class="close"><span aria-hidden="true">&times;</span></button>' + params.title + '</div>');
  1226. if (params.close === false) {
  1227. $intemp.removeClass("alert-dismissible");
  1228. $intemp.find(".close").remove();
  1229. }else{
  1230. $intemp.find(".close").click(()=>{ $A.toast($intemp); });
  1231. }
  1232. if (params.fixed === true) {
  1233. _bg(1);
  1234. $intemp.attr("data-show-bg", "true");
  1235. }
  1236. container.append($intemp);
  1237. //
  1238. if (typeof params.timeout === 'number') {
  1239. setTimeout(()=>{ $A.toast($intemp) }, params.timeout)
  1240. }
  1241. setTimeout(()=>{ $intemp.addClass("enter") }, 10);
  1242. //
  1243. return $intemp;
  1244. }
  1245. });
  1246. /**
  1247. * =============================================================================
  1248. * ***************************** ajax ****************************
  1249. * =============================================================================
  1250. */
  1251. $.extend({
  1252. ajax(params) {
  1253. if (!params) return false;
  1254. if (typeof params.url === 'undefined') return false;
  1255. if (typeof params.data === 'undefined') params.data = {};
  1256. if (typeof params.cache === 'undefined') params.cache = false;
  1257. if (typeof params.method === 'undefined') params.method = 'GET';
  1258. if (typeof params.timeout === 'undefined') params.timeout = 30000;
  1259. if (typeof params.dataType === 'undefined') params.dataType = 'json';
  1260. if (typeof params.beforeSend === 'undefined') params.beforeSend = () => { };
  1261. if (typeof params.complete === 'undefined') params.complete = () => { };
  1262. if (typeof params.afterComplete === 'undefined') params.afterComplete = () => { };
  1263. if (typeof params.success === 'undefined') params.success = () => { };
  1264. if (typeof params.error === 'undefined') params.error = () => { };
  1265. //
  1266. let loadText = "数据加载中.....";
  1267. let busyNetwork = "网络繁忙,请稍后再试!";
  1268. if (typeof $A.app === 'object' && typeof $A.app.$L === 'function') {
  1269. loadText = $A.app.$L(loadText);
  1270. busyNetwork = $A.app.$L(busyNetwork);
  1271. }
  1272. //
  1273. let toastID = null, beforeTitle = '', errorTitle = '';
  1274. if (typeof $A.app === 'object' && typeof $A.app.$Message === 'object') {
  1275. if (typeof params.beforeSend === 'string') {
  1276. beforeTitle = params.beforeSend;
  1277. params.beforeSend = () => { toastID = $A.app.$Message.loading({content:beforeTitle, duration: 0}); };
  1278. }else if (params.beforeSend === true) {
  1279. params.beforeSend = () => { toastID = $A.app.$Message.loading({content:loadText, duration: 0}); };
  1280. }
  1281. if (typeof params.error === 'string') {
  1282. errorTitle = params.error;
  1283. params.error = () => { $A.app.$Message.error({content:errorTitle, duration: 5}); };
  1284. }else if (params.error === true) {
  1285. params.error = () => { $A.app.$Message.error({content:busyNetwork, duration: 5}); };
  1286. }
  1287. if (params.complete === true) {
  1288. params.complete = () => { toastID?toastID():'' };
  1289. }
  1290. }else{
  1291. if (typeof params.beforeSend === 'string') {
  1292. beforeTitle = params.beforeSend;
  1293. params.beforeSend = () => { toastID = $A.toast({title:beforeTitle, fixed: true, timeout: false}); };
  1294. }else if (params.beforeSend === true) {
  1295. params.beforeSend = () => { toastID = $A.toast({title:loadText, fixed: true, timeout: false}); };
  1296. }
  1297. if (typeof params.error === 'string') {
  1298. errorTitle = params.error;
  1299. params.error = () => { $A.toast(errorTitle, "danger"); };
  1300. }else if (params.error === true) {
  1301. params.error = () => { $A.toast(busyNetwork, "danger"); };
  1302. }
  1303. if (params.complete === true) {
  1304. params.complete = () => { toastID?$A.toast(toastID):'' };
  1305. }
  1306. }
  1307. //
  1308. if (typeof params.header !== 'object') params.header = {};
  1309. params.header['Content-Type'] = 'application/json';
  1310. params.header['language'] = window.localStorage['__language:type__'] || 'zh';
  1311. params.header['token'] = $A.token();
  1312. //
  1313. params.data['__Access-Control-Allow-Origin'] = true;
  1314. params.beforeSend();
  1315. $A.ihttp({
  1316. url: params.url,
  1317. data: params.data,
  1318. cache: params.cache,
  1319. headers: params.header,
  1320. method: params.method.toUpperCase(),
  1321. contentType: "OPTIONS",
  1322. crossDomain: true,
  1323. dataType: params.dataType,
  1324. timeout: params.timeout,
  1325. success: function(data, status, xhr) {
  1326. params.complete();
  1327. params.success(data, status, xhr);
  1328. params.afterComplete(true);
  1329. },
  1330. error: function(xhr, status) {
  1331. params.complete();
  1332. params.error(xhr, status);
  1333. params.afterComplete(false);
  1334. }
  1335. });
  1336. }
  1337. });
  1338. /**
  1339. * =============================================================================
  1340. * ***************************** manage assist ****************************
  1341. * =============================================================================
  1342. */
  1343. $.extend({
  1344. /**
  1345. * 对象中有Date格式的转成指定格式
  1346. * @param myObj
  1347. * @param format 默认格式:Y-m-d
  1348. * @returns {*}
  1349. */
  1350. date2string(myObj, format) {
  1351. if (myObj === null) {
  1352. return myObj;
  1353. }
  1354. if (typeof format === "undefined") {
  1355. format = "Y-m-d";
  1356. }
  1357. if (typeof myObj === "object") {
  1358. if (myObj instanceof Date) {
  1359. return $A.formatDate(format, myObj);
  1360. }
  1361. $A.each(myObj, (key, val)=>{
  1362. myObj[key] = $A.date2string(val, format);
  1363. });
  1364. return myObj;
  1365. }
  1366. return myObj;
  1367. },
  1368. /**
  1369. * 获取一些指定时间
  1370. * @param str
  1371. * @param retInt
  1372. * @returns {*|string}
  1373. */
  1374. getData(str, retInt = false) {
  1375. let now = new Date(); //当前日期
  1376. let nowDayOfWeek = now.getDay(); //今天本周的第几天
  1377. let nowDay = now.getDate(); //当前日
  1378. let nowMonth = now.getMonth(); //当前月
  1379. let nowYear = now.getYear(); //当前年
  1380. nowYear += (nowYear < 2000) ? 1900 : 0;
  1381. let lastMonthDate = new Date(); //上月日期
  1382. lastMonthDate.setDate(1);
  1383. lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
  1384. let lastMonth = lastMonthDate.getMonth();
  1385. let getQuarterStartMonth = () => {
  1386. let quarterStartMonth = 0;
  1387. if(nowMonth < 3) {
  1388. quarterStartMonth = 0;
  1389. }
  1390. if (2 < nowMonth && nowMonth < 6) {
  1391. quarterStartMonth = 3;
  1392. }
  1393. if (5 < nowMonth && nowMonth < 9) {
  1394. quarterStartMonth = 6;
  1395. }
  1396. if (nowMonth > 8) {
  1397. quarterStartMonth = 9;
  1398. }
  1399. return quarterStartMonth;
  1400. };
  1401. let getMonthDays = (myMonth) => {
  1402. let monthStartDate = new Date(nowYear, myMonth, 1);
  1403. let monthEndDate = new Date(nowYear, myMonth + 1, 1);
  1404. return (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
  1405. };
  1406. //
  1407. let time = now.getTime();
  1408. switch (str) {
  1409. case '今天':
  1410. time = now;
  1411. break;
  1412. case '昨天':
  1413. time = now - 86400000;
  1414. break;
  1415. case '前天':
  1416. time = now - 86400000 * 2;
  1417. break;
  1418. case '本周':
  1419. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
  1420. break;
  1421. case '本周结束':
  1422. time = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
  1423. break;
  1424. case '上周':
  1425. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
  1426. break;
  1427. case '上周结束':
  1428. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
  1429. break;
  1430. case '本周2':
  1431. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
  1432. break;
  1433. case '本周结束2':
  1434. time = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 1);
  1435. break;
  1436. case '上周2':
  1437. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7 + 1);
  1438. break;
  1439. case '上周结束2':
  1440. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1 + 1);
  1441. break;
  1442. case '本月':
  1443. time = new Date(nowYear, nowMonth, 1);
  1444. break;
  1445. case '本月结束':
  1446. time = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
  1447. break;
  1448. case '上个月':
  1449. time = new Date(nowYear, lastMonth, 1);
  1450. break;
  1451. case '上个月结束':
  1452. time = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
  1453. break;
  1454. case '本季度':
  1455. time = new Date(nowYear, getQuarterStartMonth(), 1);
  1456. break;
  1457. case '本季度结束':
  1458. let quarterEndMonth = getQuarterStartMonth() + 2;
  1459. time = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
  1460. break;
  1461. }
  1462. if (retInt === true) {
  1463. return time;
  1464. }
  1465. return $A.formatDate("Y-m-d", parseInt(time / 1000))
  1466. },
  1467. /**
  1468. * 字节转换
  1469. * @param bytes
  1470. * @returns {string}
  1471. */
  1472. bytesToSize(bytes) {
  1473. if (bytes === 0) return '0 B';
  1474. let k = 1024;
  1475. let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  1476. let i = Math.floor(Math.log(bytes) / Math.log(k));
  1477. if (typeof sizes[i] === "undefined") {
  1478. return '0 B';
  1479. }
  1480. return $A.runNum((bytes / Math.pow(k, i)), 2) + ' ' + sizes[i];
  1481. },
  1482. });
  1483. window.$A = $;
  1484. })(window, window.jQuery);