util.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. getNowDate: function(num) {
  184. let date = new Date();
  185. date.setTime(date.getTime()+24*60*60*1000 * num );
  186. let d = date.getDate();
  187. d = d < 10 ? ('0' + d) : d;
  188. let m = date.getMonth() + 1;
  189. m = m <10 ? ('0' + m) : m;
  190. return date.getFullYear()+"-" + m + "-" + d;
  191. },
  192. tuiJsonp: function(url, callback, callbackname) {
  193. // #ifdef H5
  194. window[callbackname] = callback;
  195. let tuiScript = document.createElement("script");
  196. tuiScript.src = url;
  197. tuiScript.type = "text/javascript";
  198. document.head.appendChild(tuiScript);
  199. document.head.removeChild(tuiScript);
  200. // #endif
  201. },
  202. //设置用户信息
  203. setUserInfo: function(mobile, token) {
  204. uni.setStorageSync("X-Nideshop-Token", token)
  205. uni.setStorageSync("mobile", mobile)
  206. },
  207. //获取token
  208. getToken: function() {
  209. return uni.getStorageSync("token")
  210. },
  211. //去空格
  212. trim: function(value) {
  213. return value.replace(/(^\s*)|(\s*$)/g, "");
  214. },
  215. //内容替换
  216. replaceAll: function(text, repstr, newstr) {
  217. return text.replace(new RegExp(repstr, "gm"), newstr);
  218. },
  219. //格式化手机号码
  220. formatNumber: function(num) {
  221. return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
  222. },
  223. //金额格式化
  224. rmoney: function(money) {
  225. return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
  226. /\,$/, '').split('').reverse().join('');
  227. },
  228. // 时间格式化输出,如11:03 25:19 每1s都会调用一次
  229. dateformat: function(micro_second) {
  230. // 总秒数
  231. var second = Math.floor(micro_second / 1000);
  232. // 天数
  233. var day = Math.floor(second / 3600 / 24);
  234. // 小时
  235. var hr = Math.floor(second / 3600 % 24);
  236. // 分钟
  237. var min = Math.floor(second / 60 % 60);
  238. // 秒
  239. var sec = Math.floor(second % 60);
  240. return {
  241. day,
  242. hr: hr < 10 ? '0' + hr : hr,
  243. min: min < 10 ? '0' + min : min,
  244. sec: sec < 10 ? '0' + sec : sec,
  245. second: second
  246. }
  247. },
  248. //日期格式化
  249. formatDate: function(formatStr, fdate) {
  250. if (fdate) {
  251. if (~fdate.indexOf('.')) {
  252. fdate = fdate.substring(0, fdate.indexOf('.'));
  253. }
  254. fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
  255. var fTime, fStr = 'ymdhis';
  256. if (!formatStr)
  257. formatStr = "y-m-d h:i:s";
  258. if (fdate)
  259. fTime = new Date(fdate);
  260. else
  261. fTime = new Date();
  262. var month = fTime.getMonth() + 1;
  263. var day = fTime.getDate();
  264. var hours = fTime.getHours();
  265. var minu = fTime.getMinutes();
  266. var second = fTime.getSeconds();
  267. month = month < 10 ? '0' + month : month;
  268. day = day < 10 ? '0' + day : day;
  269. hours = hours < 10 ? ('0' + hours) : hours;
  270. minu = minu < 10 ? '0' + minu : minu;
  271. second = second < 10 ? '0' + second : second;
  272. var formatArr = [
  273. fTime.getFullYear().toString(),
  274. month.toString(),
  275. day.toString(),
  276. hours.toString(),
  277. minu.toString(),
  278. second.toString()
  279. ]
  280. for (var i = 0; i < formatArr.length; i++) {
  281. formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
  282. }
  283. return formatStr;
  284. } else {
  285. return "";
  286. }
  287. },
  288. getDistance: function(lat1, lng1, lat2, lng2) {
  289. function Rad(d) {
  290. return d * Math.PI / 180.0;
  291. }
  292. if (!lat1 || !lng1) {
  293. return '';
  294. }
  295. // lat1用户的纬度
  296. // lng1用户的经度
  297. // lat2商家的纬度
  298. // lng2商家的经度
  299. let radLat1 = Rad(lat1);
  300. let radLat2 = Rad(lat2);
  301. let a = radLat1 - radLat2;
  302. let b = Rad(lng1) - Rad(lng2);
  303. let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
  304. Math.sin(b / 2), 2)));
  305. s = s * 6378.137;
  306. s = Math.round(s * 10000) / 10000;
  307. s = '(距您' + s.toFixed(2) + '公里)' //保留两位小数
  308. return s
  309. },
  310. isMobile: function(mobile) {
  311. if (!mobile) {
  312. utils.toast('请输入手机号码');
  313. return false
  314. }
  315. if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
  316. utils.toast('手机号不正确');
  317. return false
  318. }
  319. return true
  320. },
  321. rgbToHex: function(r, g, b) {
  322. return "#" + utils.toHex(r) + utils.toHex(g) + utils.toHex(b)
  323. },
  324. toHex: function(n) {
  325. n = parseInt(n, 10);
  326. if (isNaN(n)) return "00";
  327. n = Math.max(0, Math.min(n, 255));
  328. return "0123456789ABCDEF".charAt((n - n % 16) / 16) +
  329. "0123456789ABCDEF".charAt(n % 16);
  330. },
  331. hexToRgb(hex) {
  332. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  333. return result ? {
  334. r: parseInt(result[1], 16),
  335. g: parseInt(result[2], 16),
  336. b: parseInt(result[3], 16)
  337. } : null;
  338. },
  339. transDate: function(date, fmt) {
  340. if (!date) {
  341. return '--'
  342. }
  343. let _this = new Date(date * 1000)
  344. let o = {
  345. 'M+': _this.getMonth() + 1,
  346. 'd+': _this.getDate(),
  347. 'h+': _this.getHours(),
  348. 'm+': _this.getMinutes(),
  349. 's+': _this.getSeconds(),
  350. 'q+': Math.floor((_this.getMonth() + 3) / 3),
  351. 'S': _this.getMilliseconds()
  352. }
  353. if (/(y+)/.test(fmt)) {
  354. fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + '').substr(4 - RegExp.$1.length))
  355. }
  356. for (let k in o) {
  357. if (new RegExp('(' + k + ')').test(fmt)) {
  358. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  359. }
  360. }
  361. return fmt
  362. },
  363. isNumber: function(val) {
  364. let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  365. let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  366. if (regPos.test(val) || regNeg.test(val)) {
  367. return true;
  368. } else {
  369. return false;
  370. }
  371. },
  372. //判断字符串是否为空
  373. isEmpty: function(str) {
  374. if (str === '' || str === undefined || str === null) {
  375. return true;
  376. } else {
  377. return false;
  378. }
  379. },
  380. expireTime: function(str) {
  381. if (!str) {
  382. return;
  383. }
  384. let NowTime = new Date().getTime();
  385. //IOS系统直接使用new Date('2018-10-29 11:25:21'),在IOS上获取不到对应的时间对象。
  386. let totalSecond = Date.parse(str.replace(/-/g, '/')) - NowTime || [];
  387. if (totalSecond < 0) {
  388. return;
  389. }
  390. return totalSecond / 1000
  391. },
  392. /**
  393. * 统一下单请求
  394. */
  395. payOrder: function(orderId) {
  396. return new Promise(function(resolve, reject) {
  397. utils.request('pay/prepay', {
  398. orderId: orderId
  399. }, 'POST').then((res) => {
  400. if (res.errno === 0) {
  401. let payParam = res.data;
  402. uni.requestPayment({
  403. 'timeStamp': payParam.timeStamp,
  404. 'nonceStr': payParam.nonceStr,
  405. 'package': payParam.package,
  406. 'signType': payParam.signType,
  407. 'paySign': payParam.paySign,
  408. 'success': function(res) {
  409. console.log(res)
  410. resolve(res);
  411. },
  412. 'fail': function(res) {
  413. console.log(res)
  414. reject(res);
  415. },
  416. 'complete': function(res) {
  417. console.log(res)
  418. reject(res);
  419. }
  420. });
  421. } else {
  422. reject(res);
  423. }
  424. });
  425. });
  426. },
  427. /**
  428. * 调用微信登录
  429. */
  430. login: function() {
  431. return new Promise(function(resolve, reject) {
  432. uni.login({
  433. success: function(res) {
  434. if (res.code) {
  435. resolve(res);
  436. } else {
  437. reject(res);
  438. }
  439. },
  440. fail: function(err) {
  441. reject(err);
  442. }
  443. });
  444. });
  445. },
  446. loginH5: function(data){
  447. data.interfaceUrl = "/"
  448. //return utils.request("api/oauth/anno/token", data, "post", "application/json");
  449. return utils.request("anno/token", data, "post", "application/json");
  450. },
  451. randomNum: function(len, radix) {
  452. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  453. const uuid = []
  454. radix = radix || chars.length
  455. if (len) {
  456. // Compact form
  457. for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix ]
  458. } else {
  459. // rfc4122, version 4 form
  460. let r
  461. // rfc4122 requires these characters
  462. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
  463. uuid[14] = '4'
  464. // Fill in random data. At i==19 set the high bits of clock sequence as
  465. // per rfc4122, sec. 4.1.5
  466. for (let i = 0; i < 36; i++) {
  467. if (!uuid[i]) {
  468. r = 0 | Math.random() * 16
  469. uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
  470. }
  471. }
  472. }
  473. return uuid.join('') + new Date().getTime()
  474. },
  475. initQueryParams:function(params){
  476. const defParams = {
  477. size: 10,
  478. current: 1,
  479. sort: 'id',
  480. order: 'descending',
  481. model: {
  482. },
  483. map: {},
  484. timeRange: null
  485. };
  486. return params ? { ...defParams, ...params } : defParams;
  487. }
  488. }
  489. module.exports = {
  490. interfaceUrl: utils.interfaceUrl,
  491. toast: utils.toast,
  492. modal: utils.modal,
  493. isAndroid: utils.isAndroid,
  494. isIphoneX: utils.isIphoneX,
  495. constNum: utils.constNum,
  496. request: utils.request,
  497. uploadFile: utils.uploadFile,
  498. tuiJsonp: utils.tuiJsonp,
  499. setUserInfo: utils.setUserInfo,
  500. getToken: utils.getToken,
  501. trim: utils.trim,
  502. replaceAll: utils.replaceAll,
  503. formatNumber: utils.formatNumber,
  504. rmoney: utils.rmoney,
  505. dateformat: utils.dateformat,
  506. formatDate: utils.formatDate,
  507. getDistance: utils.getDistance,
  508. isMobile: utils.isMobile,
  509. rgbToHex: utils.rgbToHex,
  510. hexToRgb: utils.hexToRgb,
  511. transDate: utils.transDate,
  512. isNumber: utils.isNumber,
  513. isEmpty: utils.isEmpty,
  514. expireTime: utils.expireTime,
  515. payOrder: utils.payOrder,
  516. login: utils.login,
  517. loginH5: utils.loginH5,
  518. randomNum: utils.randomNum,
  519. initQueryParams: utils.initQueryParams,
  520. getNowDate: utils.getNowDate
  521. }