common.js 58 KB

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