util.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. const utils = {
  2. // 域名
  3. //domain: 'https://fly2you.cn/',
  4. //domain: 'https://gn.baotingsmart.com/',
  5. domain: 'http://127.0.0.1:8764/',
  6. //接口地址
  7. interfaceUrl: function(params) {
  8. //return utils.domain + 'platform/api/'
  9. return utils.domain + (params != "" ? params : 'opsApi/')
  10. },
  11. toast: function(text, duration, success) {
  12. uni.showToast({
  13. title: text || "出错啦~",
  14. icon: success || 'none',
  15. duration: duration || 2000
  16. })
  17. },
  18. modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor, cancelText) {
  19. uni.showModal({
  20. title: title || '提示',
  21. content: content,
  22. showCancel: showCancel,
  23. cancelColor: cancelColor || "#555",
  24. confirmColor: confirmColor || "#e41f19",
  25. confirmText: confirmText || "确定",
  26. cancelText: cancelText || "取消",
  27. success(res) {
  28. if (res.confirm) {
  29. callback && callback(true)
  30. } else {
  31. callback && callback(false)
  32. }
  33. }
  34. })
  35. },
  36. isAndroid: function() {
  37. const res = uni.getSystemInfoSync();
  38. return res.platform.toLocaleLowerCase() == "android"
  39. },
  40. isIphoneX: function() {
  41. const res = uni.getSystemInfoSync();
  42. let iphonex = false;
  43. let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
  44. const model = res.model.replace(/\s/g, "").toLowerCase()
  45. if (models.includes(model)) {
  46. iphonex = true;
  47. }
  48. return iphonex;
  49. },
  50. constNum: function() {
  51. let time = 0;
  52. // #ifdef APP-PLUS
  53. time = this.isAndroid() ? 300 : 0;
  54. // #endif
  55. return time
  56. },
  57. delayed: null,
  58. /**
  59. * 请求数据处理
  60. * @param string url 请求地址
  61. * @param {*} postData 请求参数
  62. * @param string method 请求方式
  63. * GET or POST
  64. * @param string contentType 数据格式
  65. * 'application/x-www-form-urlencoded'
  66. * 'application/json'
  67. * @param bool isDelay 是否延迟显示loading
  68. * @param bool hideLoading 是否隐藏loading
  69. * true: 隐藏
  70. * false:显示
  71. */
  72. request: function(url, postData = {}, method = "POST", contentType = "application/x-www-form-urlencoded", 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. let params = postData.interfaceUrl == null? '' : postData.interfaceUrl
  90. return new Promise((resolve, reject) => {
  91. uni.request({
  92. url: utils.interfaceUrl(params) + url,
  93. data: postData,
  94. header: {
  95. 'content-type': contentType,
  96. 'token': utils.getToken(),
  97. 'Authorization': 'Basic enVpaG91X3VpOnp1aWhvdV91aV9zZWNyZXQ='
  98. },
  99. method: method, //'GET','POST'
  100. dataType: 'json',
  101. success: (res) => {
  102. if (loadding && !hideLoading) {
  103. uni.hideLoading()
  104. }
  105. if (res.statusCode === 401 || res.data.code === 40005 || res.data.code === 40001) {
  106. utils.modal('温馨提示', '您还没有登录,是否去登录', true, (confirm) => {
  107. if (confirm) {
  108. uni.redirectTo({
  109. url: '/pages/auth/login/login',
  110. })
  111. } else {
  112. uni.navigateBack({
  113. delta: 1,
  114. fail: (res) => {
  115. uni.switchTab({
  116. url: '/pages/index/index',
  117. })
  118. }
  119. })
  120. }
  121. })
  122. }else if (res.statusCode === 200){
  123. resolve(res.data);
  124. }else {
  125. reject(res.data);
  126. }
  127. },
  128. fail: (res) => {
  129. utils.toast("网络不给力,请稍后再试~")
  130. reject(res)
  131. },
  132. complete: function(res) {
  133. clearTimeout(utils.delayed)
  134. utils.delayed = null;
  135. if (res.statusCode === 200) {
  136. if (res.data.code === 0) {
  137. uni.hideLoading()
  138. }else{
  139. utils.toast(res.data.msg);
  140. }
  141. } else {
  142. utils.toast('服务器开小差了~')
  143. }
  144. }
  145. })
  146. })
  147. },
  148. /**
  149. * 上传文件
  150. * @param string url 请求地址
  151. * @param string src 文件路径
  152. */
  153. uploadFile: function(url, src) {
  154. uni.showLoading({
  155. title: '请稍候...'
  156. })
  157. return new Promise((resolve, reject) => {
  158. const uploadTask = uni.uploadFile({
  159. url: utils.interfaceUrl() + url,
  160. filePath: src,
  161. name: 'file',
  162. header: {
  163. 'content-type': 'multipart/form-data',
  164. 'X-Nideshop-Token': utils.getToken()
  165. },
  166. success: function(res) {
  167. uni.hideLoading()
  168. let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
  169. if (data.errno == 0) {
  170. //返回图片地址
  171. resolve(data)
  172. } else {
  173. that.toast(res.msg);
  174. }
  175. },
  176. fail: function(res) {
  177. utils.toast("网络不给力,请稍后再试~")
  178. reject(res)
  179. }
  180. })
  181. })
  182. },
  183. tuiJsonp: function(url, callback, callbackname) {
  184. // #ifdef H5
  185. window[callbackname] = callback;
  186. let tuiScript = document.createElement("script");
  187. tuiScript.src = url;
  188. tuiScript.type = "text/javascript";
  189. document.head.appendChild(tuiScript);
  190. document.head.removeChild(tuiScript);
  191. // #endif
  192. },
  193. //设置用户信息
  194. setUserInfo: function(mobile, token) {
  195. uni.setStorageSync("X-Nideshop-Token", token)
  196. uni.setStorageSync("mobile", mobile)
  197. },
  198. //获取token
  199. getToken: function() {
  200. return uni.getStorageSync("token")
  201. },
  202. //去空格
  203. trim: function(value) {
  204. return value.replace(/(^\s*)|(\s*$)/g, "");
  205. },
  206. //内容替换
  207. replaceAll: function(text, repstr, newstr) {
  208. return text.replace(new RegExp(repstr, "gm"), newstr);
  209. },
  210. //格式化手机号码
  211. formatNumber: function(num) {
  212. return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
  213. },
  214. //金额格式化
  215. rmoney: function(money) {
  216. return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
  217. /\,$/, '').split('').reverse().join('');
  218. },
  219. // 时间格式化输出,如11:03 25:19 每1s都会调用一次
  220. dateformat: function(micro_second) {
  221. // 总秒数
  222. var second = Math.floor(micro_second / 1000);
  223. // 天数
  224. var day = Math.floor(second / 3600 / 24);
  225. // 小时
  226. var hr = Math.floor(second / 3600 % 24);
  227. // 分钟
  228. var min = Math.floor(second / 60 % 60);
  229. // 秒
  230. var sec = Math.floor(second % 60);
  231. return {
  232. day,
  233. hr: hr < 10 ? '0' + hr : hr,
  234. min: min < 10 ? '0' + min : min,
  235. sec: sec < 10 ? '0' + sec : sec,
  236. second: second
  237. }
  238. },
  239. //日期格式化
  240. formatDate: function(formatStr, fdate) {
  241. if (fdate) {
  242. if (~fdate.indexOf('.')) {
  243. fdate = fdate.substring(0, fdate.indexOf('.'));
  244. }
  245. fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
  246. var fTime, fStr = 'ymdhis';
  247. if (!formatStr)
  248. formatStr = "y-m-d h:i:s";
  249. if (fdate)
  250. fTime = new Date(fdate);
  251. else
  252. fTime = new Date();
  253. var month = fTime.getMonth() + 1;
  254. var day = fTime.getDate();
  255. var hours = fTime.getHours();
  256. var minu = fTime.getMinutes();
  257. var second = fTime.getSeconds();
  258. month = month < 10 ? '0' + month : month;
  259. day = day < 10 ? '0' + day : day;
  260. hours = hours < 10 ? ('0' + hours) : hours;
  261. minu = minu < 10 ? '0' + minu : minu;
  262. second = second < 10 ? '0' + second : second;
  263. var formatArr = [
  264. fTime.getFullYear().toString(),
  265. month.toString(),
  266. day.toString(),
  267. hours.toString(),
  268. minu.toString(),
  269. second.toString()
  270. ]
  271. for (var i = 0; i < formatArr.length; i++) {
  272. formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
  273. }
  274. return formatStr;
  275. } else {
  276. return "";
  277. }
  278. },
  279. getDistance: function(lat1, lng1, lat2, lng2) {
  280. function Rad(d) {
  281. return d * Math.PI / 180.0;
  282. }
  283. if (!lat1 || !lng1) {
  284. return '';
  285. }
  286. // lat1用户的纬度
  287. // lng1用户的经度
  288. // lat2商家的纬度
  289. // lng2商家的经度
  290. let radLat1 = Rad(lat1);
  291. let radLat2 = Rad(lat2);
  292. let a = radLat1 - radLat2;
  293. let b = Rad(lng1) - Rad(lng2);
  294. let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
  295. Math.sin(b / 2), 2)));
  296. s = s * 6378.137;
  297. s = Math.round(s * 10000) / 10000;
  298. s = '(距您' + s.toFixed(2) + '公里)' //保留两位小数
  299. return s
  300. },
  301. isMobile: function(mobile) {
  302. if (!mobile) {
  303. utils.toast('请输入手机号码');
  304. return false
  305. }
  306. if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
  307. utils.toast('手机号不正确');
  308. return false
  309. }
  310. return true
  311. },
  312. rgbToHex: function(r, g, b) {
  313. return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
  314. },
  315. toHex: function(n) {
  316. n = parseInt(n, 10);
  317. if (isNaN(n)) return "00";
  318. n = Math.max(0, Math.min(n, 255));
  319. return "0123456789ABCDEF".charAt((n - n % 16) / 16) +
  320. "0123456789ABCDEF".charAt(n % 16);
  321. },
  322. hexToRgb(hex) {
  323. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  324. return result ? {
  325. r: parseInt(result[1], 16),
  326. g: parseInt(result[2], 16),
  327. b: parseInt(result[3], 16)
  328. } : null;
  329. },
  330. transDate: function(date, fmt) {
  331. if (!date) {
  332. return '--'
  333. }
  334. let _this = new Date(date * 1000)
  335. let o = {
  336. 'M+': _this.getMonth() + 1,
  337. 'd+': _this.getDate(),
  338. 'h+': _this.getHours(),
  339. 'm+': _this.getMinutes(),
  340. 's+': _this.getSeconds(),
  341. 'q+': Math.floor((_this.getMonth() + 3) / 3),
  342. 'S': _this.getMilliseconds()
  343. }
  344. if (/(y+)/.test(fmt)) {
  345. fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
  346. }
  347. for (let k in o) {
  348. if (new RegExp('(' + k + ')').test(fmt)) {
  349. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  350. }
  351. }
  352. return fmt
  353. },
  354. isNumber: function(val) {
  355. let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  356. let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  357. if (regPos.test(val) || regNeg.test(val)) {
  358. return true;
  359. } else {
  360. return false;
  361. }
  362. },
  363. //判断字符串是否为空
  364. isEmpty: function(str) {
  365. if (str === '' || str === undefined || str === null) {
  366. return true;
  367. } else {
  368. return false;
  369. }
  370. },
  371. expireTime: function(str) {
  372. if (!str) {
  373. return;
  374. }
  375. let NowTime = new Date().getTime();
  376. //IOS系统直接使用new Date('2018-10-29 11:25:21'),在IOS上获取不到对应的时间对象。
  377. let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
  378. if (totalSecond < 0) {
  379. return;
  380. }
  381. return totalSecond / 1000
  382. },
  383. /**
  384. * 统一下单请求
  385. */
  386. payOrder: function(orderId) {
  387. return new Promise(function(resolve, reject) {
  388. utils.request('pay/prepay', {
  389. orderId: orderId
  390. }, 'POST').then((res) => {
  391. if (res.errno === 0) {
  392. let payParam = res.data;
  393. uni.requestPayment({
  394. 'timeStamp': payParam.timeStamp,
  395. 'nonceStr': payParam.nonceStr,
  396. 'package': payParam.package,
  397. 'signType': payParam.signType,
  398. 'paySign': payParam.paySign,
  399. 'success': function(res) {
  400. console.log(res)
  401. resolve(res);
  402. },
  403. 'fail': function(res) {
  404. console.log(res)
  405. reject(res);
  406. },
  407. 'complete': function(res) {
  408. console.log(res)
  409. reject(res);
  410. }
  411. });
  412. } else {
  413. reject(res);
  414. }
  415. });
  416. });
  417. },
  418. /**
  419. * 调用微信登录
  420. */
  421. login: function() {
  422. return new Promise(function(resolve, reject) {
  423. uni.login({
  424. success: function(res) {
  425. if (res.code) {
  426. resolve(res);
  427. } else {
  428. reject(res);
  429. }
  430. },
  431. fail: function(err) {
  432. reject(err);
  433. }
  434. });
  435. });
  436. },
  437. loginH5: function(data){
  438. data.interfaceUrl = "/"
  439. return utils.request("anno/token", data, "post", "application/json");
  440. },
  441. randomNum: function(len, radix) {
  442. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  443. const uuid = []
  444. radix = radix || chars.length
  445. if (len) {
  446. // Compact form
  447. for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix ]
  448. } else {
  449. // rfc4122, version 4 form
  450. let r
  451. // rfc4122 requires these characters
  452. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
  453. uuid[14] = '4'
  454. // Fill in random data. At i==19 set the high bits of clock sequence as
  455. // per rfc4122, sec. 4.1.5
  456. for (let i = 0; i < 36; i++) {
  457. if (!uuid[i]) {
  458. r = 0 | Math.random() * 16
  459. uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
  460. }
  461. }
  462. }
  463. return uuid.join('') + new Date().getTime()
  464. },
  465. initQueryParams:function(params){
  466. const defParams = {
  467. size: 10,
  468. current: 1,
  469. sort: 'id',
  470. order: 'descending',
  471. model: {
  472. },
  473. map: {},
  474. timeRange: null
  475. };
  476. return params ? { ...defParams, ...params } : defParams;
  477. }
  478. }
  479. module.exports = {
  480. interfaceUrl: utils.interfaceUrl,
  481. toast: utils.toast,
  482. modal: utils.modal,
  483. isAndroid: utils.isAndroid,
  484. isIphoneX: utils.isIphoneX,
  485. constNum: utils.constNum,
  486. request: utils.request,
  487. uploadFile: utils.uploadFile,
  488. tuiJsonp: utils.tuiJsonp,
  489. setUserInfo: utils.setUserInfo,
  490. getToken: utils.getToken,
  491. trim: utils.trim,
  492. replaceAll: utils.replaceAll,
  493. formatNumber: utils.formatNumber,
  494. rmoney: utils.rmoney,
  495. dateformat: utils.dateformat,
  496. formatDate: utils.formatDate,
  497. getDistance: utils.getDistance,
  498. isMobile: utils.isMobile,
  499. rgbToHex: utils.rgbToHex,
  500. hexToRgb: utils.hexToRgb,
  501. transDate: utils.transDate,
  502. isNumber: utils.isNumber,
  503. isEmpty: utils.isEmpty,
  504. expireTime: utils.expireTime,
  505. payOrder: utils.payOrder,
  506. login: utils.login,
  507. loginH5: utils.loginH5,
  508. randomNum: utils.randomNum,
  509. initQueryParams: utils.initQueryParams
  510. }