util.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import qrcode from './qrcode.js'
  2. // import barcode from './barcode.js'
  3. import { get, post } from './http.js'
  4. const formatTime = (date) => {
  5. const year = date.getFullYear()
  6. const month = date.getMonth() + 1
  7. const day = date.getDate()
  8. const hour = date.getHours()
  9. const minute = date.getMinutes()
  10. const second = date.getSeconds()
  11. return `${[year, month, day].map(formatNumber).join('/')} ${[
  12. hour,
  13. minute,
  14. second
  15. ]
  16. .map(formatNumber)
  17. .join(':')}`
  18. }
  19. const formatNumber = (n) => {
  20. n = n.toString()
  21. return n[1] ? n : `0${n}`
  22. }
  23. const urlToObj = function (url) {
  24. let obj = {}
  25. let str = url.slice(url.indexOf('?') + 1)
  26. let arr = str.split('&')
  27. for (let i = 0; i < arr.length; i++) {
  28. let arr_temp = arr[i].split('=')
  29. obj[arr_temp[0]] = arr_temp[1]
  30. }
  31. return obj
  32. }
  33. const removeCss = function (content) {
  34. let reg = /(style|class)="[^"]+"/gi
  35. let img = /<img[^>]+>/gi
  36. let res
  37. if (img.test(content)) {
  38. res = content.match(img)
  39. for (let i = 0; i < res.length; i++) {
  40. console.log(res[i].replace(reg, ''))
  41. content = content.replace(res[i], res[i].replace(reg, ''))
  42. }
  43. }
  44. // (/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
  45. return content.replace(/\<img/gi, '<img class="richImg" ')
  46. }
  47. const getPrePage = function (content) {
  48. let pages = getCurrentPages()
  49. return pages[pages.length - 1]
  50. }
  51. const objToParam = function (param) {
  52. if (Object.prototype.toString.call(param) !== '[object Object]') {
  53. return ''
  54. }
  55. let queryParam = ''
  56. for (let key in param) {
  57. if (param.hasOwnProperty(key)) {
  58. let value = param[key]
  59. queryParam += toQueryPair(key, value)
  60. }
  61. }
  62. return queryParam
  63. }
  64. let callBackList = []
  65. let timer_
  66. /**
  67. * 开启定时器
  68. */
  69. const startTimer = function () {
  70. if (!timer_) {
  71. timer_ = setInterval(() => {
  72. if (callBackList.length == 0) {
  73. console.log('倒计时结束 关闭定时器')
  74. clearInterval(timer_)
  75. timer_ = null
  76. }
  77. callBackList.forEach((item, index) => {
  78. item.currentTime--
  79. var h = parseInt(item.currentTime / 3600) //小时
  80. var m = parseInt((item.currentTime / 60) % 60) //分钟
  81. var s = parseInt(item.currentTime % 60) //当前的秒
  82. let obj = {
  83. h,
  84. m,
  85. s,
  86. currentTime: item.currentTime
  87. }
  88. item.fn(obj)
  89. if (item.currentTime <= 0) {
  90. callBackList.splice(index, 1)
  91. }
  92. })
  93. }, 1000)
  94. }
  95. }
  96. const addTime = function (callback, currentTime) {
  97. if (currentTime) {
  98. callBackList.push({ fn: callback, currentTime })
  99. console.log('第' + callBackList.length + '个倒计时开启')
  100. if (!timer_) {
  101. startTimer()
  102. }
  103. }
  104. }
  105. const removeTime = function (fn) {
  106. for (var i = 0; i < callBackList.length; i++) {
  107. let item = callBackList[i]
  108. if (item.fn == fn) {
  109. console.log('清除倒计时~')
  110. callBackList.splice(i, 1)
  111. }
  112. }
  113. }
  114. function toQueryPair(key, value) {
  115. if (typeof value == 'undefined') {
  116. return `${key}=&`
  117. }
  118. return `${key}=${value}&`
  119. }
  120. /**
  121. * 插件内部是根据width, height参数的rpx值来进行绘画
  122. * 把数字转换成条形码
  123. */
  124. // function toBarcode(canvasId, code, width, height) {
  125. // barcode.code128(wx.createCanvasContext(canvasId), code, width, height)
  126. // }
  127. /**
  128. * 把数字转换成二维码
  129. */
  130. function toQrcode(canvasId, code, width, height) {
  131. let pixelRatio1 = 750 / wx.getSystemInfoSync().windowWidth
  132. qrcode.api.draw(code, {
  133. ctx: wx.createCanvasContext(canvasId),
  134. width: width / pixelRatio1,
  135. height: height / pixelRatio1
  136. })
  137. }
  138. /**
  139. * @description 函数节流: 每隔一段时间,只执行一次函数
  140. * @param { Function } fn 需要延迟执行的函数
  141. * @param { Number } interval 延迟执行的时间,默认值500ms
  142. */
  143. function throttle(fn, interval = 200) {
  144. // 记录定时器id
  145. let timer = null // 是否是第一次调用
  146. let isFirstTime = true
  147. return function () {
  148. const args = arguments
  149. const _me = this // 第一次直接执行,改变标志,无需延迟
  150. if (isFirstTime) {
  151. fn.apply(_me, args)
  152. return (isFirstTime = false)
  153. } // 不是第一次 // 存在定时器,前面的延迟操作没有完成,直接返回,拒绝调用请求
  154. if (timer) {
  155. return false
  156. } // 延迟执行
  157. timer = setTimeout(() => {
  158. clearTimeout(timer)
  159. timer = null
  160. fn.apply(_me, args)
  161. }, interval)
  162. }
  163. }
  164. /**
  165. * @description 函数防抖: 延迟函数执行,并且不管触发多少次都只执行最后一次
  166. * @param {Function} fn
  167. * @param {Number} interval
  168. */
  169. function debounce(fn, interval) {
  170. let timer = null
  171. let gapTime = interval || 200 //间隔时间,如果interval不传,则默认200ms
  172. return function () {
  173. clearTimeout(timer)
  174. let context = this
  175. let args = arguments //保存此处的arguments,因为setTimeout是全局的,arguments不是防抖函数需要的。
  176. timer = setTimeout(function () {
  177. fn.call(context, args)
  178. }, gapTime)
  179. }
  180. }
  181. /**
  182. * 店铺信息
  183. * /api/store/info
  184. */
  185. function getStoreInfo(store_id) {
  186. return new Promise((resolve, reject) => {
  187. get(
  188. 'api/store/info',
  189. {
  190. store_id
  191. },
  192. (res) => {
  193. wx.setStorageSync('store_id', String(store_id))
  194. getApp().globalData.storeData = res.data
  195. resolve(res.data)
  196. },
  197. (err) => {
  198. reject(err)
  199. }
  200. )
  201. })
  202. }
  203. /**
  204. * @description 用户点击行为统计 v2/api/user/user_click
  205. * @param {string} type
  206. * 1是推送的点击 2是订单详情点击 3是banner充值 4是上镜小V脸 5是banner新人体验活动 7是邀请 8是被邀请
  207. */
  208. async function trackUserEvent(type) {
  209. try {
  210. let resp = await post('v2/api/user/user_click', { type })
  211. if (resp === 200) {
  212. // 数据上报成功
  213. }
  214. } catch (error) {
  215. // 上报失败
  216. console.log(error)
  217. }
  218. }
  219. module.exports = {
  220. formatTime,
  221. urlToObj,
  222. removeCss,
  223. getPrePage,
  224. objToParam,
  225. addTime,
  226. removeTime,
  227. toQrcode,
  228. throttle,
  229. debounce,
  230. getStoreInfo,
  231. trackUserEvent
  232. }