util.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. })
  168. return new Promise((resolve, reject) => {
  169. const uploadTask = uni.uploadFile({
  170. url: utils.interfaceUrl() + url,
  171. filePath: src,
  172. name: 'file',
  173. header: {
  174. 'content-type': 'multipart/form-data',
  175. 'token': utils.getToken()
  176. },
  177. success: function(res) {
  178. uni.hideLoading()
  179. let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
  180. if (data.errno == 0) {
  181. //返回图片地址
  182. resolve(data)
  183. } else {
  184. that.toast(res.msg);
  185. }
  186. },
  187. fail: function(res) {
  188. utils.toast("网络不给力,请稍后再试~")
  189. reject(res)
  190. }
  191. })
  192. })
  193. },
  194. tuiJsonp: function(url, callback, callbackname) {
  195. // #ifdef H5
  196. window[callbackname] = callback;
  197. let tuiScript = document.createElement("script");
  198. tuiScript.src = url;
  199. tuiScript.type = "text/javascript";
  200. document.head.appendChild(tuiScript);
  201. document.head.removeChild(tuiScript);
  202. // #endif
  203. },
  204. //设置用户信息
  205. setUserInfo: function(mobile, token) {
  206. uni.setStorageSync("token", token)
  207. uni.setStorageSync("mobile", mobile)
  208. },
  209. //获取token
  210. getToken: function() {
  211. return uni.getStorageSync("token")
  212. },
  213. //去空格
  214. trim: function(value) {
  215. return value.replace(/(^\s*)|(\s*$)/g, "");
  216. },
  217. //内容替换
  218. replaceAll: function(text, repstr, newstr) {
  219. return text.replace(new RegExp(repstr, "gm"), newstr);
  220. },
  221. //格式化手机号码
  222. formatNumber: function(num) {
  223. return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
  224. },
  225. //金额格式化
  226. rmoney: function(money) {
  227. return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
  228. /\,$/, '').split('').reverse().join('');
  229. },
  230. // 时间格式化输出,如11:03 25:19 每1s都会调用一次
  231. dateformat: function(micro_second) {
  232. // 总秒数
  233. var second = Math.floor(micro_second / 1000);
  234. // 天数
  235. var day = Math.floor(second / 3600 / 24);
  236. // 小时
  237. var hr = Math.floor(second / 3600 % 24);
  238. // 分钟
  239. var min = Math.floor(second / 60 % 60);
  240. // 秒
  241. var sec = Math.floor(second % 60);
  242. return {
  243. day,
  244. hr: hr < 10 ? '0' + hr : hr,
  245. min: min < 10 ? '0' + min : min,
  246. sec: sec < 10 ? '0' + sec : sec,
  247. second: second
  248. }
  249. },
  250. //日期格式化
  251. formatDate: function(formatStr, fdate) {
  252. if (fdate) {
  253. if (~fdate.indexOf('.')) {
  254. fdate = fdate.substring(0, fdate.indexOf('.'));
  255. }
  256. fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
  257. var fTime, fStr = 'ymdhis';
  258. if (!formatStr)
  259. formatStr = "y-m-d h:i:s";
  260. if (fdate)
  261. fTime = new Date(fdate);
  262. else
  263. fTime = new Date();
  264. var month = fTime.getMonth() + 1;
  265. var day = fTime.getDate();
  266. var hours = fTime.getHours();
  267. var minu = fTime.getMinutes();
  268. var second = fTime.getSeconds();
  269. month = month < 10 ? '0' + month : month;
  270. day = day < 10 ? '0' + day : day;
  271. hours = hours < 10 ? ('0' + hours) : hours;
  272. minu = minu < 10 ? '0' + minu : minu;
  273. second = second < 10 ? '0' + second : second;
  274. var formatArr = [
  275. fTime.getFullYear().toString(),
  276. month.toString(),
  277. day.toString(),
  278. hours.toString(),
  279. minu.toString(),
  280. second.toString()
  281. ]
  282. for (var i = 0; i < formatArr.length; i++) {
  283. formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
  284. }
  285. return formatStr;
  286. } else {
  287. return "";
  288. }
  289. },
  290. getDistance: function(lat1, lng1, lat2, lng2) {
  291. function Rad(d) {
  292. return d * Math.PI / 180.0;
  293. }
  294. if (!lat1 || !lng1) {
  295. return '';
  296. }
  297. // lat1用户的纬度
  298. // lng1用户的经度
  299. // lat2商家的纬度
  300. // lng2商家的经度
  301. let radLat1 = Rad(lat1);
  302. let radLat2 = Rad(lat2);
  303. let a = radLat1 - radLat2;
  304. let b = Rad(lng1) - Rad(lng2);
  305. let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
  306. Math.sin(b / 2), 2)));
  307. s = s * 6378.137;
  308. s = Math.round(s * 10000) / 10000;
  309. s = '(距您' + s.toFixed(2) + '公里)' //保留两位小数
  310. return s
  311. },
  312. isMobile: function(mobile) {
  313. if (!mobile) {
  314. utils.toast('请输入手机号码');
  315. return false
  316. }
  317. if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
  318. utils.toast('手机号不正确');
  319. return false
  320. }
  321. return true
  322. },
  323. rgbToHex: function(r, g, b) {
  324. return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
  325. },
  326. toHex: function(n) {
  327. n = parseInt(n, 10);
  328. if (isNaN(n)) return "00";
  329. n = Math.max(0, Math.min(n, 255));
  330. return "0123456789ABCDEF".charAt((n - n % 16) / 16) +
  331. "0123456789ABCDEF".charAt(n % 16);
  332. },
  333. hexToRgb(hex) {
  334. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  335. return result ? {
  336. r: parseInt(result[1], 16),
  337. g: parseInt(result[2], 16),
  338. b: parseInt(result[3], 16)
  339. } : null;
  340. },
  341. transDate: function(date, fmt) {
  342. if (!date) {
  343. return '--'
  344. }
  345. let _this = new Date(date * 1000)
  346. let o = {
  347. 'M+': _this.getMonth() + 1,
  348. 'd+': _this.getDate(),
  349. 'h+': _this.getHours(),
  350. 'm+': _this.getMinutes(),
  351. 's+': _this.getSeconds(),
  352. 'q+': Math.floor((_this.getMonth() + 3) / 3),
  353. 'S': _this.getMilliseconds()
  354. }
  355. if (/(y+)/.test(fmt)) {
  356. fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
  357. }
  358. for (let k in o) {
  359. if (new RegExp('(' + k + ')').test(fmt)) {
  360. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  361. }
  362. }
  363. return fmt
  364. },
  365. isNumber: function(val) {
  366. let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  367. let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  368. if (regPos.test(val) || regNeg.test(val)) {
  369. return true;
  370. } else {
  371. return false;
  372. }
  373. },
  374. //判断字符串是否为空
  375. isEmpty: function(str) {
  376. if (str === '' || str === undefined || str === null) {
  377. return true;
  378. } else {
  379. return false;
  380. }
  381. },
  382. expireTime: function(str) {
  383. if (!str) {
  384. return;
  385. }
  386. let NowTime = new Date().getTime();
  387. //IOS系统直接使用new Date('2018-10-29 11:25:21'),在IOS上获取不到对应的时间对象。
  388. let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
  389. if (totalSecond < 0) {
  390. return;
  391. }
  392. return totalSecond / 1000
  393. },
  394. /**
  395. * 统一下单请求
  396. */
  397. payOrder: function(orderId) {
  398. let tradeType = 'JSAPI'
  399. // #ifdef APP-PLUS
  400. tradeType = 'APP'
  401. // #endif
  402. // #ifdef H5
  403. tradeType = 'MWEB'
  404. // #endif
  405. return new Promise(function(resolve, reject) {
  406. utils.request('pay/prepay', {
  407. orderId: orderId,
  408. tradeType: tradeType
  409. }, 'POST').then((res) => {
  410. if (res.errno === 0) {
  411. // #ifdef H5
  412. location.href = res.mwebOrderResult.mwebUrl + '&redirect_url=' + encodeURIComponent(utils.domain +
  413. 'h5/#/pageD/payResult/payResult?orderId=' + orderId)
  414. // #endif
  415. // #ifdef APP-PLUS
  416. let appOrderResult = res.appOrderResult;
  417. uni.requestPayment({
  418. provider: 'wxpay',
  419. orderInfo: {
  420. "appid": appOrderResult.appId,
  421. "noncestr": appOrderResult.nonceStr,
  422. "package": appOrderResult.packageValue,
  423. "partnerid": appOrderResult.partnerId,
  424. "prepayid": appOrderResult.prepayId,
  425. "timestamp": appOrderResult.timeStamp,
  426. "sign": appOrderResult.sign
  427. },
  428. success: function(res) {
  429. console.log(res)
  430. resolve(res);
  431. },
  432. fail: function(res) {
  433. console.log(res)
  434. reject(res);
  435. },
  436. complete: function(res) {
  437. console.log(res)
  438. reject(res);
  439. }
  440. });
  441. // #endif
  442. // #ifdef MP-WEIXIN
  443. let payParam = res.data;
  444. uni.requestPayment({
  445. 'timeStamp': payParam.timeStamp,
  446. 'nonceStr': payParam.nonceStr,
  447. 'package': payParam.package,
  448. 'signType': payParam.signType,
  449. 'paySign': payParam.paySign,
  450. 'success': function(res) {
  451. console.log(res)
  452. resolve(res);
  453. },
  454. 'fail': function(res) {
  455. console.log(res)
  456. reject(res);
  457. },
  458. 'complete': function(res) {
  459. console.log(res)
  460. reject(res);
  461. }
  462. });
  463. // #endif
  464. } else {
  465. reject(res);
  466. }
  467. });
  468. });
  469. },
  470. /**
  471. * 调用微信登录
  472. */
  473. login: function() {
  474. return new Promise(function(resolve, reject) {
  475. uni.login({
  476. success: function(res) {
  477. if (res.code) {
  478. resolve(res);
  479. } else {
  480. reject(res);
  481. }
  482. },
  483. fail: function(err) {
  484. reject(err);
  485. }
  486. });
  487. });
  488. }
  489. }
  490. module.exports = {
  491. interfaceUrl: utils.interfaceUrl,
  492. toast: utils.toast,
  493. modal: utils.modal,
  494. isAndroid: utils.isAndroid,
  495. isIphoneX: utils.isIphoneX,
  496. constNum: utils.constNum,
  497. request: utils.request,
  498. uploadFile: utils.uploadFile,
  499. tuiJsonp: utils.tuiJsonp,
  500. setUserInfo: utils.setUserInfo,
  501. getToken: utils.getToken,
  502. trim: utils.trim,
  503. replaceAll: utils.replaceAll,
  504. formatNumber: utils.formatNumber,
  505. rmoney: utils.rmoney,
  506. dateformat: utils.dateformat,
  507. formatDate: utils.formatDate,
  508. getDistance: utils.getDistance,
  509. isMobile: utils.isMobile,
  510. rgbToHex: utils.rgbToHex,
  511. hexToRgb: utils.hexToRgb,
  512. transDate: utils.transDate,
  513. isNumber: utils.isNumber,
  514. isEmpty: utils.isEmpty,
  515. expireTime: utils.expireTime,
  516. payOrder: utils.payOrder,
  517. login: utils.login
  518. }