DWHutils.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { whoami } from '../api/auth'
  2. import { T_STORAGE_KEY, USER_INFO } from '../constant'
  3. import { jsonp } from 'vue-jsonp'
  4. import { isNull } from 'lodash-es'
  5. /**
  6. * @description 解决小数计算精度问题(en,你应该使用big.js)
  7. * @param {Number, String} data 数字
  8. * @param {Number} accuracy 保留几位小数
  9. * @returns
  10. */
  11. export const fomartNumber = (data, accuracy = 2) => {
  12. const temp = data + ''
  13. if (temp.includes('.')) {
  14. return (data * 1).toFixed(accuracy)
  15. }
  16. return data
  17. }
  18. /**
  19. * @description 批量清除缓存
  20. * @param {String[]} cacheArr 要清除的缓存string数组
  21. */
  22. export const removeCache = (cacheArr) => {
  23. if (!Array.isArray(cacheArr)) {
  24. return
  25. }
  26. for (const item of cacheArr) {
  27. uni.removeStorageSync(item)
  28. }
  29. }
  30. /**
  31. * 检测登录是否有效
  32. */
  33. export const checkWhoami = () => {
  34. new Promise(async (resolve, reject) => {
  35. const userId = getUserId()
  36. const res = await whoami(userId)
  37. if (res.errno !== 0) {
  38. uni.navigateTo({
  39. url: '/pages/login/login'
  40. })
  41. }
  42. })
  43. }
  44. /**
  45. * 获取用户userid
  46. * @returns
  47. */
  48. export const getUserId = () => {
  49. const userId = uni.getStorageSync(xxx)
  50. if (!userId) {
  51. // uni.showToast({
  52. // title: "登录已失效,请重新登录",
  53. // duration: 2000,
  54. // icon: "none",
  55. // });
  56. // uni.navigateTo({
  57. // url: "/pages/login/login",
  58. // });
  59. uni.showModal({
  60. title: '提示',
  61. content: '您还未登录,是否去登录?',
  62. success(res) {
  63. if (res.confirm) {
  64. uni.navigateTo({
  65. url: '/pages/login/login'
  66. })
  67. } else if (res.cancel) {
  68. // uni.navigateBack();
  69. }
  70. }
  71. })
  72. return
  73. }
  74. return userId
  75. }
  76. /**
  77. * 获取新团蜂token
  78. * @returns
  79. */
  80. export const getStorageKeyToken = () => {
  81. // const userInfo = uni.getStorageSync(USER_INFO)
  82. // if (!userInfo || !userInfo.userId) {
  83. // uni.showModal({
  84. // title: '提示',
  85. // content: '您还未登录,是否去登录?',
  86. // success(res) {
  87. // if (res.confirm) {
  88. // uni.navigateTo({
  89. // url: '/pages/login/login'
  90. // })
  91. // } else if (res.cancel) {
  92. // // uni.navigateBack();
  93. // }
  94. // }
  95. // })
  96. // return
  97. // }
  98. // if (!userInfo || !userInfo.phone) {
  99. // uni.showModal({
  100. // title: '提示',
  101. // content: '未绑定手机号码,是否去绑定?',
  102. // success(res) {
  103. // if (res.confirm) {
  104. // uni.switchTab({
  105. // url: '/'
  106. // })
  107. // } else if (res.cancel) {
  108. // // uni.navigateBack();
  109. // }
  110. // }
  111. // })
  112. // return
  113. // }
  114. const storageKey = uni.getStorageSync(T_STORAGE_KEY)
  115. if (!storageKey || !storageKey.token) {
  116. uni.showModal({
  117. title: '提示',
  118. content: '系统出错,请重新登陆',
  119. success(res) {
  120. if (res.confirm) {
  121. uni.navigateTo({
  122. url: '/pages/login/login'
  123. })
  124. } else if (res.cancel) {
  125. // uni.navigateBack();
  126. }
  127. }
  128. })
  129. return
  130. }
  131. return storageKey.token
  132. }
  133. /**
  134. * 跳转到新团蜂入驻端项目
  135. * @returns
  136. */
  137. export const jumpToOtherProject = (url, cb = () => { }) => {
  138. // #ifdef H5
  139. window.location.href = url
  140. // #endif
  141. // #ifdef APP
  142. plus.runtime.openURL(url, cb)
  143. // #endif
  144. // #ifdef MP
  145. uni.redirectTo({
  146. url: `/user/view?target=${url}`
  147. })
  148. // #endif
  149. }
  150. /**
  151. * 点击复制
  152. * @param {*} text
  153. */
  154. export const useCopy = (text) => {
  155. const input = document.createElement('input')
  156. input.value = text
  157. document.body.appendChild(input)
  158. input.select()
  159. document.execCommand('Copy')
  160. document.body.removeChild(input)
  161. uni.showToast({
  162. title: '单号复制成功'
  163. })
  164. }
  165. /**
  166. * @description 防抖函数
  167. * @param {*} func
  168. * @param {*} wait
  169. * @param {*} immediate
  170. * @returns
  171. */
  172. export function handleDebounce(func, wait, immediate) {
  173. let timeout
  174. return function () {
  175. const context = this
  176. const args = arguments
  177. if (timeout) clearTimeout(timeout)
  178. if (immediate) {
  179. var callNow = !timeout
  180. timeout = setTimeout(() => {
  181. timeout = null
  182. }, wait)
  183. if (callNow) func.apply(context, args)
  184. } else {
  185. timeout = setTimeout(function () {
  186. func.apply(context, args)
  187. }, wait)
  188. }
  189. }
  190. }
  191. export function getRandom(min, max) {
  192. return Math.floor(Math.random() * (max - min) + min)
  193. }
  194. export const randomRGB = () => {
  195. const r = Math.floor(Math.random() * 255)
  196. const g = Math.floor(Math.random() * 255)
  197. const b = Math.floor(Math.random() * 255)
  198. return `rgb(${r}, ${g}, ${b})`
  199. }
  200. export const timestampToTime = (timestamp) => {
  201. // 时间戳为10位需*1000,时间戳为13位不需乘1000
  202. // var date = new Date(timestamp * 1000);
  203. var date = new Date(timestamp)
  204. var Y = date.getFullYear() + '-'
  205. var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  206. var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
  207. var h = date.getHours() + ':'
  208. var m = date.getMinutes() + ':'
  209. var s = date.getSeconds()
  210. return Y + M + D + h + m + s
  211. // console.log(timestampToTime(1670145353)); //2022-12-04 17:15:53
  212. }
  213. /**
  214. * 时间格式化
  215. */
  216. export const timeFormatting = (timeDifference) => {
  217. // 天数
  218. const day = Math.floor(timeDifference / 3600 / 24)
  219. // 小时
  220. const hr = Math.floor(timeDifference / 3600 % 24)
  221. // 分钟
  222. const min = Math.floor(timeDifference / 60 % 60)
  223. // 秒
  224. const sec = Math.floor(timeDifference % 60)
  225. return {
  226. day: day < 10 ? '0' + day : day,
  227. hour: hr < 10 ? '0' + hr : hr,
  228. min: min < 10 ? '0' + min : min,
  229. sec: sec < 10 ? '0' + sec : sec
  230. }
  231. }
  232. export const throttle = (fn, interval) => {
  233. let lastTime = 0
  234. const _throttle = function (...args) {
  235. const nowTime = new Date().getTime()
  236. const remainTime = interval - (nowTime - lastTime)
  237. if (remainTime <= 0) {
  238. fn.apply(this, args)
  239. lastTime = nowTime
  240. }
  241. }
  242. return _throttle
  243. }
  244. // 获取 微信 code
  245. // #ifdef H5
  246. export const getUrlCode = () => {
  247. var url = location.search
  248. var theRequest = new Object()
  249. if (url.indexOf('?') != -1) {
  250. var str = url.substr(1)
  251. var strs = str.split('&')
  252. for (var i = 0; i < strs.length; i++) {
  253. theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
  254. }
  255. }
  256. console.log('code结果', theRequest)
  257. return theRequest
  258. }
  259. // #endif
  260. // 判断当前是否处于微信环境
  261. export const isInWx = () => {
  262. // #ifdef H5
  263. var ua = navigator.userAgent.toLowerCase()
  264. return ua.match(/MicroMessenger/i) == 'micromessenger'
  265. // #endif
  266. // #ifdef APP
  267. return false
  268. // #endif
  269. }
  270. /**
  271. * 大数转小数 12345.123 = 1.23万
  272. */
  273. export const convertToDecimal = (number) => {
  274. if (!number || isNull(number)) return 0
  275. if (number < 10000) {
  276. return number.toString()
  277. } else if (number < 100000000) {
  278. const decimalNumber = (number / 10000).toFixed(2)
  279. return decimalNumber + '万'
  280. }
  281. const decimalNumber = (number / 100000000).toFixed(2)
  282. return decimalNumber + '亿'
  283. }
  284. export const isSubarray = (arr, subarr) => {
  285. const mainSet = new Set(arr)
  286. for (const element of subarr) {
  287. if (!mainSet.has(element)) {
  288. return false
  289. }
  290. }
  291. return true
  292. }
  293. export const tradeOrderNo = function () {
  294. const now = new Date()
  295. const year = now.getFullYear()
  296. let month = now.getMonth() + 1
  297. let day = now.getDate()
  298. let hour = now.getHours()
  299. let minutes = now.getMinutes()
  300. let seconds = now.getSeconds()
  301. String(month).length < 2 ? month = Number('0' + month) : month
  302. String(day).length < 2 ? day = Number('0' + day) : day
  303. String(hour).length < 2 ? hour = Number('0' + hour) : hour
  304. String(minutes).length < 2 ? minutes = Number('0' + minutes) : minutes
  305. String(seconds).length < 2 ? seconds = Number('0' + seconds) : seconds
  306. const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`
  307. return yyyyMMddHHmmss + Math.random().toString(36)
  308. .substr(2, 9)
  309. }
  310. /**
  311. * 判断当前H5是否在webview中打开
  312. */
  313. export const isH5InWebview = () => {
  314. const ua = navigator.userAgent.toLowerCase()
  315. return typeof ua === 'string' && (ua.includes('webview') || ua.includes('miniprogramhtmlwebview'))
  316. }
  317. /**
  318. * 判断当前资源是否是视频格式
  319. * @param {string} url
  320. * @returns {boolean}
  321. */
  322. // export function isVideo(url) {
  323. // // ['png', 'jpg', 'jpeg', 'bmp', 'gif','webp'] ['mp4', 'm2v', 'mkv', 'webm', 'ogg', 'flv']
  324. // const videoExtensions = ['.avi', '.wmv', '.mpg', '.mpeg', '.mov', '.rm', '.ram', '.swf', '.flv', '.mp4']
  325. // const lowercasedUrl = url.toLowerCase()
  326. // return videoExtensions.some(type => lowercasedUrl.includes(type))
  327. // }
  328. export function isVideoSource(src) {
  329. // return ['.avi', '.wmv', '.mpg', '.mpeg', '.mov', '.rm', '.ram', '.swf', '.flv', '.mp4'].some((item) => src.indexOf(item) !== -1)
  330. return ['.avi', '.wmv', '.mpg', '.mpeg', '.mov', '.rm', '.ram', '.swf', '.flv', '.mp4'].includes(src.substring(src.lastIndexOf('.')))
  331. }
  332. export const saveImg = (url, cb) => {
  333. // #ifdef H5
  334. const uniappA = document.createElement('a')
  335. uniappA.download = ''
  336. uniappA.href = url
  337. document.body.appendChild(uniappA)
  338. uniappA.click()
  339. uniappA.remove()
  340. cb && typeof cb === 'function' && cb()
  341. // #endif
  342. // #ifdef APP
  343. uni.saveImageToPhotosAlbum({
  344. filePath: url,
  345. success() {
  346. cb && typeof cb === 'function' && cb()
  347. }
  348. })
  349. // #endif
  350. }