index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import Validate from './validate.js';
  2. import regeneratorRuntime from './wxPromise.min.js'
  3. export default {
  4. //验证
  5. Validate,
  6. regeneratorRuntime,
  7. //格式化时间
  8. formatTime(date, format) {
  9. let newFormat = format || 'YY-M-D h:m:s';
  10. let formatNumber = this.formatNumber;
  11. let newDate = date || new Date();
  12. if (Object.prototype.toString.call(newDate).slice(8, -1) !== "Date") {
  13. newDate = new Date(date);
  14. }
  15. let week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', '日', '一', '二', '三', '四', '五', '六'];
  16. return newFormat.replace(/YY|Y|M|D|h|m|s|week|星期/g, function (a) {
  17. switch (a) {
  18. case 'YY':
  19. return newDate.getFullYear();
  20. case 'Y':
  21. return (newDate.getFullYear() + '').slice(2);
  22. case 'M':
  23. return formatNumber(newDate.getMonth() + 1);
  24. case 'D':
  25. return formatNumber(newDate.getDate());
  26. case 'h':
  27. return formatNumber(newDate.getHours());
  28. case 'm':
  29. return formatNumber(newDate.getMinutes());
  30. case 's':
  31. return formatNumber(newDate.getSeconds());
  32. case '星期':
  33. return "星期" + week[newDate.getDay() + 7];
  34. case 'week':
  35. return week[newDate.getDay()];
  36. }
  37. })
  38. },
  39. //格式化数字
  40. formatNumber(n) {
  41. n = n.toString();
  42. return n[1] ? n : '0' + n
  43. },
  44. /**
  45. * 人性话格式时间
  46. */
  47. ctDate(date) {
  48. const minute = 1000 * 60;
  49. const hour = minute * 60;
  50. const day = hour * 24;
  51. const month = day * 30;
  52. if (!date) return "";
  53. const now = Date.now();
  54. let diffValue;
  55. let result;
  56. date = typeof date === "number" ? date : +(new Date(date));
  57. diffValue = now - date;
  58. let monthC = diffValue / month;
  59. let weekC = diffValue / (7 * day);
  60. let dayC = diffValue / day;
  61. let hourC = diffValue / hour;
  62. let minC = diffValue / minute;
  63. if (monthC >= 1) {
  64. result = parseInt(monthC) + "个月前";
  65. } else if (weekC >= 1) {
  66. result = parseInt(weekC) + "个星期前";
  67. } else if (dayC >= 1) {
  68. result = parseInt(dayC) + "天前";
  69. } else if (hourC >= 1) {
  70. result = parseInt(hourC) + "个小时前";
  71. } else if (minC >= 1) {
  72. result = parseInt(minC) + "分钟前";
  73. } else {
  74. result = "刚刚发表";
  75. }
  76. return result;
  77. },
  78. //返回类型
  79. typeOf(param) {
  80. return Object.prototype.toString.call(param).slice(8, -1)
  81. },
  82. //判断是否为空
  83. isEmpty(param) {
  84. //基本类型为空
  85. let condition1 = param === '' || param === null || param === undefined || param === "NaN" || param === false;
  86. let condition2;
  87. let condition3
  88. //引用类型为空
  89. if (!condition1) {
  90. condition2 = this.typeOf(param) === "Object" && Object.keys(param).length < 1;
  91. condition3 = this.typeOf(param) === "Array" && param.length < 1;
  92. }
  93. return condition1 || condition2 || condition3;
  94. },
  95. // 判断是否是数字
  96. isNum(param) {
  97. var reg = /^[0-9]+.?[0-9]*$/;
  98. if (reg.test(param)) {
  99. return true
  100. }
  101. return false
  102. },
  103. //检查授权
  104. checkAuth(name) {
  105. let that = this;
  106. return new Promise((resove, reject) => {
  107. wx.getSetting({
  108. success(res) {
  109. console.log(res.authSetting[`scope.${name}`], "res.authSetting")
  110. if (res.authSetting[`scope.${name}`]) {
  111. resove(true)
  112. } else {
  113. resove(false)
  114. }
  115. },
  116. fail() {
  117. that.networkError()
  118. }
  119. })
  120. })
  121. },
  122. //小程序自带获取定位
  123. getLocation() {
  124. let that = this;
  125. return new Promise((resove, reject) => {
  126. wx.getLocation({
  127. success: function (res) {
  128. resove(res)
  129. },
  130. fail: function (res) {
  131. reject(res)
  132. that.hideAll()
  133. }
  134. })
  135. })
  136. },
  137. //授权后调用百度地图接口获取当前城市
  138. getLocation(_this) {
  139. // 微信获得经纬度
  140. let ak = 'GoI7BxLpfvBEyf1TcMXCloi99Vov7flZ'
  141. return new Promise((resolve, reject) => {
  142. wx.getLocation({
  143. type: 'wgs84', //gcj02 // wgs84
  144. success: function (res) {
  145. let latitude = res.latitude
  146. let longitude = res.longitude
  147. wx.request({
  148. url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude,
  149. data: {},
  150. header: {
  151. 'Content-Type': 'application/json'
  152. },
  153. success: function (ops) {
  154. let {
  155. province,
  156. city,
  157. district
  158. } = ops.data.result.addressComponent
  159. let region = province + city + district
  160. resolve({
  161. region,
  162. latitude,
  163. longitude
  164. })
  165. },
  166. fail: function (err) {
  167. wx.showModal({
  168. title: '信息提示',
  169. content: '请求失败',
  170. showCancel: false,
  171. confirmColor: '#f37938'
  172. });
  173. },
  174. complete: function () { }
  175. })
  176. },
  177. fail(err) {
  178. wx.showModal({
  179. title: '未授权',
  180. content: `为保证功能正常使用,点击「右上角」-「关于**」-「右上角」-「设置」,打开位置权限后重试`,
  181. showCancel: false,
  182. })
  183. resolve()
  184. },
  185. complete: (data) => {
  186. }
  187. })
  188. })
  189. },
  190. //网络错误提示
  191. networkError(status = 0) {
  192. const netMessage = {
  193. "0": "网络异常",
  194. "1": "请求超时",
  195. "500": "服务器错误",
  196. "404": "请求地址错误"
  197. }
  198. if (status != 500) return;
  199. this.showFail(netMessage[status])
  200. },
  201. /* 打开提示信息 */
  202. showModal(content = "服务器错误") {
  203. wx.showModal({
  204. title: "提示",
  205. content,
  206. showCancel: false
  207. })
  208. },
  209. showLoading(title = "加载中") {
  210. wx.showLoading({
  211. title,
  212. mask: true
  213. })
  214. },
  215. showSuccess(title = "操作成功") {
  216. wx.showToast({
  217. title,
  218. })
  219. },
  220. showFail(title = "操作失败") {
  221. wx.showToast({
  222. title,
  223. icon: 'none'
  224. })
  225. },
  226. hideLoading() {
  227. wx.hideLoading()
  228. },
  229. /* 隐藏所有提示信息 */
  230. hideAll() {
  231. wx.hideLoading();
  232. wx.stopPullDownRefresh();
  233. wx.hideNavigationBarLoading();
  234. },
  235. //获取标签上data
  236. getFormData(e) {
  237. return e.detail.target.dataset
  238. },
  239. getData(e) {
  240. return e.currentTarget.dataset
  241. },
  242. //获表单控件值
  243. getValue(e) {
  244. return e.detail.value
  245. },
  246. //跳转
  247. goUrl(url, method = "navigateTo") {
  248. if (!url) {
  249. return;
  250. }
  251. //拨打电话
  252. if (url.indexOf('tel:') > -1) {
  253. wx.makePhoneCall({
  254. phoneNumber: url.split(':')[1],
  255. })
  256. return;
  257. }
  258. //网页跳转
  259. if (url.indexOf('http') > -1) {
  260. wx.navigateTo({
  261. url: `/pages/common/webview/webview?url=${url}`,
  262. })
  263. return;
  264. }
  265. //小程序跳转
  266. if (url.indexOf('wx') == 0) {
  267. var appIdData, pathData = '',
  268. envVersionData = 'release';
  269. var urlArr = url.split(':');
  270. if (urlArr.length == 1) {
  271. appIdData = urlArr[0];
  272. } else if (urlArr.length == 2) {
  273. appIdData = urlArr[0];
  274. pathData = urlArr[1];
  275. } else if (urlArr.length == 3) {
  276. appIdData = urlArr[0];
  277. pathData = urlArr[1];
  278. envVersionData = urlArr[2];
  279. }
  280. wx.navigateToMiniProgram({
  281. appId: appIdData,
  282. path: pathData,
  283. extraData: {
  284. lb: 'longbing'
  285. },
  286. envVersion: envVersionData,
  287. success(res) {
  288. // 打开成功
  289. }
  290. })
  291. return;
  292. }
  293. //消息插件跳转
  294. if (url.indexOf('/nova-chat') == 0) {
  295. getApp().JIMServ.chatNavigate(url);
  296. return
  297. }
  298. //商城组件跳转
  299. if (url.indexOf('/mshop') == 0) {
  300. wx.navigateTo({
  301. url
  302. })
  303. return
  304. }
  305. //正常页面跳转
  306. wx[method]({
  307. url
  308. })
  309. },
  310. //复制文本
  311. setClipboard(content) {
  312. wx.setClipboardData({
  313. data: content,
  314. success: function (res) {
  315. wx.getClipboardData({
  316. success: function (res) {
  317. console.log('复制文本成功 ==>>', res.data);
  318. }
  319. });
  320. }
  321. });
  322. },
  323. //格式化参数对象
  324. setOptions(o) {
  325. return encodeURIComponent(JSON.stringify(o))
  326. },
  327. //解析参数对象
  328. getOptions(o) {
  329. return JSON.parse(decodeURIComponent(o))
  330. },
  331. //获取页面对象,0时为当前页面
  332. getPage(index = 0) {
  333. let pages = getCurrentPages();
  334. let page = pages[pages.length - 1 + index]
  335. return page
  336. },
  337. //发起支付
  338. pay(orderInfo) {
  339. let that = this;
  340. return new Promise((resove, reject) => {
  341. wx.requestPayment({
  342. timeStamp: orderInfo.timeStamp,
  343. nonceStr: orderInfo.nonceStr,
  344. 'package': orderInfo.package,
  345. signType: orderInfo.signType,
  346. paySign: orderInfo.paySign,
  347. success: function (res) {
  348. resove(true)
  349. },
  350. fail: function (res) {
  351. that.showFail("支付失败")
  352. },
  353. complete: function (res) {
  354. console.log(res)
  355. },
  356. })
  357. })
  358. },
  359. //深拷贝
  360. deepCopy(o) {
  361. let that = this;
  362. if (o instanceof Array) {
  363. var n = [];
  364. for (var i = 0; i < o.length; ++i) {
  365. n[i] = that.deepCopy(o[i]);
  366. }
  367. return n;
  368. } else if (o instanceof Function) {
  369. var n = new Function("return " + o.toString())();
  370. return n
  371. } else if (o instanceof Object) {
  372. var n = {}
  373. for (var i in o) {
  374. n[i] = that.deepCopy(o[i]);
  375. }
  376. return n;
  377. } else {
  378. return o;
  379. }
  380. },
  381. //获取数组中的id字符串,以逗号隔开
  382. getIds: function (o) {
  383. let ids = [];
  384. o = o || [];
  385. o.forEach((item) => {
  386. ids.push(item.id || item)
  387. })
  388. return ids.join(',');
  389. },
  390. //查询某个字符在字符串的位置
  391. searchSubStr: function (str, subStr) {
  392. let positions = [];
  393. let pos = str.indexOf(subStr);
  394. while (pos > -1) {
  395. positions.push(pos);
  396. pos = str.indexOf(subStr, pos + 1);
  397. }
  398. return positions
  399. },
  400. //将一个数组根据规则分为两个
  401. partition: function (arr, isValid) {
  402. arr.reduce(
  403. ([pass, fail], elem) =>
  404. isValid(elem) ? [
  405. [...pass, elem], fail
  406. ] : [pass, [...fail, elem]], [
  407. [],
  408. []
  409. ],
  410. )
  411. },
  412. /*
  413. * 获取链接某个参数
  414. * url 链接地址
  415. * name 参数名称
  416. */
  417. getUrlParam: function (url, name) {
  418. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  419. var r = url.split('?')[1].match(reg); //匹配目标参数
  420. if (r != null) return unescape(r[2]);
  421. return null; //返回参数值
  422. },
  423. /*
  424. * 格式化扫码二维码的参数scene例如a=1&b=2转化为对象{a:1,b:2}
  425. * param 参数scene
  426. */
  427. getSceneParam: function (param) {
  428. if (!param) return {};
  429. let paramArr = param.split('&');
  430. let paramObj = {};
  431. for (let item of paramArr) {
  432. let sp = item.split("=")
  433. paramObj[sp[0]] = sp[1]
  434. }
  435. return paramObj
  436. },
  437. /**
  438. * @desc 函数防抖
  439. * @param func 函数
  440. * @param wait 延迟执行毫秒数
  441. * @param immediate true 表立即执行,false 表非立即执行
  442. */
  443. debounce: function (func, wait, immediate) {
  444. var timeout = null;
  445. return function () {
  446. var context = this;
  447. var args = arguments;
  448. if (timeout) clearTimeout(timeout);
  449. if (immediate) {
  450. let callNow = !timeout;
  451. timeout = setTimeout(function () {
  452. timeout = null;
  453. }, wait)
  454. if (callNow) func.apply(context, args)
  455. } else {
  456. timeout = setTimeout(function () {
  457. func.apply(context, args)
  458. }, wait);
  459. }
  460. }
  461. },
  462. getHostname(url) {
  463. var reg = /^http(s)?:\/\/(.*?)\//
  464. // 必须是http开头或者https开头,结尾为'/'
  465. var ToReplace = 'Host/'
  466. url.replace(reg, ToReplace)
  467. url = reg.exec(url)[2];
  468. return url;
  469. },
  470. nowPageIndex(tabBar) {
  471. let pages = getCurrentPages();
  472. let page = pages[pages.length - 1]
  473. let route = page.__route__
  474. let nowPageIndex;
  475. for (let i in tabBar.list) {
  476. let item = tabBar.list[i]
  477. if (item.pagePath.includes(route)) {
  478. nowPageIndex = i
  479. }
  480. }
  481. return nowPageIndex;
  482. },
  483. getNavBarHeight() {
  484. let {
  485. statusBarHeight
  486. } = wx.getSystemInfoSync();
  487. let custom = wx.getMenuButtonBoundingClientRect();
  488. let navBarHeight = custom.bottom + custom.top - statusBarHeight;
  489. //let navBarHeight = statusBarHeight+44
  490. return navBarHeight
  491. },
  492. splitArr(list, num) {
  493. let newList = [];
  494. let index = 0;
  495. while (index < list.length) {
  496. newList.push(list.slice(index, index += num));
  497. }
  498. return newList
  499. },
  500. getPageConfig(configInfo, arr = []) {
  501. let pageConfig = {};
  502. for (let i in arr) {
  503. let key = arr[i]
  504. pageConfig[key] = configInfo[key]
  505. }
  506. return pageConfig
  507. },
  508. //解析文件类型
  509. getFileType(url) {
  510. let pdfReg = /^.+(\.pdf)$/
  511. let txtReg = /^.+(\.txt)$/
  512. let wordReg = /^.+(\.doc|\.docx)$/
  513. let excelReg = /^.+(\.xls|\.xlsx)$/
  514. let jpgPng = /^.+(\.png)$/
  515. let jpgJpg = /^.+(\.jpg)$/
  516. let jpgJpeg = /^.+(\.jpeg)$/
  517. if (pdfReg.test(url)) {
  518. return 'pdf'
  519. }
  520. if (txtReg.test(url)) {
  521. return 'txt'
  522. }
  523. if (wordReg.test(url)) {
  524. return 'docx'
  525. }
  526. if (excelReg.test(url)) {
  527. return 'xls'
  528. }
  529. if (jpgPng.test(url)) {
  530. return 'png'
  531. }
  532. if (jpgJpg.test(url)) {
  533. return 'jpg'
  534. }
  535. if (jpgJpeg.test(url)) {
  536. return 'jpeg'
  537. }
  538. },
  539. }