util.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. const utils = {
  2. // 域名
  3. domain: 'https://fly2you.cn/',
  4. // domain: 'http://192.168.1.3:8080/',
  5. //接口地址
  6. interfaceUrl: function() {
  7. return utils.domain + 'platform/api/'
  8. },
  9. toast: function(text, duration, success) {
  10. uni.showToast({
  11. title: text || "出错啦~",
  12. icon: success || 'none',
  13. duration: duration || 2000
  14. })
  15. },
  16. modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor, cancelText) {
  17. uni.showModal({
  18. title: title || '提示',
  19. content: content,
  20. showCancel: showCancel,
  21. cancelColor: cancelColor || "#555",
  22. confirmColor: confirmColor || "#e41f19",
  23. confirmText: confirmText || "确定",
  24. cancelText: cancelText || "取消",
  25. success(res) {
  26. if (res.confirm) {
  27. callback && callback(true)
  28. } else {
  29. callback && callback(false)
  30. }
  31. }
  32. })
  33. },
  34. isAndroid: function() {
  35. const res = uni.getSystemInfoSync();
  36. return res.platform.toLocaleLowerCase() == "android"
  37. },
  38. isIphoneX: function() {
  39. const res = uni.getSystemInfoSync();
  40. let iphonex = false;
  41. let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
  42. const model = res.model.replace(/\s/g, "").toLowerCase()
  43. if (models.includes(model)) {
  44. iphonex = true;
  45. }
  46. return iphonex;
  47. },
  48. constNum: function() {
  49. let time = 0;
  50. // #ifdef APP-PLUS
  51. time = this.isAndroid() ? 300 : 0;
  52. // #endif
  53. return time
  54. },
  55. delayed: null,
  56. /**
  57. * 请求数据处理
  58. * @param string url 请求地址
  59. * @param {*} postData 请求参数
  60. * @param string method 请求方式
  61. * GET or POST
  62. * @param string contentType 数据格式
  63. * 'application/x-www-form-urlencoded'
  64. * 'application/json'
  65. * @param bool isDelay 是否延迟显示loading
  66. * @param bool hideLoading 是否隐藏loading
  67. * true: 隐藏
  68. * false:显示
  69. */
  70. request: function(url, postData = {}, method = "POST", contentType = "application/x-www-form-urlencoded", isDelay, hideLoading) {
  71. //接口请求
  72. let loadding = false;
  73. utils.delayed && uni.hideLoading();
  74. clearTimeout(utils.delayed);
  75. utils.delayed = null;
  76. if (!hideLoading) {
  77. utils.delayed = setTimeout(() => {
  78. uni.showLoading({
  79. mask: true,
  80. title: '请稍候...',
  81. success(res) {
  82. loadding = true
  83. }
  84. })
  85. }, isDelay ? 1000 : 0)
  86. }
  87. return new Promise((resolve, reject) => {
  88. uni.request({
  89. url: utils.interfaceUrl() + url,
  90. data: postData,
  91. header: {
  92. 'content-type': contentType,
  93. 'token': utils.getToken()
  94. },
  95. method: method, //'GET','POST'
  96. dataType: 'json',
  97. success: (res) => {
  98. if (loadding && !hideLoading) {
  99. uni.hideLoading()
  100. }
  101. if (res.statusCode === 200) {
  102. if (res.data.errno === 401) {
  103. //返回码401说明token过期或者用户未登录
  104. uni.removeStorage({
  105. key: 'token',
  106. success() {
  107. //个人中心页不跳转
  108. if (uni.getStorageSync("navUrl") != "/pages/ucenter/index/index") {
  109. utils.modal('温馨提示', '您还没有登录,是否去登录', true, (confirm) => {
  110. if (confirm) {
  111. uni.redirectTo({
  112. url: '/pages/auth/btnAuth/btnAuth',
  113. })
  114. } else {
  115. uni.navigateBack({
  116. delta: 1,
  117. fail: (res) => {
  118. uni.switchTab({
  119. url: '/pages/index/index',
  120. })
  121. }
  122. })
  123. }
  124. })
  125. }
  126. }
  127. })
  128. } else if (res.data.errno === 500) {
  129. utils.toast(res.data.msg)
  130. } else if (res.data.errno === 404) {
  131. utils.toast(res.data.msg)
  132. } else {
  133. resolve(res.data);
  134. }
  135. } else {
  136. reject(res.data.msg);
  137. }
  138. },
  139. fail: (res) => {
  140. utils.toast("网络不给力,请稍后再试~")
  141. reject(res)
  142. },
  143. complete: function(res) {
  144. clearTimeout(utils.delayed)
  145. utils.delayed = null;
  146. if (res.statusCode === 200) {
  147. if (res.data.errno === 0 || res.data.errno === 401) {
  148. uni.hideLoading()
  149. } else {
  150. utils.toast(res.data.msg)
  151. }
  152. } else {
  153. utils.toast('服务器开小差了~')
  154. }
  155. }
  156. })
  157. })
  158. },
  159. /**
  160. * 上传文件
  161. * @param string url 请求地址
  162. * @param string src 文件路径
  163. */
  164. uploadFile: function(url, src) {
  165. uni.showLoading({
  166. title: '请稍候...',
  167. mask:true
  168. })
  169. return new Promise((resolve, reject) => {
  170. const uploadTask = uni.uploadFile({
  171. url: utils.interfaceUrl() + url,
  172. filePath: src,
  173. name: 'file',
  174. header: {
  175. 'content-type': 'multipart/form-data',
  176. 'token': utils.getToken()
  177. },
  178. success: function(res) {
  179. uni.hideLoading()
  180. let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
  181. if (data.errno == 0) {
  182. //返回图片地址
  183. resolve(data)
  184. } else {
  185. that.toast(res.msg);
  186. }
  187. },
  188. fail: function(res) {
  189. utils.toast("网络不给力,请稍后再试~")
  190. reject(res)
  191. }
  192. })
  193. })
  194. },
  195. tuiJsonp: function(url, callback, callbackname) {
  196. // #ifdef H5
  197. window[callbackname] = callback;
  198. let tuiScript = document.createElement("script");
  199. tuiScript.src = url;
  200. tuiScript.type = "text/javascript";
  201. document.head.appendChild(tuiScript);
  202. document.head.removeChild(tuiScript);
  203. // #endif
  204. },
  205. //设置用户信息
  206. setUserInfo: function(mobile, token) {
  207. uni.setStorageSync("token", token)
  208. uni.setStorageSync("mobile", mobile)
  209. },
  210. //获取token
  211. getToken: function() {
  212. return uni.getStorageSync("token")
  213. },
  214. //去空格
  215. trim: function(value) {
  216. return value.replace(/(^\s*)|(\s*$)/g, "");
  217. },
  218. //内容替换
  219. replaceAll: function(text, repstr, newstr) {
  220. return text.replace(new RegExp(repstr, "gm"), newstr);
  221. },
  222. //格式化手机号码
  223. formatNumber: function(num) {
  224. return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
  225. },
  226. //金额格式化
  227. rmoney: function(money) {
  228. return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
  229. /\,$/, '').split('').reverse().join('');
  230. },
  231. // 时间格式化输出,如11:03 25:19 每1s都会调用一次
  232. dateformat: function(micro_second) {
  233. // 总秒数
  234. var second = Math.floor(micro_second / 1000);
  235. // 天数
  236. var day = Math.floor(second / 3600 / 24);
  237. // 小时
  238. var hr = Math.floor(second / 3600 % 24);
  239. // 分钟
  240. var min = Math.floor(second / 60 % 60);
  241. // 秒
  242. var sec = Math.floor(second % 60);
  243. return {
  244. day,
  245. hr: hr < 10 ? '0' + hr : hr,
  246. min: min < 10 ? '0' + min : min,
  247. sec: sec < 10 ? '0' + sec : sec,
  248. second: second
  249. }
  250. },
  251. //日期格式化
  252. formatDate: function(formatStr, fdate) {
  253. if (fdate) {
  254. if (~fdate.indexOf('.')) {
  255. fdate = fdate.substring(0, fdate.indexOf('.'));
  256. }
  257. fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
  258. var fTime, fStr = 'ymdhis';
  259. if (!formatStr)
  260. formatStr = "y-m-d h:i:s";
  261. if (fdate)
  262. fTime = new Date(fdate);
  263. else
  264. fTime = new Date();
  265. var month = fTime.getMonth() + 1;
  266. var day = fTime.getDate();
  267. var hours = fTime.getHours();
  268. var minu = fTime.getMinutes();
  269. var second = fTime.getSeconds();
  270. month = month < 10 ? '0' + month : month;
  271. day = day < 10 ? '0' + day : day;
  272. hours = hours < 10 ? ('0' + hours) : hours;
  273. minu = minu < 10 ? '0' + minu : minu;
  274. second = second < 10 ? '0' + second : second;
  275. var formatArr = [
  276. fTime.getFullYear().toString(),
  277. month.toString(),
  278. day.toString(),
  279. hours.toString(),
  280. minu.toString(),
  281. second.toString()
  282. ]
  283. for (var i = 0; i < formatArr.length; i++) {
  284. formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
  285. }
  286. return formatStr;
  287. } else {
  288. return "";
  289. }
  290. },
  291. getDistance: function(lat1, lng1, lat2, lng2) {
  292. function Rad(d) {
  293. return d * Math.PI / 180.0;
  294. }
  295. if (!lat1 || !lng1) {
  296. return '';
  297. }
  298. // lat1用户的纬度
  299. // lng1用户的经度
  300. // lat2商家的纬度
  301. // lng2商家的经度
  302. let radLat1 = Rad(lat1);
  303. let radLat2 = Rad(lat2);
  304. let a = radLat1 - radLat2;
  305. let b = Rad(lng1) - Rad(lng2);
  306. let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
  307. Math.sin(b / 2), 2)));
  308. s = s * 6378.137;
  309. s = Math.round(s * 10000) / 10000;
  310. s = '(距您' + s.toFixed(2) + '公里)' //保留两位小数
  311. return s
  312. },
  313. isMobile: function(mobile) {
  314. if (!mobile) {
  315. utils.toast('请输入手机号码');
  316. return false
  317. }
  318. if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
  319. utils.toast('手机号不正确');
  320. return false
  321. }
  322. return true
  323. },
  324. rgbToHex: function(r, g, b) {
  325. return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
  326. },
  327. toHex: function(n) {
  328. n = parseInt(n, 10);
  329. if (isNaN(n)) return "00";
  330. n = Math.max(0, Math.min(n, 255));
  331. return "0123456789ABCDEF".charAt((n - n % 16) / 16) +
  332. "0123456789ABCDEF".charAt(n % 16);
  333. },
  334. hexToRgb(hex) {
  335. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  336. return result ? {
  337. r: parseInt(result[1], 16),
  338. g: parseInt(result[2], 16),
  339. b: parseInt(result[3], 16)
  340. } : null;
  341. },
  342. transDate: function(date, fmt) {
  343. if (!date) {
  344. return '--'
  345. }
  346. let _this = new Date(date * 1000)
  347. let o = {
  348. 'M+': _this.getMonth() + 1,
  349. 'd+': _this.getDate(),
  350. 'h+': _this.getHours(),
  351. 'm+': _this.getMinutes(),
  352. 's+': _this.getSeconds(),
  353. 'q+': Math.floor((_this.getMonth() + 3) / 3),
  354. 'S': _this.getMilliseconds()
  355. }
  356. if (/(y+)/.test(fmt)) {
  357. fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
  358. }
  359. for (let k in o) {
  360. if (new RegExp('(' + k + ')').test(fmt)) {
  361. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  362. }
  363. }
  364. return fmt
  365. },
  366. isNumber: function(val) {
  367. let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  368. let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  369. if (regPos.test(val) || regNeg.test(val)) {
  370. return true;
  371. } else {
  372. return false;
  373. }
  374. },
  375. //判断字符串是否为空
  376. isEmpty: function(str) {
  377. if (str === '' || str === undefined || str === null) {
  378. return true;
  379. } else {
  380. return false;
  381. }
  382. },
  383. expireTime: function(str) {
  384. if (!str) {
  385. return;
  386. }
  387. let NowTime = new Date().getTime();
  388. //IOS系统直接使用new Date('2018-10-29 11:25:21'),在IOS上获取不到对应的时间对象。
  389. let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
  390. if (totalSecond < 0) {
  391. return;
  392. }
  393. return totalSecond / 1000
  394. },
  395. /**
  396. * 统一下单请求
  397. */
  398. payOrder: function(orderId) {
  399. let tradeType = 'JSAPI'
  400. // #ifdef APP-PLUS
  401. tradeType = 'APP'
  402. // #endif
  403. // #ifdef H5
  404. tradeType = 'MWEB'
  405. // #endif
  406. return new Promise(function(resolve, reject) {
  407. utils.request('pay/prepay', {
  408. orderId: orderId,
  409. tradeType: tradeType
  410. }, 'POST').then((res) => {
  411. if (res.errno === 0) {
  412. // #ifdef H5
  413. location.href = res.mwebOrderResult.mwebUrl + '&redirect_url=' + encodeURIComponent(utils.domain +
  414. 'h5/#/pageD/payResult/payResult?orderId=' + orderId)
  415. // #endif
  416. // #ifdef APP-PLUS
  417. let appOrderResult = res.appOrderResult;
  418. uni.requestPayment({
  419. provider: 'wxpay',
  420. orderInfo: {
  421. "appid": appOrderResult.appId,
  422. "noncestr": appOrderResult.nonceStr,
  423. "package": appOrderResult.packageValue,
  424. "partnerid": appOrderResult.partnerId,
  425. "prepayid": appOrderResult.prepayId,
  426. "timestamp": appOrderResult.timeStamp,
  427. "sign": appOrderResult.sign
  428. },
  429. success: function(res) {
  430. console.log(res)
  431. resolve(res);
  432. },
  433. fail: function(res) {
  434. console.log(res)
  435. reject(res);
  436. },
  437. complete: function(res) {
  438. console.log(res)
  439. reject(res);
  440. }
  441. });
  442. // #endif
  443. // #ifdef MP-WEIXIN
  444. let payParam = res.data;
  445. uni.requestPayment({
  446. 'timeStamp': payParam.timeStamp,
  447. 'nonceStr': payParam.nonceStr,
  448. 'package': payParam.package,
  449. 'signType': payParam.signType,
  450. 'paySign': payParam.paySign,
  451. 'success': function(res) {
  452. console.log(res)
  453. resolve(res);
  454. },
  455. 'fail': function(res) {
  456. console.log(res)
  457. reject(res);
  458. },
  459. 'complete': function(res) {
  460. console.log(res)
  461. reject(res);
  462. }
  463. });
  464. // #endif
  465. } else {
  466. reject(res);
  467. }
  468. });
  469. });
  470. },
  471. /**
  472. * 调用微信登录
  473. */
  474. login: function() {
  475. return new Promise(function(resolve, reject) {
  476. uni.login({
  477. success: function(res) {
  478. if (res.code) {
  479. resolve(res);
  480. } else {
  481. reject(res);
  482. }
  483. },
  484. fail: function(err) {
  485. reject(err);
  486. }
  487. });
  488. });
  489. }
  490. }
  491. module.exports = {
  492. interfaceUrl: utils.interfaceUrl,
  493. toast: utils.toast,
  494. modal: utils.modal,
  495. isAndroid: utils.isAndroid,
  496. isIphoneX: utils.isIphoneX,
  497. constNum: utils.constNum,
  498. request: utils.request,
  499. uploadFile: utils.uploadFile,
  500. tuiJsonp: utils.tuiJsonp,
  501. setUserInfo: utils.setUserInfo,
  502. getToken: utils.getToken,
  503. trim: utils.trim,
  504. replaceAll: utils.replaceAll,
  505. formatNumber: utils.formatNumber,
  506. rmoney: utils.rmoney,
  507. dateformat: utils.dateformat,
  508. formatDate: utils.formatDate,
  509. getDistance: utils.getDistance,
  510. isMobile: utils.isMobile,
  511. rgbToHex: utils.rgbToHex,
  512. hexToRgb: utils.hexToRgb,
  513. transDate: utils.transDate,
  514. isNumber: utils.isNumber,
  515. isEmpty: utils.isEmpty,
  516. expireTime: utils.expireTime,
  517. payOrder: utils.payOrder,
  518. login: utils.login
  519. }