util.js 15 KB

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