util.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /**
  2. * 判断是否有值
  3. */
  4. const hasVal = v => {
  5. return typeof v !== 'undefined' && v !== null
  6. }
  7. /**
  8. * 判断是否是字符串
  9. */
  10. const isStr = v => {
  11. return typeof v === 'string'
  12. }
  13. /**
  14. * 判断是否是函数
  15. */
  16. const isFn = v => {
  17. return typeof v === 'function'
  18. }
  19. /**
  20. * 判断是否是数组
  21. */
  22. const isArr = v => {
  23. return Array.isArray ? Array.isArray(v) : Object.prototype.toString.call([]) === '[object Array]'
  24. }
  25. /**
  26. * 判断是否是对象
  27. */
  28. const isObj = v => {
  29. return v !== null && typeof v === 'object'
  30. }
  31. /**
  32. * 判断是否是空对象
  33. */
  34. const isEmptyObj = v => {
  35. if (v !== null && typeof v === 'object') {
  36. for (const i in v)
  37. return false
  38. return true
  39. }
  40. return true
  41. }
  42. /**
  43. * 对个位数前补零
  44. */
  45. const formatNumber = n => {
  46. n = n.toString()
  47. return n[1] ? n : '0' + n
  48. }
  49. /**
  50. * 日期时间格式化
  51. * 2018-01-01 23:59:59
  52. */
  53. const formatDateTime = (date, { dateStr = '-', medianStr = ' ', timeStr = ':' } = {}) => {
  54. const year = date.getFullYear()
  55. const month = date.getMonth() + 1
  56. const day = date.getDate()
  57. const hour = date.getHours()
  58. const minute = date.getMinutes()
  59. const second = date.getSeconds()
  60. return [year, month, day].map(formatNumber).join(dateStr) + medianStr + [hour, minute, second].map(formatNumber).join(timeStr)
  61. }
  62. /**
  63. * 日期格式化
  64. * 2018-01-01
  65. */
  66. const formatDate = (date, dateStr = '-') => {
  67. const year = date.getFullYear()
  68. const month = date.getMonth() + 1
  69. const day = date.getDate()
  70. return [year, month, day].map(formatNumber).join(dateStr)
  71. }
  72. /**
  73. * 时间格式化
  74. * 23:59:59
  75. */
  76. const formatTime = (date, timeStr = ':') => {
  77. const hour = date.getHours()
  78. const minute = date.getMinutes()
  79. const second = date.getSeconds()
  80. return [hour, minute, second].map(formatNumber).join(timeStr)
  81. }
  82. /**
  83. * 路径格式化
  84. */
  85. const formatUrl = (url, obj) => {
  86. const arr = []
  87. if (isObj(obj)) {
  88. for (let i in obj) {
  89. arr.push(`${i}=${obj[i]}`)
  90. }
  91. return url.indexOf('?') < 0 ? url + '?' + arr.join('&') : url + '&' + arr.join('&')
  92. }
  93. return url
  94. }
  95. /**
  96. * 判断当前月份的总天数
  97. */
  98. const thisMonthLenth = ({ year, month }) => {
  99. let len = 0
  100. if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
  101. len = 31
  102. } else if (month == 4 || month == 6 || month == 9 || month == 11) {
  103. len = 30
  104. } else if (month == 2) {
  105. if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {
  106. len = 29
  107. } else {
  108. len = 28
  109. }
  110. }
  111. return len
  112. }
  113. /**
  114. * 节流
  115. * fn是我们需要包装的事件回调, interval是时间间隔的阈值
  116. */
  117. const throttle = (fn, interval = 800) => {
  118. // last为上一次触发回调的时间
  119. let last = 0
  120. // 将throttle处理结果当作函数返回
  121. return function () {
  122. // 保留调用时的this上下文
  123. let context = this
  124. // 保留调用时传入的参数
  125. let args = arguments
  126. // 记录本次触发回调的时间
  127. let now = +new Date()
  128. // 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
  129. if (now - last >= interval) {
  130. // 如果时间间隔大于我们设定的时间间隔阈值,则执行回调
  131. last = now;
  132. fn.apply(context, args);
  133. }
  134. }
  135. }
  136. /**
  137. * 防抖
  138. * fn是我们需要包装的事件回调, delay是每次推迟执行的等待时间
  139. */
  140. const debounce = (fn, delay = 800) => {
  141. // 定时器
  142. let timer = null
  143. // 将debounce处理结果当作函数返回
  144. return function () {
  145. // 保留调用时的this上下文
  146. let context = this
  147. // 保留调用时传入的参数
  148. let args = arguments
  149. // 每次事件被触发时,都去清除之前的旧定时器
  150. if (timer) {
  151. clearTimeout(timer)
  152. }
  153. // 设立新定时器
  154. timer = setTimeout(function () {
  155. fn.apply(context, args)
  156. }, delay)
  157. }
  158. }
  159. /**
  160. * 加强版节流
  161. * fn是我们需要包装的事件回调, delay是时间间隔的阈值
  162. */
  163. const throttleDebounce = (fn, delay = 800) => {
  164. // last为上一次触发回调的时间, timer是定时器
  165. let last = 0, timer = null
  166. // 将throttle处理结果当作函数返回
  167. return function () {
  168. // 保留调用时的this上下文
  169. let context = this
  170. // 保留调用时传入的参数
  171. let args = arguments
  172. // 记录本次触发回调的时间
  173. let now = +new Date()
  174. // 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
  175. if (now - last < delay) {
  176. // 如果时间间隔小于我们设定的时间间隔阈值,则为本次触发操作设立一个新的定时器
  177. clearTimeout(timer)
  178. timer = setTimeout(function () {
  179. last = now
  180. fn.apply(context, args)
  181. }, delay)
  182. } else {
  183. // 如果时间间隔超出了我们设定的时间间隔阈值,那就不等了,无论如何要反馈给用户一次响应
  184. last = now
  185. fn.apply(context, args)
  186. }
  187. }
  188. }
  189. /**
  190. * 微信授权接口封装
  191. */
  192. const wxSetting = ({ scope, text }) => {
  193. return new Promise((resolve, reject) => {
  194. wx.getSetting({
  195. success: res => {
  196. if (isEmptyObj(res.authSetting)) {
  197. resolve(Object.assign(res, { type: 1, text: `请手动点击${text}` }))
  198. } else if (res.authSetting[scope] === true) {
  199. resolve(Object.assign(res, { type: 2, text: `默认${text}成功` }))
  200. } else if (res.authSetting[scope] === false) {
  201. wx.showModal({
  202. content: `检测到您没打开${text},是否去设置打开?`,
  203. confirmText: "确认",
  204. cancelText: "取消",
  205. success: res => {
  206. if (res.confirm) {
  207. wx.openSetting({
  208. success: res => {
  209. if (res.authSetting[scope]) {
  210. resolve(Object.assign(res, { type: 3, text: `手动设置${text}成功` }))
  211. } else {
  212. reject(Object.assign(res, { type: 5, text: `没有手动设置${text}` }))
  213. }
  214. },
  215. fail: res => {
  216. reject(Object.assign(res, { type: 4, text: `打开手动设置${text}失败` }))
  217. }
  218. })
  219. } else {
  220. reject(Object.assign(res, { type: 3, text: `拒绝打开手动设置${text}` }))
  221. }
  222. },
  223. fail: res => {
  224. reject(Object.assign(res, { type: 2, text: `弹出${text}提示框失败` }))
  225. }
  226. })
  227. } else {
  228. wx.authorize({
  229. scope,
  230. success: res => {
  231. resolve(Object.assign(res, { type: 4, text: `自动获取${text}成功` }))
  232. },
  233. fail: res => {
  234. reject(Object.assign(res, { type: 6, text: `自动获取${text}失败` }))
  235. }
  236. })
  237. }
  238. },
  239. fail: res => {
  240. reject(res, { type: 1, text: `获取${text}失败` })
  241. }
  242. })
  243. })
  244. }
  245. /**
  246. * 获取微信用户信息授权
  247. */
  248. const getWxUserInfoSetting = cb => {
  249. wxSetting({ scope: 'scope.userInfo', text: '微信用户信息授权' }).then((res) => {
  250. wx.setStorageSync('hasUserInfo', 1)
  251. if (isFn(cb)) cb(1, res)
  252. }).catch((res) => {
  253. wx.setStorageSync('hasUserInfo', 0)
  254. if (res.type != 6) {
  255. wx.showToast({
  256. title: res.text,
  257. icon: 'none'
  258. })
  259. }
  260. setTimeout(() => {
  261. wx.navigateBack({
  262. delta: 1
  263. })
  264. }, 1200)
  265. if (isFn(cb)) cb(0, res)
  266. })
  267. }
  268. /**
  269. * 获取微信定位授权
  270. */
  271. const getWxLocationSetting = cb => {
  272. wxSetting({ scope: 'scope.userLocation', text: '微信定位授权' }).then((res) => {
  273. wx.setStorageSync('hasPosition', 1)
  274. if (isFn(cb)) cb(1, res)
  275. }).catch((res) => {
  276. wx.setStorageSync('hasPosition', 0)
  277. wx.showToast({
  278. title: res.text,
  279. icon: 'none'
  280. })
  281. setTimeout(() => {
  282. wx.navigateBack({
  283. delta: 1
  284. })
  285. }, 1200)
  286. if (isFn(cb)) cb(0, res)
  287. })
  288. }
  289. /**
  290. * 获取微信相机授权
  291. */
  292. const getWxCameraSetting = cb => {
  293. wxSetting({ scope: 'scope.camera', text: '微信相机授权' }).then((res) => {
  294. wx.setStorageSync('hasCamera', 1)
  295. if (isFn(cb)) cb(1, res)
  296. }).catch((res) => {
  297. wx.setStorageSync('hasCamera', 0)
  298. wx.showToast({
  299. title: res.text,
  300. icon: 'none'
  301. })
  302. setTimeout(() => {
  303. wx.navigateBack({
  304. delta: 1
  305. })
  306. }, 1200)
  307. if (isFn(cb)) cb(0, res)
  308. })
  309. }
  310. /**
  311. * 获取系统信息
  312. */
  313. const systemInfo = wx.getSystemInfoSync()
  314. /**
  315. * 路由跳转
  316. */
  317. const routers = () => {
  318. const fn = (method) => {
  319. return (e) => {
  320. const { paras = null, url = null, msg = '暂未开放', delta = 1 } = e && e.currentTarget && e.currentTarget.dataset ? e.currentTarget.dataset : e && !e.currentTarget ? e : {}
  321. switch (method) {
  322. case 'navigateBack':
  323. wx.navigateBack({ delta })
  324. break
  325. default:
  326. if (!url) {
  327. wx.showToast({
  328. title: msg,
  329. icon: 'none'
  330. })
  331. return
  332. }
  333. wx[method]({
  334. url: `/${formatUrl(url, method === 'switchTab' ? null : paras)}`,
  335. success: res => { },
  336. fail: res => {
  337. wx.showToast({
  338. title: '跳转失败',
  339. icon: 'none'
  340. })
  341. }
  342. })
  343. }
  344. }
  345. }
  346. const arr = ['reLaunch', 'navigateTo', 'redirectTo', 'switchTab', 'navigateBack']
  347. const obj = {}
  348. for (const v of arr) {
  349. obj[v] = throttleDebounce(fn(v))
  350. }
  351. return obj
  352. }
  353. /**
  354. * 查看图片
  355. */
  356. const viewImage = throttleDebounce((e, type) => {
  357. const { images, index, baseurl, url = 'imgUrl' } = type ? e : e.currentTarget.dataset
  358. const arr = []
  359. if (isObj(images)) {
  360. for (const v of images) {
  361. arr.push(`${baseurl}${v[url] ? v[url] : v}`)
  362. }
  363. }
  364. wx.previewImage({
  365. current: arr[index],
  366. urls: arr
  367. })
  368. })
  369. /**
  370. * 分享控制层
  371. */
  372. const sharePage = ({ title = '私塾家', path = 'pages/index/index', imageUrl = null, msg = '转发成功' } = {}) => {
  373. return {
  374. title,
  375. path,
  376. imageUrl,
  377. success: res => {
  378. wx.showToast({
  379. title: msg,
  380. icon: 'success'
  381. })
  382. }
  383. }
  384. }
  385. /**
  386. * 获取全局值
  387. */
  388. const getGlobalVal = (e1, e2 = e1) => hasVal(getApp().globalData[e1]) ? getApp().globalData[e1] : hasVal(wx.getStorageSync(e2)) ? wx.getStorageSync(e2) : null
  389. /**
  390. * 统一调用微信支付
  391. */
  392. const wxPayment = ({ timeStamp = '', nonceStr = '', packageValue = '', signType = '', paySign = '' }) => {
  393. return new Promise((resolve, reject) => {
  394. wx.requestPayment({
  395. timeStamp,
  396. nonceStr,
  397. package: packageValue,
  398. signType,
  399. paySign,
  400. success: res => {
  401. if (res.errMsg == 'requestPayment:ok') {
  402. wx.showToast({
  403. title: '支付成功',
  404. icon: 'success'
  405. })
  406. resolve(res)
  407. } else {
  408. wx.showToast({
  409. title: '支付失败',
  410. icon: 'none'
  411. })
  412. reject(res)
  413. }
  414. },
  415. fail: res => {
  416. wx.showToast({
  417. title: '支付取消',
  418. icon: 'none'
  419. })
  420. reject(res)
  421. }
  422. })
  423. })
  424. }
  425. /**
  426. * 获取最新版本
  427. */
  428. const getUpdateManager = () => {
  429. const updateManager = wx.getUpdateManager()
  430. updateManager.onCheckForUpdate(res => {
  431. const { hasUpdate } = res
  432. if (hasUpdate) {
  433. wx.showToast({
  434. title: '已发现新版本哦',
  435. icon: 'none'
  436. })
  437. }
  438. })
  439. updateManager.onUpdateReady(() => {
  440. wx.showModal({
  441. title: '更新提示',
  442. content: '新版本已经准备好,是否重启应用?',
  443. success(res) {
  444. if (res.confirm) {
  445. updateManager.applyUpdate()
  446. }
  447. }
  448. })
  449. })
  450. updateManager.onUpdateFailed(() => {
  451. wx.showToast({
  452. title: '新版本下载失败',
  453. icon: 'none'
  454. })
  455. })
  456. }
  457. /**
  458. * fetch 网络请求封装
  459. * @param url{String} url【请求后台路径,默认必穿项,否则报错】
  460. * @param paras{Object} paras【请求后台路径拼接的参数,默认为空】
  461. * @param method{String} method【网络请求方法,默认POST】
  462. * @param data{Object} data【自定义传的参数数据,默认必传项,可为空对象】
  463. * @param continuousFn{Object} continuousFn: { fn: Function, param: Object } 续弦函数:当接口报登录失效401的时候 记录失效的当前状态,等待自动登录成功后接着运行
  464. */
  465. const fetch = ({ url = null, paras = {}, method = 'POST', data = {}, continuousFn = null }) => {
  466. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build, errorText = '出了点小问题' } = getApp().globalData
  467. const accessToken = getGlobalVal('accessToken') || ''
  468. const header = { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/json" }
  469. const showToast = (text) => {
  470. wx.showToast({
  471. title: text || errorText,
  472. icon: 'none'
  473. })
  474. }
  475. url = formatUrl(host + url, Object.assign({}, paras, { accessToken }))
  476. return new Promise((resolve, reject) => {
  477. wx.request({
  478. url,
  479. data,
  480. method,
  481. header,
  482. success: e => {
  483. const { statusCode, data } = e
  484. const { code, msg } = data
  485. switch (~~statusCode) {
  486. case 200:
  487. switch (~~code) {
  488. case 999:
  489. resolve(data)
  490. break
  491. default:
  492. if (url.indexOf('/user/checkToken') < 0) {
  493. showToast(msg)
  494. }
  495. reject(e)
  496. }
  497. if (loginTime > 0) {
  498. getApp().globalData.loginTime = 0
  499. }
  500. break
  501. case 401:
  502. getApp().globalData.loginTime = loginTime + 1
  503. if (loginTime < 2) {
  504. getApp().globalData.continuousFn = continuousFn
  505. getApp().login()
  506. } else {
  507. showToast('登录失效,稍后再试')
  508. reject(e)
  509. }
  510. break
  511. default:
  512. showToast()
  513. reject(e)
  514. }
  515. },
  516. fail: e => {
  517. showToast()
  518. reject(e)
  519. },
  520. complete: e => {
  521. getApp().globalData.isPending = true
  522. console.log({ url, request: data, response: e.data, globalData: getApp().globalData })
  523. }
  524. })
  525. })
  526. }
  527. /**
  528. * uploadFile 上传文件封装
  529. * @param url{String} url【请求后台路径,默认必穿项,否则报错】
  530. * @param paras{Object} paras【请求后台路径拼接的参数,默认为空】
  531. * @param file{String} file【微信小程序生成的临时文件资源路径】
  532. * @param data{Object} data【自定义传的参数数据,默认必传项,可为空对象】
  533. * @param continuousFn{Object} continuousFn: { fn: Function, param: Object } 续弦函数:当接口报登录失效401的时候 记录失效的当前状态,等待自动登录成功后接着运行
  534. */
  535. const uploadFile = ({ url = null, paras = {}, file = null, data = {}, continuousFn = null }) => {
  536. const { host, loginTime, wechatsys, phoneimei, phonesys, phonetype, version, platform, build, errorText = '出了点小问题' } = getApp().globalData
  537. const accessToken = getGlobalVal('accessToken') || ''
  538. const header = { wechatsys, phoneimei, phonesys, phonetype, version, platform, build, "Content-Type": "application/json" }
  539. const showToast = (text) => {
  540. wx.showToast({
  541. title: text || errorText,
  542. icon: 'none'
  543. })
  544. }
  545. url = formatUrl(host + url, Object.assign({}, paras, { accessToken }))
  546. return new Promise((resolve, reject) => {
  547. const files = isArr(file) ? file : [file]
  548. const len = files.length
  549. const arr = []
  550. let i = 0
  551. const Fn = (f) => {
  552. const uploadTask = wx.uploadFile({
  553. url,
  554. filePath: f,
  555. name: 'files',
  556. formData: data,
  557. header,
  558. success: e => {
  559. const { statusCode } = e
  560. const { code, msg, data } = JSON.parse(e.data)
  561. switch (~~statusCode) {
  562. case 200:
  563. switch (~~code) {
  564. case 999:
  565. arr.push(data.pics[0].filePath)
  566. if (i < len - 1) {
  567. ++i
  568. Fn(files[i])
  569. } else {
  570. resolve(arr)
  571. }
  572. break
  573. default:
  574. showToast(msg)
  575. reject(e)
  576. }
  577. if (loginTime > 0) {
  578. getApp().globalData.loginTime = 0
  579. }
  580. break
  581. case 401:
  582. getApp().globalData.loginTime = loginTime + 1
  583. if (loginTime < 2) {
  584. getApp().globalData.continuousFn = continuousFn
  585. getApp().login()
  586. } else {
  587. showToast('登录失效,稍后再试')
  588. reject(e)
  589. }
  590. break
  591. default:
  592. showToast()
  593. reject(e)
  594. }
  595. },
  596. fail: e => {
  597. showToast()
  598. reject(e)
  599. },
  600. complete: e => {
  601. getApp().globalData.isPending = true
  602. uploadTask.abort()
  603. wx.hideLoading()
  604. console.log({ url, request: data, response: e.data, globalData: getApp().globalData })
  605. }
  606. })
  607. uploadTask.onProgressUpdate((res) => {
  608. progress && progress(res)
  609. const { progress } = res
  610. const progressNumber = ~~(progress / len + 100 / len * i)
  611. wx.showLoading({
  612. title: `已上传(${progressNumber}%)`
  613. })
  614. if (progressNumber == 100) {
  615. wx.hideLoading()
  616. }
  617. })
  618. }
  619. Fn(files[i])
  620. })
  621. }
  622. export {
  623. hasVal,
  624. isStr,
  625. isFn,
  626. isArr,
  627. isObj,
  628. isEmptyObj,
  629. formatNumber,
  630. formatDateTime,
  631. formatDate,
  632. formatTime,
  633. formatUrl,
  634. thisMonthLenth,
  635. throttle,
  636. debounce,
  637. throttleDebounce,
  638. wxSetting,
  639. getWxUserInfoSetting,
  640. getWxLocationSetting,
  641. getWxCameraSetting,
  642. systemInfo,
  643. routers,
  644. viewImage,
  645. sharePage,
  646. getGlobalVal,
  647. wxPayment,
  648. getUpdateManager,
  649. fetch,
  650. uploadFile,
  651. }