common.js 56 KB

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