util.js 15 KB

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