common.js 57 KB

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