common.js 57 KB

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