common.js 57 KB

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