Commonutils.js 8.7 KB

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