common.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  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 && typeof str === "object") {
  493. return str;
  494. }
  495. try{
  496. return JSON.parse(str);
  497. }catch (e) {
  498. return defaultVal ? defaultVal : {};
  499. }
  500. },
  501. /**
  502. * 将 JavaScript 值转换为 JSON 字符串(已try)
  503. * @param json
  504. * @param defaultVal
  505. * @returns {string}
  506. */
  507. jsonStringify(json, defaultVal) {
  508. if (typeof json !== 'object') {
  509. return json;
  510. }
  511. try{
  512. return JSON.stringify(json);
  513. }catch (e) {
  514. return defaultVal ? defaultVal : "";
  515. }
  516. },
  517. /**
  518. * 监听对象尺寸发生改变
  519. * @param obj
  520. * @param callback
  521. */
  522. resize(obj, callback) {
  523. let myObj = $A(obj);
  524. if (myObj.length === 0) return;
  525. let height = parseInt(myObj.outerHeight()),
  526. width = parseInt(myObj.outerWidth());
  527. let inter = setInterval(()=>{
  528. if (myObj.length === 0) clearInterval(inter);
  529. let tmpHeight = parseInt(myObj.outerHeight()),
  530. tmpWidth = parseInt(myObj.outerWidth());
  531. if (height !== tmpHeight || width !== tmpWidth) {
  532. height = tmpHeight;
  533. width = tmpWidth;
  534. console.log(width, height);
  535. if (typeof callback === 'function') callback();
  536. }
  537. }, 250);
  538. },
  539. /**
  540. * 是否IOS
  541. * @returns {boolean|string}
  542. */
  543. isIos() {
  544. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  545. return ua && /iphone|ipad|ipod|ios/.test(ua);
  546. },
  547. /**
  548. * 是否安卓
  549. * @returns {boolean|string}
  550. */
  551. isAndroid() {
  552. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  553. return ua && ua.indexOf('android') > 0;
  554. },
  555. /**
  556. * 是否微信
  557. * @returns {boolean}
  558. */
  559. isWeixin() {
  560. let ua = typeof window !== 'undefined' && window.navigator.userAgent.toLowerCase();
  561. return (ua.match(/MicroMessenger/i) + '' === 'micromessenger');
  562. },
  563. /**
  564. * 获取对象
  565. * @param obj
  566. * @param keys
  567. * @returns {string|*}
  568. */
  569. getObject(obj, keys) {
  570. let object = obj;
  571. if (this.count(obj) === 0 || this.count(keys) === 0) {
  572. return "";
  573. }
  574. let arr = keys.replace(/,/g, "|").replace(/\./g, "|").split("|");
  575. $A.each(arr, (index, key) => {
  576. object = typeof object[key] === "undefined" ? "" : object[key];
  577. });
  578. return object;
  579. },
  580. /**
  581. * 统计数组或对象长度
  582. * @param obj
  583. * @returns {number}
  584. */
  585. count(obj) {
  586. try {
  587. if (typeof obj === "undefined") {
  588. return 0;
  589. }
  590. if (typeof obj === "number") {
  591. obj+= "";
  592. }
  593. if (typeof obj.length === 'number') {
  594. return obj.length;
  595. } else {
  596. let i = 0, key;
  597. for (key in obj) {
  598. i++;
  599. }
  600. return i;
  601. }
  602. }catch (e) {
  603. return 0;
  604. }
  605. },
  606. /**
  607. * 将数组或对象内容部分拼成字符串
  608. * @param obj
  609. * @returns {string}
  610. */
  611. objImplode(obj) {
  612. if (obj === null) {
  613. return "";
  614. }
  615. let str = "";
  616. $A.each(obj, (key, val) => {
  617. if (val !== null) {
  618. if (typeof val === "object" && this.count(val) > 0) {
  619. str += this.objImplode(val);
  620. } else {
  621. str += String(val);
  622. }
  623. }
  624. });
  625. return str.replace(/\s/g, "").replace(/undefined/g, "");
  626. },
  627. /**
  628. * hash数组拼接
  629. * @param obj
  630. * @param filtrate
  631. * @returns {*}
  632. */
  633. hashSplice(obj, filtrate) {
  634. if (typeof obj !== 'object') {
  635. return obj;
  636. }
  637. let sObj = Object.keys(obj).sort(),
  638. text = "",
  639. sFiltrate = "," + filtrate + ",";
  640. for (let prop in sObj) {
  641. if (sObj.hasOwnProperty(prop)) {
  642. if (!$A.strExists(sFiltrate, "," + sObj[prop] + ",")) {
  643. if (text) text += "&";
  644. text += sObj[prop] + "=" + obj[sObj[prop]];
  645. }
  646. }
  647. }
  648. return text;
  649. },
  650. /**
  651. * 指定键获取hash参数
  652. * @param key
  653. * @returns {*}
  654. */
  655. hashParameter(key) {
  656. let params = this.hashParameterAll();
  657. return params[key];
  658. },
  659. hashParameterAll() {
  660. let hash = location.hash || "";
  661. let arr;
  662. if (this.strExists(hash, "?")) {
  663. arr = this.getMiddle(hash, "?").split("&");
  664. }else{
  665. arr = this.getMiddle(hash, "#").split("&");
  666. }
  667. let params = {};
  668. for (let i = 0; i < arr.length; i++) {
  669. let data = arr[i].split("=");
  670. if (data.length === 2) {
  671. params[data[0]] = data[1];
  672. }
  673. }
  674. return params;
  675. },
  676. /**
  677. * 链接字符串
  678. * @param value 第一个参数为连接符
  679. * @returns {string}
  680. */
  681. stringConnect(...value) {
  682. let s = null;
  683. let text = "";
  684. value.forEach((val) => {
  685. if (s === null) {
  686. s = val;
  687. }else if (val){
  688. if (val && text) text+= s;
  689. text+= val;
  690. }
  691. });
  692. return text;
  693. },
  694. /**
  695. * 判断两个对象是否相等
  696. * @param x
  697. * @param y
  698. * @returns {boolean}
  699. */
  700. objEquals(x, y) {
  701. let f1 = x instanceof Object;
  702. let f2 = y instanceof Object;
  703. if (!f1 || !f2) {
  704. return x === y
  705. }
  706. if (Object.keys(x).length !== Object.keys(y).length) {
  707. return false
  708. }
  709. for (let p in x) {
  710. if (x.hasOwnProperty(p)) {
  711. let a = x[p] instanceof Object;
  712. let b = y[p] instanceof Object;
  713. if (a && b) {
  714. if (!this.objEquals(x[p], y[p])) {
  715. return false;
  716. }
  717. } else if (x[p] != y[p]) {
  718. return false;
  719. }
  720. }
  721. }
  722. return true;
  723. },
  724. /**
  725. * 输入框内插入文本
  726. * @param object
  727. * @param content
  728. */
  729. insert2Input (object, content) {
  730. if (object === null || typeof object !== "object") return;
  731. if (typeof object.length === 'number' && object.length > 0) object = object[0];
  732. let ele = typeof object.$el === "object" ? $A(object.$el) : $A(object);
  733. if (ele.length === 0) return;
  734. let eleDom = ele[0];
  735. if (eleDom.tagName != "INPUT" && eleDom.tagName != "TEXTAREA") {
  736. if (ele.find("input").length === 0) {
  737. ele = ele.find("textarea");
  738. }else{
  739. ele = ele.find("input");
  740. }
  741. }
  742. if (ele.length === 0) return;
  743. eleDom = ele[0];
  744. if (eleDom.tagName != "INPUT" && eleDom.tagName != "TEXTAREA") return;
  745. let text = ele.val();
  746. let { selectionStart, selectionEnd } = eleDom;
  747. ele.val(`${text.substring(0, selectionStart)}${content}${text.substring(selectionEnd, text.length)}`);
  748. eleDom.dispatchEvent(new Event('input'));
  749. setTimeout(() => {
  750. if (eleDom.setSelectionRange) {
  751. let pos = text.substring(0, selectionStart).length + content.length;
  752. eleDom.focus();
  753. eleDom.setSelectionRange(pos, pos);
  754. }
  755. }, 10);
  756. },
  757. /**
  758. * iOS上虚拟键盘引起的触控错位
  759. */
  760. iOSKeyboardFixer() {
  761. if (!this.isIos()) {
  762. return;
  763. }
  764. document.body.scrollTop = document.body.scrollTop + 1;
  765. document.body.scrollTop = document.body.scrollTop - 1;
  766. },
  767. autoDevwid(width) {
  768. let _width = width || 640;
  769. new function () {
  770. let _self = this;
  771. _self.width = _width; //设置默认最大宽度
  772. _self.fontSize = 30; //默认字体大小
  773. _self.widthProportion = function () {
  774. let p = (document.body && document.body.clientWidth || document.getElementsByTagName("html")[0].offsetWidth) / _self.width;
  775. return p > 1 ? 1 : p < 0.38 ? 0.38 : p;
  776. };
  777. _self.changePage = function () {
  778. document.getElementsByTagName("html")[0].setAttribute("style", "font-size:" + _self.widthProportion() * _self.fontSize + "px !important");
  779. };
  780. _self.changePage();
  781. window.addEventListener('resize', function () {
  782. _self.changePage();
  783. }, false);
  784. };
  785. //
  786. let scale = $A(window).width() / _width;
  787. $A(".__auto").each(function () {
  788. if ($A(this).attr("data-original") !== "1") {
  789. $A(this).attr("data-original-top", parseInt($A(this).css("top")));
  790. $A(this).attr("data-original-right", parseInt($A(this).css("right")));
  791. $A(this).attr("data-original-bottom", parseInt($A(this).css("bottom")));
  792. $A(this).attr("data-original-left", parseInt($A(this).css("left")));
  793. $A(this).attr("data-original-width", parseInt($A(this).css("width")));
  794. $A(this).attr("data-original-height", parseInt($A(this).css("height")));
  795. $A(this).attr("data-original-line-height", parseInt($A(this).css("line-height")));
  796. $A(this).attr("data-original", "1");
  797. }
  798. let _t = parseInt($A(this).attr("data-original-top"));
  799. let _r = parseInt($A(this).attr("data-original-right"));
  800. let _b = parseInt($A(this).attr("data-original-bottom"));
  801. let _l = parseInt($A(this).attr("data-original-left"));
  802. let _w = parseInt($A(this).attr("data-original-width"));
  803. let _h = parseInt($A(this).attr("data-original-height"));
  804. let _lh = parseInt($A(this).attr("data-original-line-height"));
  805. //
  806. let _css = {};
  807. if (_t > 0) _css['top'] = _t * scale;
  808. if (_r > 0) _css['right'] = _r * scale;
  809. if (_b > 0) _css['bottom'] = _b * scale;
  810. if (_l > 0) _css['left'] = _l * scale;
  811. if (_w > 0) _css['width'] = _w * scale;
  812. if (_h > 0) _css['height'] = _h * scale;
  813. if (_lh > 0) _css['line-height'] = (_lh * scale) + 'px';
  814. $A(this).css(_css);
  815. });
  816. return scale;
  817. }
  818. });
  819. /**
  820. * =============================================================================
  821. * **************************** ihttp ****************************
  822. * =============================================================================
  823. */
  824. $.extend({
  825. serializeObject (obj, parents) {
  826. if (typeof obj === 'string') return obj;
  827. let resultArray = [];
  828. let separator = '&';
  829. parents = parents || [];
  830. let newParents;
  831. function var_name(name) {
  832. if (parents.length > 0) {
  833. let _parents = '';
  834. for (let j = 0; j < parents.length; j++) {
  835. if (j === 0) _parents += parents[j];
  836. else _parents += '[' + encodeURIComponent(parents[j]) + ']';
  837. }
  838. return _parents + '[' + encodeURIComponent(name) + ']';
  839. }
  840. else {
  841. return encodeURIComponent(name);
  842. }
  843. }
  844. function var_value(value) {
  845. return encodeURIComponent(value);
  846. }
  847. for (let prop in obj) {
  848. if (obj.hasOwnProperty(prop)) {
  849. let toPush;
  850. if (Array.isArray(obj[prop])) {
  851. toPush = [];
  852. for (let i = 0; i < obj[prop].length; i++) {
  853. if (!Array.isArray(obj[prop][i]) && typeof obj[prop][i] === 'object') {
  854. newParents = parents.slice();
  855. newParents.push(prop);
  856. newParents.push(i + '');
  857. toPush.push($.serializeObject(obj[prop][i], newParents));
  858. }
  859. else {
  860. toPush.push(var_name(prop) + '[]=' + var_value(obj[prop][i]));
  861. }
  862. }
  863. if (toPush.length > 0) resultArray.push(toPush.join(separator));
  864. }
  865. else if (obj[prop] === null) {
  866. resultArray.push(var_name(prop) + '=');
  867. }
  868. else if (typeof obj[prop] === 'object') {
  869. // Object, convert to named array
  870. newParents = parents.slice();
  871. newParents.push(prop);
  872. toPush = $.serializeObject(obj[prop], newParents);
  873. if (toPush !== '') resultArray.push(toPush);
  874. }
  875. else if (typeof obj[prop] !== 'undefined' && obj[prop] !== '') {
  876. // Should be string or plain value
  877. resultArray.push(var_name(prop) + '=' + var_value(obj[prop]));
  878. }
  879. else if (obj[prop] === '') resultArray.push(var_name(prop));
  880. }
  881. }
  882. return resultArray.join(separator);
  883. },
  884. // Global Ajax Setup
  885. globalAjaxOptions: {},
  886. ajaxSetup (options) {
  887. if (options.type) options.method = options.type;
  888. $.each(options, function (optionName, optionValue) {
  889. $.globalAjaxOptions[optionName] = optionValue;
  890. });
  891. },
  892. // Ajax
  893. _jsonpRequests: 0,
  894. ihttp(options) {
  895. let defaults = {
  896. method: 'GET',
  897. data: false,
  898. async: true,
  899. cache: true,
  900. user: '',
  901. password: '',
  902. headers: {},
  903. xhrFields: {},
  904. statusCode: {},
  905. processData: true,
  906. dataType: 'text',
  907. contentType: 'application/x-www-form-urlencoded',
  908. timeout: 0
  909. };
  910. let callbacks = ['beforeSend', 'error', 'complete', 'success', 'statusCode'];
  911. //For jQuery guys
  912. if (options.type) options.method = options.type;
  913. // Merge global and defaults
  914. $.each($.globalAjaxOptions, function (globalOptionName, globalOptionValue) {
  915. if (callbacks.indexOf(globalOptionName) < 0) defaults[globalOptionName] = globalOptionValue;
  916. });
  917. // Function to run XHR callbacks and events
  918. function fireAjaxCallback(eventName, eventData, callbackName) {
  919. let a = arguments;
  920. if (eventName) $(document).trigger(eventName, eventData);
  921. if (callbackName) {
  922. // Global callback
  923. if (callbackName in $.globalAjaxOptions) $.globalAjaxOptions[callbackName](a[3], a[4], a[5], a[6]);
  924. // Options callback
  925. if (options[callbackName]) options[callbackName](a[3], a[4], a[5], a[6]);
  926. }
  927. }
  928. // Merge options and defaults
  929. $.each(defaults, function (prop, defaultValue) {
  930. if (!(prop in options)) options[prop] = defaultValue;
  931. });
  932. // Default URL
  933. if (!options.url) {
  934. options.url = window.location.toString();
  935. }
  936. // Parameters Prefix
  937. let paramsPrefix = options.url.indexOf('?') >= 0 ? '&' : '?';
  938. // UC method
  939. let _method = options.method.toUpperCase();
  940. // Data to modify GET URL
  941. if ((_method === 'GET' || _method === 'HEAD' || _method === 'OPTIONS' || _method === 'DELETE') && options.data) {
  942. let stringData;
  943. if (typeof options.data === 'string') {
  944. // Should be key=value string
  945. if (options.data.indexOf('?') >= 0) stringData = options.data.split('?')[1];
  946. else stringData = options.data;
  947. }
  948. else {
  949. // Should be key=value object
  950. stringData = $.serializeObject(options.data);
  951. }
  952. if (stringData.length) {
  953. options.url += paramsPrefix + stringData;
  954. if (paramsPrefix === '?') paramsPrefix = '&';
  955. }
  956. }
  957. // JSONP
  958. if (options.dataType === 'json' && options.url.indexOf('callback=') >= 0) {
  959. let callbackName = 'f7jsonp_' + Date.now() + ($._jsonpRequests++);
  960. let abortTimeout;
  961. let callbackSplit = options.url.split('callback=');
  962. let requestUrl = callbackSplit[0] + 'callback=' + callbackName;
  963. if (callbackSplit[1].indexOf('&') >= 0) {
  964. let addVars = callbackSplit[1].split('&').filter(function (el) {
  965. return el.indexOf('=') > 0;
  966. }).join('&');
  967. if (addVars.length > 0) requestUrl += '&' + addVars;
  968. }
  969. // Create script
  970. let script = document.createElement('script');
  971. script.type = 'text/javascript';
  972. script.onerror = function () {
  973. clearTimeout(abortTimeout);
  974. fireAjaxCallback(undefined, undefined, 'error', null, 'scripterror');
  975. fireAjaxCallback('ajaxComplete ajax:complete', {scripterror: true}, 'complete', null, 'scripterror');
  976. };
  977. script.src = requestUrl;
  978. // Handler
  979. window[callbackName] = function (data) {
  980. clearTimeout(abortTimeout);
  981. fireAjaxCallback(undefined, undefined, 'success', data);
  982. script.parentNode.removeChild(script);
  983. script = null;
  984. delete window[callbackName];
  985. };
  986. document.querySelector('head').appendChild(script);
  987. if (options.timeout > 0) {
  988. abortTimeout = setTimeout(function () {
  989. script.parentNode.removeChild(script);
  990. script = null;
  991. fireAjaxCallback(undefined, undefined, 'error', null, 'timeout');
  992. }, options.timeout);
  993. }
  994. return;
  995. }
  996. // Cache for GET/HEAD requests
  997. if (_method === 'GET' || _method === 'HEAD' || _method === 'OPTIONS' || _method === 'DELETE') {
  998. if (options.cache === false) {
  999. options.url += (paramsPrefix + '_nocache=' + Date.now());
  1000. }
  1001. }
  1002. // Create XHR
  1003. let xhr = new XMLHttpRequest();
  1004. // Save Request URL
  1005. xhr.requestUrl = options.url;
  1006. xhr.requestParameters = options;
  1007. // Open XHR
  1008. xhr.open(_method, options.url, options.async, options.user, options.password);
  1009. // Create POST Data
  1010. let postData = null;
  1011. if ((_method === 'POST' || _method === 'PUT' || _method === 'PATCH') && options.data) {
  1012. if (options.processData) {
  1013. let postDataInstances = [ArrayBuffer, Blob, Document, FormData];
  1014. // Post Data
  1015. if (postDataInstances.indexOf(options.data.constructor) >= 0) {
  1016. postData = options.data;
  1017. }
  1018. else {
  1019. // POST Headers
  1020. let boundary = '---------------------------' + Date.now().toString(16);
  1021. if (options.contentType === 'multipart\/form-data') {
  1022. xhr.setRequestHeader('Content-Type', 'multipart\/form-data; boundary=' + boundary);
  1023. }
  1024. else {
  1025. xhr.setRequestHeader('Content-Type', options.contentType);
  1026. }
  1027. postData = '';
  1028. let _data = $.serializeObject(options.data);
  1029. if (options.contentType === 'multipart\/form-data') {
  1030. boundary = '---------------------------' + Date.now().toString(16);
  1031. _data = _data.split('&');
  1032. let _newData = [];
  1033. for (let i = 0; i < _data.length; i++) {
  1034. _newData.push('Content-Disposition: form-data; name="' + _data[i].split('=')[0] + '"\r\n\r\n' + _data[i].split('=')[1] + '\r\n');
  1035. }
  1036. postData = '--' + boundary + '\r\n' + _newData.join('--' + boundary + '\r\n') + '--' + boundary + '--\r\n';
  1037. }
  1038. else {
  1039. postData = _data;
  1040. }
  1041. }
  1042. }
  1043. else {
  1044. postData = options.data;
  1045. }
  1046. }
  1047. // Additional headers
  1048. if (options.headers) {
  1049. $.each(options.headers, function (headerName, headerCallback) {
  1050. xhr.setRequestHeader(headerName, headerCallback);
  1051. });
  1052. }
  1053. // Check for crossDomain
  1054. if (typeof options.crossDomain === 'undefined') {
  1055. options.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(options.url) && RegExp.$2 !== window.location.host;
  1056. }
  1057. if (!options.crossDomain) {
  1058. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  1059. }
  1060. if (options.xhrFields) {
  1061. $.each(options.xhrFields, function (fieldName, fieldValue) {
  1062. xhr[fieldName] = fieldValue;
  1063. });
  1064. }
  1065. let xhrTimeout;
  1066. // Handle XHR
  1067. xhr.onload = function (e) {
  1068. if (xhrTimeout) clearTimeout(xhrTimeout);
  1069. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
  1070. let responseData;
  1071. if (options.dataType === 'json') {
  1072. try {
  1073. responseData = JSON.parse(xhr.responseText);
  1074. fireAjaxCallback('ajaxSuccess ajax:success', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
  1075. }
  1076. catch (err) {
  1077. fireAjaxCallback('ajaxError ajax:error', {
  1078. xhr: xhr,
  1079. parseerror: true
  1080. }, 'error', xhr, 'parseerror');
  1081. }
  1082. }
  1083. else {
  1084. responseData = xhr.responseType === 'text' || xhr.responseType === '' ? xhr.responseText : xhr.response;
  1085. fireAjaxCallback('ajaxSuccess ajax:success', {xhr: xhr}, 'success', responseData, xhr.status, xhr);
  1086. }
  1087. }
  1088. else {
  1089. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr}, 'error', xhr, xhr.status);
  1090. }
  1091. if (options.statusCode) {
  1092. if ($.globalAjaxOptions.statusCode && $.globalAjaxOptions.statusCode[xhr.status]) $.globalAjaxOptions.statusCode[xhr.status](xhr);
  1093. if (options.statusCode[xhr.status]) options.statusCode[xhr.status](xhr);
  1094. }
  1095. fireAjaxCallback('ajaxComplete ajax:complete', {xhr: xhr}, 'complete', xhr, xhr.status);
  1096. };
  1097. xhr.onerror = function (e) {
  1098. if (xhrTimeout) clearTimeout(xhrTimeout);
  1099. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr}, 'error', xhr, xhr.status);
  1100. fireAjaxCallback('ajaxComplete ajax:complete', {xhr: xhr, error: true}, 'complete', xhr, 'error');
  1101. };
  1102. // Ajax start callback
  1103. fireAjaxCallback('ajaxStart ajax:start', {xhr: xhr}, 'start', xhr);
  1104. fireAjaxCallback(undefined, undefined, 'beforeSend', xhr);
  1105. // Timeout
  1106. if (options.timeout > 0) {
  1107. xhr.onabort = function () {
  1108. if (xhrTimeout) clearTimeout(xhrTimeout);
  1109. };
  1110. xhrTimeout = setTimeout(function () {
  1111. xhr.abort();
  1112. fireAjaxCallback('ajaxError ajax:error', {xhr: xhr, timeout: true}, 'error', xhr, 'timeout');
  1113. fireAjaxCallback('ajaxComplete ajax:complete', {
  1114. xhr: xhr,
  1115. timeout: true
  1116. }, 'complete', xhr, 'timeout');
  1117. }, options.timeout);
  1118. }
  1119. // Send XHR
  1120. xhr.send(postData);
  1121. // Return XHR object
  1122. return xhr;
  1123. }
  1124. });
  1125. /**
  1126. * =============================================================================
  1127. * ************************* Bootstrap extend ************************
  1128. * =============================================================================
  1129. */
  1130. $.extend({
  1131. toast(params, timeout, template) {
  1132. let _bg = function(num) {
  1133. let container = $A(".__bootstrap_toast_container");
  1134. if (container.length > 0) {
  1135. let bgobj = container.find(".alert-bg");
  1136. let bgnum = parseInt(bgobj.attr("data-num"));
  1137. bgnum+= num;
  1138. bgobj.attr("data-num", bgnum);
  1139. if (bgnum > 0) {
  1140. bgobj.show();
  1141. }else{
  1142. bgobj.hide();
  1143. }
  1144. }
  1145. };
  1146. if (!params) return false;
  1147. if (typeof params === 'object' && params.length > 0) {
  1148. if (params.attr("data-show-bg") === "true") _bg(-1);
  1149. params.css({width: Math.ceil(params.outerWidth())});
  1150. params.addClass("leave");
  1151. setTimeout(()=>{ params.remove() }, 300);
  1152. return;
  1153. }
  1154. if (typeof timeout === 'string') {
  1155. template = timeout;
  1156. timeout = 2500;
  1157. }
  1158. if (typeof params === 'string') params = { title: params };
  1159. if (typeof params.timeout === 'undefined') params.timeout = 2500;
  1160. if (typeof params.template === 'undefined') params.template = 'success';
  1161. if (typeof params.fixed === 'undefined') params.fixed = false;
  1162. if (typeof params.close === 'undefined') params.close = true;
  1163. if (typeof timeout !== 'undefined') params.timeout = timeout;
  1164. if (typeof template !== 'undefined') params.template = template;
  1165. //
  1166. let container = $A(".__bootstrap_toast_container");
  1167. if (container.length === 0) {
  1168. $A("<style>")
  1169. .attr({type: "text/css"})
  1170. .html(
  1171. ".__bootstrap_toast_container{position:fixed;z-index:99999;top:5%;right:5%;padding:0;text-align:right;}" +
  1172. ".__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);}" +
  1173. ".__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;}" +
  1174. ".__bootstrap_toast_container .alert-body.enter{opacity:1;transform:translate3d(0,0,0);-webkit-transform:translate3d(0,0,0);}" +
  1175. ".__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;}" +
  1176. "")
  1177. .appendTo("head");
  1178. $A("body").append("<div class='__bootstrap_toast_container'><div class='alert-bg' data-num='0'></div></div>");
  1179. container = $A(".__bootstrap_toast_container");
  1180. }
  1181. //
  1182. 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>');
  1183. if (params.close === false) {
  1184. $intemp.removeClass("alert-dismissible");
  1185. $intemp.find(".close").remove();
  1186. }else{
  1187. $intemp.find(".close").click(()=>{ $A.toast($intemp); });
  1188. }
  1189. if (params.fixed === true) {
  1190. _bg(1);
  1191. $intemp.attr("data-show-bg", "true");
  1192. }
  1193. container.append($intemp);
  1194. //
  1195. if (typeof params.timeout === 'number') {
  1196. setTimeout(()=>{ $A.toast($intemp) }, params.timeout)
  1197. }
  1198. setTimeout(()=>{ $intemp.addClass("enter") }, 10);
  1199. //
  1200. return $intemp;
  1201. }
  1202. });
  1203. /**
  1204. * =============================================================================
  1205. * ***************************** ajax ****************************
  1206. * =============================================================================
  1207. */
  1208. $.extend({
  1209. ajax(params) {
  1210. if (!params) return false;
  1211. if (typeof params.url === 'undefined') return false;
  1212. if (typeof params.data === 'undefined') params.data = {};
  1213. if (typeof params.cache === 'undefined') params.cache = false;
  1214. if (typeof params.method === 'undefined') params.method = 'GET';
  1215. if (typeof params.timeout === 'undefined') params.timeout = 30000;
  1216. if (typeof params.dataType === 'undefined') params.dataType = 'json';
  1217. if (typeof params.beforeSend === 'undefined') params.beforeSend = () => { };
  1218. if (typeof params.complete === 'undefined') params.complete = () => { };
  1219. if (typeof params.afterComplete === 'undefined') params.afterComplete = () => { };
  1220. if (typeof params.success === 'undefined') params.success = () => { };
  1221. if (typeof params.error === 'undefined') params.error = () => { };
  1222. //
  1223. let loadText = "数据加载中.....";
  1224. let busyNetwork = "网络繁忙,请稍后再试!";
  1225. if (typeof $A.app === 'object' && typeof $A.app.$L === 'function') {
  1226. loadText = $A.app.$L(loadText);
  1227. busyNetwork = $A.app.$L(busyNetwork);
  1228. }
  1229. //
  1230. let toastID = null, beforeTitle = '', errorTitle = '';
  1231. if (typeof $A.app === 'object' && typeof $A.app.$Message === 'object') {
  1232. if (typeof params.beforeSend === 'string') {
  1233. beforeTitle = params.beforeSend;
  1234. params.beforeSend = () => { toastID = $A.app.$Message.loading({content:beforeTitle, duration: 0}); };
  1235. }else if (params.beforeSend === true) {
  1236. params.beforeSend = () => { toastID = $A.app.$Message.loading({content:loadText, duration: 0}); };
  1237. }
  1238. if (typeof params.error === 'string') {
  1239. errorTitle = params.error;
  1240. params.error = () => { $A.app.$Message.error({content:errorTitle, duration: 5}); };
  1241. }else if (params.error === true) {
  1242. params.error = () => { $A.app.$Message.error({content:busyNetwork, duration: 5}); };
  1243. }
  1244. if (params.complete === true) {
  1245. params.complete = () => { toastID?toastID():'' };
  1246. }
  1247. }else{
  1248. if (typeof params.beforeSend === 'string') {
  1249. beforeTitle = params.beforeSend;
  1250. params.beforeSend = () => { toastID = $A.toast({title:beforeTitle, fixed: true, timeout: false}); };
  1251. }else if (params.beforeSend === true) {
  1252. params.beforeSend = () => { toastID = $A.toast({title:loadText, fixed: true, timeout: false}); };
  1253. }
  1254. if (typeof params.error === 'string') {
  1255. errorTitle = params.error;
  1256. params.error = () => { $A.toast(errorTitle, "danger"); };
  1257. }else if (params.error === true) {
  1258. params.error = () => { $A.toast(busyNetwork, "danger"); };
  1259. }
  1260. if (params.complete === true) {
  1261. params.complete = () => { toastID?$A.toast(toastID):'' };
  1262. }
  1263. }
  1264. //
  1265. if (typeof params.header !== 'object') params.header = {};
  1266. params.header['Content-Type'] = 'application/json';
  1267. params.header['language'] = window.localStorage['__language:type__'] || 'zh';
  1268. params.header['token'] = $A.token();
  1269. //渠道
  1270. let channel = $A.hashParameter('channel');
  1271. if (!$A.ishave(channel)) {
  1272. channel = $A.storage('platform-channel');
  1273. }else{
  1274. $A.storage('platform-channel', channel);
  1275. }
  1276. if (!$A.ishave(channel)) {
  1277. channel = "none";
  1278. }
  1279. params.header['platform-channel'] = channel;
  1280. //
  1281. params.data['__Access-Control-Allow-Origin'] = true;
  1282. params.beforeSend();
  1283. $A.ihttp({
  1284. url: params.url,
  1285. data: params.data,
  1286. cache: params.cache,
  1287. headers: params.header,
  1288. method: params.method.toUpperCase(),
  1289. contentType: "OPTIONS",
  1290. crossDomain: true,
  1291. dataType: params.dataType,
  1292. timeout: params.timeout,
  1293. success: function(data, status, xhr) {
  1294. params.complete();
  1295. params.success(data, status, xhr);
  1296. params.afterComplete(true);
  1297. },
  1298. error: function(xhr, status) {
  1299. params.complete();
  1300. params.error(xhr, status);
  1301. params.afterComplete(false);
  1302. }
  1303. });
  1304. }
  1305. });
  1306. /**
  1307. * =============================================================================
  1308. * ***************************** manage assist ****************************
  1309. * =============================================================================
  1310. */
  1311. $.extend({
  1312. /**
  1313. * 对象中有Date格式的转成指定格式
  1314. * @param myObj
  1315. * @param format 默认格式:Y-m-d
  1316. * @returns {*}
  1317. */
  1318. date2string(myObj, format) {
  1319. if (myObj === null) {
  1320. return myObj;
  1321. }
  1322. if (typeof format === "undefined") {
  1323. format = "Y-m-d";
  1324. }
  1325. if (typeof myObj === "object") {
  1326. if (myObj instanceof Date) {
  1327. return $A.formatDate(format, myObj);
  1328. }
  1329. $A.each(myObj, (key, val)=>{
  1330. myObj[key] = $A.date2string(val, format);
  1331. });
  1332. return myObj;
  1333. }
  1334. return myObj;
  1335. },
  1336. /**
  1337. * 获取一些指定时间
  1338. * @param str
  1339. * @param retInt
  1340. * @returns {*|string}
  1341. */
  1342. getData(str, retInt = false) {
  1343. let now = new Date(); //当前日期
  1344. let nowDayOfWeek = now.getDay(); //今天本周的第几天
  1345. let nowDay = now.getDate(); //当前日
  1346. let nowMonth = now.getMonth(); //当前月
  1347. let nowYear = now.getYear(); //当前年
  1348. nowYear += (nowYear < 2000) ? 1900 : 0;
  1349. let lastMonthDate = new Date(); //上月日期
  1350. lastMonthDate.setDate(1);
  1351. lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
  1352. let lastMonth = lastMonthDate.getMonth();
  1353. let getQuarterStartMonth = () => {
  1354. let quarterStartMonth = 0;
  1355. if(nowMonth < 3) {
  1356. quarterStartMonth = 0;
  1357. }
  1358. if (2 < nowMonth && nowMonth < 6) {
  1359. quarterStartMonth = 3;
  1360. }
  1361. if (5 < nowMonth && nowMonth < 9) {
  1362. quarterStartMonth = 6;
  1363. }
  1364. if (nowMonth > 8) {
  1365. quarterStartMonth = 9;
  1366. }
  1367. return quarterStartMonth;
  1368. };
  1369. let getMonthDays = (myMonth) => {
  1370. let monthStartDate = new Date(nowYear, myMonth, 1);
  1371. let monthEndDate = new Date(nowYear, myMonth + 1, 1);
  1372. return (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
  1373. };
  1374. //
  1375. let time = now.getTime();
  1376. switch (str) {
  1377. case '今天':
  1378. time = now;
  1379. break;
  1380. case '昨天':
  1381. time = now - 86400000;
  1382. break;
  1383. case '前天':
  1384. time = now - 86400000 * 2;
  1385. break;
  1386. case '本周':
  1387. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
  1388. break;
  1389. case '本周结束':
  1390. time = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
  1391. break;
  1392. case '上周':
  1393. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
  1394. break;
  1395. case '上周结束':
  1396. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
  1397. break;
  1398. case '本周2':
  1399. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
  1400. break;
  1401. case '本周结束2':
  1402. time = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 1);
  1403. break;
  1404. case '上周2':
  1405. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7 + 1);
  1406. break;
  1407. case '上周结束2':
  1408. time = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1 + 1);
  1409. break;
  1410. case '本月':
  1411. time = new Date(nowYear, nowMonth, 1);
  1412. break;
  1413. case '本月结束':
  1414. time = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
  1415. break;
  1416. case '上个月':
  1417. time = new Date(nowYear, lastMonth, 1);
  1418. break;
  1419. case '上个月结束':
  1420. time = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
  1421. break;
  1422. case '本季度':
  1423. time = new Date(nowYear, getQuarterStartMonth(), 1);
  1424. break;
  1425. case '本季度结束':
  1426. let quarterEndMonth = getQuarterStartMonth() + 2;
  1427. time = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
  1428. break;
  1429. }
  1430. if (retInt === true) {
  1431. return time;
  1432. }
  1433. return $A.formatDate("Y-m-d", parseInt(time / 1000))
  1434. },
  1435. /**
  1436. * 字节转换
  1437. * @param bytes
  1438. * @returns {string}
  1439. */
  1440. bytesToSize(bytes) {
  1441. if (bytes === 0) return '0 B';
  1442. let k = 1024;
  1443. let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  1444. let i = Math.floor(Math.log(bytes) / Math.log(k));
  1445. if (typeof sizes[i] === "undefined") {
  1446. return '0 B';
  1447. }
  1448. return $A.runNum((bytes / Math.pow(k, i)), 2) + ' ' + sizes[i];
  1449. },
  1450. });
  1451. window.$A = $;
  1452. })(window, window.jQuery);