lib.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import $ from 'jquery';
  2. import WjySdk from 'extSdk';
  3. import {Indicator, Toast, MessageBox} from 'mint-ui';
  4. const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1; //android终端
  5. const isiOS = navigator.userAgent.match(/(iPhone|iPod|iPad);?/i); //ios终端
  6. var lib = {};
  7. var BDY = {};
  8. BDY.params = [];
  9. BDY.timeout = [];
  10. BDY.interval = [];
  11. BDY.xhrs = [];
  12. BDY.xhrCount = 0;
  13. BDY.appId = 4;
  14. //+++++++++++++++++++++++++++ hash 参数控制 +++++++++++++++++++++++++++++++++++++
  15. /**
  16. * js获取url参数的值,(函数内部decodeURIComponent值)
  17. * @author benzhan
  18. * @param {string} name 参数名
  19. * @return {string} 参数值
  20. */
  21. function getParam(name) {
  22. //先获取#后面的参数
  23. var str = document.location.hash.substr(2);
  24. var value = getParam2(name, str);
  25. if (value == null) {
  26. str = document.location.search.substr(1);
  27. value = getParam2(name, str);
  28. }
  29. return value;
  30. };
  31. function getParam2(name, str) {
  32. //获取参数name的值
  33. var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
  34. //再获取?后面的参数
  35. var r = str.match(reg);
  36. if (r != null) {
  37. try {
  38. return decodeURIComponent(r[2]);
  39. } catch (e) {
  40. return null;
  41. }
  42. }
  43. return null;
  44. };
  45. /**
  46. * js设置url中hash参数的值, (函数内部encodeURIComponent传入的value参数)
  47. * @author benzhan
  48. * @param {string} name 参数名
  49. * @return {string} value 参数值
  50. */
  51. function setParam(name, value, causeHistory) {
  52. var search = document.location.search.substr(1);
  53. if ($.type(name) === "object") {
  54. // 支持 setParam(value, causeHistory)的写法
  55. causeHistory = value;
  56. value = name;
  57. for (var key in value) {
  58. search = setParam2(key, value[key], search);
  59. }
  60. } else {
  61. search = setParam2(name, value, search);
  62. }
  63. if (causeHistory) {
  64. if (history.pushState) {
  65. history.pushState({}, null, "?" + search);
  66. } else {
  67. document.location.search = search;
  68. }
  69. } else {
  70. if (history.replaceState) {
  71. history.replaceState({}, null, "?" + search);
  72. } else {
  73. console.error("history.replaceState:" + history.replaceState);
  74. }
  75. }
  76. };
  77. function setParam2(name, value, str) {
  78. if ($.type(name) === "object") {
  79. // 支持 setParam(value, causeHistory)的写法
  80. str = value;
  81. value = name;
  82. for (var key in value) {
  83. str = setParam2(key, value[key], str);
  84. }
  85. return str;
  86. } else {
  87. var prefix = str ? "&" : "";
  88. var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
  89. var r = str.match(reg);
  90. value = encodeURIComponent(value);
  91. if (r) {
  92. if (r[2]) {
  93. var newValue = r[0].replace(r[2], value);
  94. str = str.replace(r[0], newValue);
  95. } else {
  96. var newValue = prefix + name + "=" + value + "&";
  97. str = str.replace(r[0], newValue);
  98. }
  99. } else {
  100. var newValue = prefix + name + "=" + value;
  101. str += newValue;
  102. }
  103. return str;
  104. }
  105. };
  106. function removeParam(name, causeHistory) {
  107. var search = document.location.search.substr(1);
  108. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  109. r = search.match(reg);
  110. if (r) {
  111. if (r[1] && r[3]) {
  112. search = search.replace(r[0], '&');
  113. } else {
  114. search = search.replace(r[0], '');
  115. }
  116. }
  117. if (causeHistory) {
  118. document.location.search = search;
  119. } else {
  120. if (history.replaceState) {
  121. history.replaceState({}, null, "?" + search);
  122. } else {
  123. console.error("history.replaceState:" + history.replaceState);
  124. }
  125. }
  126. };
  127. function parseHash(strUrl) {
  128. strUrl = strUrl ? strUrl : document.location.search.substr(1);
  129. //获取参数name的值
  130. var reg = new RegExp("(^|!|#|&|\\?)(\\w*)=([^&]*)", "g");
  131. //先获取#后面的参数
  132. var r = reg.exec(strUrl);
  133. var datas = {};
  134. var i = 0;
  135. while (r != null) {
  136. datas[r[2]] = decodeURIComponent(r[3]);
  137. r = reg.exec(strUrl);
  138. }
  139. return datas;
  140. };
  141. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  142. // +++++++++++++++++++++++++++ get 和 post +++++++++++++++++++++++++++++++++++++
  143. function _getDefaultData(data) {
  144. data = data || {};
  145. var ouid = getCookie('ouid');
  146. ouid && (data.ouid = ouid);
  147. var defaultKeys = ['gym_id'];
  148. for (var i in defaultKeys) {
  149. var key = defaultKeys[i];
  150. var value = getLocalData(key);
  151. if (value && value != "undefined") {
  152. data[key] = value;
  153. }
  154. }
  155. for (var k in data) {
  156. var v = data[k];
  157. if (v == null || typeof v === 'undefined') {
  158. delete data[k];
  159. } else {
  160. if (typeof v === 'string') {
  161. data[k] = $.trim(v);
  162. }
  163. }
  164. }
  165. return data;
  166. }
  167. /**
  168. * option object {'cache', 'loading', 'onTimeout'}
  169. * cache为every、once
  170. */
  171. function post(url, data, callback, option) {
  172. option = option || {};
  173. // 支持postCross(url, callback)的写法;
  174. if ( typeof data == 'function') {
  175. option = callback || {};
  176. callback = data;
  177. data = {};
  178. }
  179. data = _getDefaultData(data);
  180. var xhr = new XMLHttpRequest();
  181. BDY.xhrs.push(xhr);
  182. BDY.xhrCount++;
  183. xhr.index = BDY.xhrs.length;
  184. xhr.open("POST", url);
  185. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  186. xhr.withCredentials = true;
  187. // 兼容ios6.0会缓存
  188. if (window.KalaGame) {
  189. xhr.setRequestHeader("Cache-Control", "no-cache");
  190. }
  191. data = $.param(data);
  192. //获取cache的key
  193. if (option['cache']) {
  194. var cacheKey = 'ajaxCache-' + url + '?' + data;
  195. //如果有cache则不出现loading
  196. var isCached = _loadAjaxCache(cacheKey, callback);
  197. if (isCached) {
  198. option['loading'] = false;
  199. if (option['cache'] == "must") {
  200. return;
  201. }
  202. }
  203. }
  204. if (option['loading']) {
  205. xhr.timeout = 15000;
  206. showLoading();
  207. }
  208. xhr.send(data);
  209. xhr.ontimeout = option['onTimeout'] || function () {
  210. callback && callback({result:0, code:-11, msg:"网络超时,请重试"});
  211. };
  212. // 响应处理
  213. xhr.onload = function() {
  214. BDY.xhrs[xhr.index] = null;
  215. BDY.xhrCount--;
  216. option['loading'] && hideLoading();
  217. var objResult = _getAjaxResult(xhr.responseText);
  218. if (objResult['result'] && option['cache']) {
  219. var cache = localStorage.getItem(cacheKey);
  220. if (cache && cache == xhr.responseText) {
  221. // 网络返回跟缓存一致
  222. return;
  223. } else {
  224. localStorage.setItem(cacheKey, xhr.responseText);
  225. }
  226. }
  227. callback && callback(objResult);
  228. };
  229. }
  230. function get(url, callback, option) {
  231. option = option || {};
  232. var xhr = new XMLHttpRequest();
  233. BDY.xhrs.push(xhr);
  234. BDY.xhrCount++;
  235. var data = {};
  236. _getDefaultData(data);
  237. for (var key in data) {
  238. if (!getParam2(key, url)) {
  239. url += url.indexOf('?') >= 0 ? '&' : '?';
  240. url += key + '=' + data[key];
  241. }
  242. }
  243. xhr.url = url;
  244. option['loading'] && showLoading();
  245. xhr.onreadystatechange = function() {
  246. if (xhr.readyState != 4) {
  247. return;
  248. }
  249. BDY.xhrs[xhr.index] = null;
  250. BDY.xhrCount--;
  251. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && location.protocol == 'file:')) {
  252. option['loading'] && hideLoading();
  253. if (option['type'] == 'text') {
  254. callback(xhr.responseText);
  255. } else {
  256. callback(_getAjaxResult(xhr.responseText));
  257. }
  258. }
  259. };
  260. xhr.open("GET", url);
  261. // xhr.withCredentials = true;
  262. xhr.send();
  263. }
  264. function _getAjaxResult(text) {
  265. var objResult = {};
  266. var objError = {
  267. result : 0,
  268. msg : "系统繁忙,请稍后再试!"
  269. };
  270. try {
  271. objResult = JSON.parse(text);
  272. if (typeof objResult !== 'object' || objResult === null) {
  273. objResult = objError;
  274. }
  275. } catch (ex) {
  276. //非json的处理
  277. objResult = objError;
  278. }
  279. return objResult;
  280. }
  281. function _loadAjaxCache(cacheKey, callback) {
  282. var cache = localStorage.getItem(cacheKey);
  283. if (cache) {
  284. var objResult = JSON.parse(cache);
  285. objResult._fromCache = true;
  286. callback && callback(objResult);
  287. return true;
  288. } else {
  289. return false;
  290. }
  291. }
  292. function _handleResult(callback, objResult) {
  293. //session_id失效,重新验证登录
  294. if(!objResult.result && objResult.code == -5) {
  295. openLogin();
  296. } else {
  297. callback && callback(objResult);
  298. }
  299. }
  300. function _deserialize(value){
  301. if (typeof value != 'string') {
  302. return undefined
  303. }
  304. try {
  305. return JSON.parse(value)
  306. }catch(e) {
  307. return value || undefined
  308. }
  309. }
  310. function getLocalData(key) {
  311. return getParam(key) || _deserialize(localStorage.getItem(key));
  312. }
  313. function setLocalData(key, val) {
  314. localStorage.setItem(key, JSON.stringify(val))
  315. }
  316. function getCookie(name) {
  317. var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  318. if(arr=document.cookie.match(reg))
  319. return unescape(arr[2]);
  320. else
  321. return null;
  322. }
  323. function _setTimeout(callback, timeout) {
  324. var timer = setTimeout(callback, timeout);
  325. BDY.timeout.push(timer);
  326. return timer;
  327. }
  328. function _setInterval(callback, timeout) {
  329. var timer = setInterval(callback, timeout);
  330. BDY.interval.push(timer);
  331. return timer;
  332. }
  333. function _clearRes() {
  334. var len;
  335. var timeout = BDY.timeout;
  336. var interval = BDY.interval;
  337. len = timeout.length;
  338. for (var i = 0; i < len; i++) {
  339. clearTimeout(timeout[i]);
  340. }
  341. len = interval.length;
  342. for (var i = 0; i < len; i++) {
  343. clearInterval(interval[i]);
  344. }
  345. // 重置timer
  346. BDY.timeout = [];
  347. BDY.interval = [];
  348. for (var i in BDY.xhrs) {
  349. BDY.xhrs[i] && BDY.xhrs[i].abort();
  350. }
  351. BDY.xhrs = [];
  352. BDY.xhrCount = 0;
  353. }
  354. // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  355. var loadingDelayHandler = 0;
  356. var loadingTimeoutHandler = 0;
  357. var loadDialog;
  358. function showLoading(text, timeout, cancelable, delay) {
  359. // 超时时间为15s
  360. timeout = timeout || 15000;
  361. // 0.2s后才显示loading
  362. delay = delay || 200;
  363. if (cancelable == null) {
  364. cancelable = true;
  365. } else {
  366. cancelable = !!cancelable;
  367. }
  368. if (loadingDelayHandler) {
  369. return;
  370. }
  371. loadingDelayHandler = setTimeout(function() {
  372. if (!WjySdk.showLoading(text, timeout, cancelable)) {
  373. Indicator.open(text);
  374. loadingTimeoutHandler = setTimeout(function(){
  375. hideLoading();
  376. showTip("加载超时,请稍后再试");
  377. }, timeout);
  378. }
  379. }, delay);
  380. }
  381. function hideLoading() {
  382. loadingDelayHandler && clearTimeout(loadingDelayHandler);
  383. loadingDelayHandler = 0;
  384. loadingTimeoutHandler && clearTimeout(loadingTimeoutHandler);
  385. loadingTimeoutHandler = 0;
  386. try {
  387. Indicator.close();
  388. } catch(e) {}
  389. }
  390. function showErrorTip(msg, timeout) {
  391. if (!msg) { return; }
  392. timeout = timeout || 3000;
  393. if (!WjySdk.showErrorTip(msg, timeout)) {
  394. Toast({
  395. message : msg,
  396. position: 'middle',
  397. duration: timeout
  398. });
  399. }
  400. }
  401. function showTip(msg, timeout) {
  402. if (!msg) { return; }
  403. timeout = timeout || 2000;
  404. if (!WjySdk.showTip(msg, timeout)) {
  405. Toast({
  406. message : msg,
  407. position: 'bottom',
  408. duration: timeout
  409. });
  410. }
  411. }
  412. function showDialog(msg, callback, title, buttonLabels) {
  413. title = title || "提示";
  414. buttonLabels = buttonLabels || "确定";
  415. MessageBox({
  416. title: title,
  417. message: msg,
  418. confirmButtonText: buttonLabels
  419. }).then(action => {
  420. callback && callback(action);
  421. });
  422. }
  423. function confirm(msg, callback, title, buttonLabels) {
  424. title = title || "提示";
  425. buttonLabels = buttonLabels || "确定,取消";
  426. if (!WjySdk.confirm(msg, callback, title, buttonLabels)) {
  427. MessageBox.confirm(msg, title).then(action => {
  428. callback && callback(true);
  429. }).catch(err => {
  430. callback && callback(false);
  431. });
  432. }
  433. }
  434. function handleTime(timeStamp,type){
  435. if(!timeStamp) return "--"
  436. var date = new Date(timeStamp)
  437. var year = date.getFullYear()
  438. var month = date.getMonth()+1
  439. var day = date.getDate()
  440. var hour = date.getHours()
  441. var minute = date.getMinutes()
  442. month = month >= 10 ? month : "0"+month
  443. day = day >= 10 ? day : "0"+day
  444. hour = hour >= 10 ? hour : "0"+hour
  445. minute = minute >= 10 ? minute : "0"+minute
  446. if(type==2) {
  447. return year+"-"+month+"-"+day+" "+hour+":"+minute
  448. } else {
  449. return year+"年"+month+"月"+day+"日 "+hour+":"+minute
  450. }
  451. }
  452. function checkWXAgent() {
  453. var ua = navigator.userAgent.toLowerCase();
  454. if (ua.match(/micromessenger/i) == "micromessenger") {
  455. return true;
  456. } else {
  457. return false;
  458. }
  459. }
  460. function getDomain(){
  461. var host = location.host;
  462. if (host.indexOf("127.0.0.1") > -1 || host.indexOf("test-minipay.ouj.com") > -1) {
  463. lib.apiUrl = "//test-api-minipay.ouj.com";
  464. lib.domain = "//test-minipay.ouj.com";
  465. } else {
  466. lib.apiUrl = "//api-minipay.ouj.com";
  467. lib.domain = "//minipay.ouj.com";
  468. }
  469. }
  470. //设置微信分享的参数
  471. function setWxShare(data,sCallback,cCallBack){ //分享数据,success回调,cancel回调
  472. if (!checkWXAgent()) return;
  473. var checkWxInterval = setInterval(function(){
  474. if(wx) {
  475. clearInterval(checkWxInterval);
  476. // 适配https
  477. if(!data.imgUrl.match(/http\:\/\/|https\:\/\//)) {
  478. data.imgUrl = "https:" + data.imgUrl
  479. }
  480. wx.ready(function(){
  481. wx.onMenuShareTimeline({
  482. title: data.title, // 分享标题
  483. link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  484. imgUrl: data.imgUrl, // 分享图标
  485. success: function () {
  486. sCallback && sCallback(); // 用户确认分享后执行的回调函数
  487. },
  488. cancel: function () {
  489. cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
  490. }
  491. });
  492. wx.onMenuShareAppMessage({
  493. title: data.title, // 分享标题
  494. desc: data.desc, // 分享描述
  495. link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
  496. imgUrl: data.imgUrl, // 分享图标
  497. success: function () {
  498. sCallback && sCallback(); // 用户确认分享后执行的回调函数
  499. },
  500. cancel: function () {
  501. cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
  502. }
  503. });
  504. });
  505. }
  506. },200);
  507. }
  508. function formatHttpProtocol(object) {
  509. let fData = JSON.stringify(object);
  510. fData = fData.replace(/http\:\/\//g, "//");
  511. return JSON.parse(fData);
  512. }
  513. function init(){
  514. getDomain();
  515. }
  516. init();
  517. lib.getParam = getParam;
  518. lib.getParam2 = getParam2;
  519. lib.setParam = setParam;
  520. lib.setParam2 = setParam2;
  521. lib.removeParam = removeParam;
  522. lib.parseHash = parseHash;
  523. lib.post = post;
  524. lib.get = get;
  525. lib.getLocalData = getLocalData;
  526. lib.setLocalData = setLocalData;
  527. lib.getCookie = getCookie;
  528. lib.setTimeout = _setTimeout;
  529. lib.setInterval = _setInterval;
  530. lib.clearRes = _clearRes;
  531. lib.showLoading = showLoading;
  532. lib.hideLoading = hideLoading;
  533. lib.showErrorTip = showErrorTip;
  534. lib.showTip = showTip;
  535. lib.showDialog = showDialog;
  536. lib.confirm = confirm;
  537. lib.checkWXAgent = checkWXAgent;
  538. lib.handleTime = handleTime;
  539. lib.setWxShare = setWxShare;
  540. lib.formatHttpProtocol = formatHttpProtocol;
  541. lib.appid = {
  542. taptapStar: 1010
  543. }
  544. export default lib;