util.js 15 KB

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