common.js 58 KB

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