util.js 15 KB

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