index.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { pages, subPackages, tabBar } from '@/pages.json'
  2. import { isMpWeixin } from './platform'
  3. const getLastPage = () => {
  4. // getCurrentPages() 至少有1个元素,所以不再额外判断
  5. // const lastPage = getCurrentPages().at(-1)
  6. // 上面那个在低版本安卓中打包回报错,所以改用下面这个【虽然我加了src/interceptions/prototype.ts,但依然报错】
  7. const pages = getCurrentPages()
  8. return pages[pages.length - 1]
  9. }
  10. /** 判断当前页面是否是tabbar页 */
  11. export const getIsTabbar = () => {
  12. if (!tabBar) {
  13. return false
  14. }
  15. if (!tabBar.list.length) {
  16. // 通常有tabBar的话,list不能有空,且至少有2个元素,这里其实不用处理
  17. return false
  18. }
  19. const lastPage = getLastPage()
  20. const currPath = lastPage.route
  21. return !!tabBar.list.find((e) => e.pagePath === currPath)
  22. }
  23. /**
  24. * 获取当前页面路由的 path 路径和 redirectPath 路径
  25. * path 如 ‘/pages/login/index’
  26. * redirectPath 如 ‘/pages/demo/base/route-interceptor’
  27. */
  28. export const currRoute = () => {
  29. const lastPage = getLastPage()
  30. const currRoute = (lastPage as any).$page
  31. // console.log('lastPage.$page:', currRoute)
  32. // console.log('lastPage.$page.fullpath:', currRoute.fullPath)
  33. // console.log('lastPage.$page.options:', currRoute.options)
  34. // console.log('lastPage.options:', (lastPage as any).options)
  35. // 经过多端测试,只有 fullPath 靠谱,其他都不靠谱
  36. const { fullPath } = currRoute as { fullPath: string }
  37. // console.log(fullPath)
  38. // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
  39. // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
  40. return getUrlObj(fullPath)
  41. }
  42. const ensureDecodeURIComponent = (url: string) => {
  43. if (url.startsWith('%')) {
  44. return ensureDecodeURIComponent(decodeURIComponent(url))
  45. }
  46. return url
  47. }
  48. /**
  49. * 解析 url 得到 path 和 query
  50. * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
  51. * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
  52. */
  53. export const getUrlObj = (url: string) => {
  54. const [path, queryStr] = url.split('?')
  55. // console.log(path, queryStr)
  56. if (!queryStr) {
  57. return {
  58. path,
  59. query: {},
  60. }
  61. }
  62. const query: Record<string, string> = {}
  63. queryStr.split('&').forEach((item) => {
  64. const [key, value] = item.split('=')
  65. // console.log(key, value)
  66. query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下,可以兼容h5和微信y
  67. })
  68. return { path, query }
  69. }
  70. /**
  71. * 得到所有的需要登录的pages,包括主包和分包的
  72. * 这里设计得通用一点,可以传递key作为判断依据,默认是 needLogin, 与 route-block 配对使用
  73. * 如果没有传 key,则表示所有的pages,如果传递了 key, 则表示通过 key 过滤
  74. */
  75. export const getAllPages = (key = 'needLogin') => {
  76. // 这里处理主包
  77. const mainPages = [
  78. ...pages
  79. .filter((page) => !key || page[key])
  80. .map((page) => ({
  81. ...page,
  82. path: `/${page.path}`,
  83. })),
  84. ]
  85. // 这里处理分包
  86. const subPages: any[] = []
  87. subPackages.forEach((subPageObj) => {
  88. // console.log(subPageObj)
  89. const { root } = subPageObj
  90. subPageObj.pages
  91. .filter((page) => !key || page[key])
  92. .forEach((page: { path: string } & Record<string, any>) => {
  93. subPages.push({
  94. ...page,
  95. path: `/${root}/${page.path}`,
  96. })
  97. })
  98. })
  99. const result = [...mainPages, ...subPages]
  100. // console.log(`getAllPages by ${key} result: `, result)
  101. return result
  102. }
  103. /**
  104. * 得到所有的需要登录的pages,包括主包和分包的
  105. * 只得到 path 数组
  106. */
  107. export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)
  108. /**
  109. * 得到所有的需要登录的pages,包括主包和分包的
  110. * 只得到 path 数组
  111. */
  112. export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
  113. /**
  114. * 根据微信小程序当前环境,判断应该获取的BaseUrl
  115. */
  116. export const getEnvBaseUrl = () => {
  117. // 请求基准地址
  118. let baseUrl = import.meta.env.VITE_SERVER_BASEURL
  119. // 微信小程序端环境区分
  120. if (isMpWeixin) {
  121. const {
  122. miniProgram: { envVersion },
  123. } = uni.getAccountInfoSync()
  124. switch (envVersion) {
  125. case 'develop':
  126. baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_DEVELOP || baseUrl
  127. break
  128. case 'trial':
  129. baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_TRIAL || baseUrl
  130. break
  131. case 'release':
  132. baseUrl = import.meta.env.VITE_SERVER_BASEURL__WEIXIN_RELEASE || baseUrl
  133. break
  134. }
  135. }
  136. return baseUrl
  137. }
  138. /**
  139. * 根据微信小程序当前环境,判断应该获取的UPLOAD_BASEURL
  140. */
  141. export const getEnvBaseUploadUrl = () => {
  142. // 请求基准地址
  143. let baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL
  144. // 微信小程序端环境区分
  145. if (isMpWeixin) {
  146. const {
  147. miniProgram: { envVersion },
  148. } = uni.getAccountInfoSync()
  149. switch (envVersion) {
  150. case 'develop':
  151. baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_DEVELOP || baseUploadUrl
  152. break
  153. case 'trial':
  154. baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_TRIAL || baseUploadUrl
  155. break
  156. case 'release':
  157. baseUploadUrl = import.meta.env.VITE_UPLOAD_BASEURL__WEIXIN_RELEASE || baseUploadUrl
  158. break
  159. }
  160. }
  161. return baseUploadUrl
  162. }
  163. // 获取登录的code
  164. export const getLoginCode = () => {
  165. return new Promise((resolve, reject) => {
  166. uni.login({
  167. success: (res) => {
  168. if (res.code) resolve(res.code)
  169. else reject(res)
  170. },
  171. fail: (err) => {
  172. reject(err)
  173. },
  174. })
  175. })
  176. }
  177. // 回显字典
  178. export const getLabel = (code: string, options: any) => {
  179. let label = ''
  180. if (code) {
  181. label = options.find((e: any) => e.value == code)?.label || ''
  182. }
  183. return label || code
  184. }
  185. // 回显字典颜色
  186. export const getLabelColor = (code: string, options: any) => {
  187. let color = ''
  188. if (code) {
  189. color = options.find((e: any) => e.value == code)?.color || ''
  190. }
  191. return color
  192. }
  193. // 字典转为label和value
  194. export const dictLabel = (lists: any[]) => {
  195. let datas: any = []
  196. if (!lists.length) return datas
  197. datas = lists.map((item) => {
  198. return {
  199. value: item.code,
  200. label: item.name,
  201. }
  202. })
  203. return datas
  204. }
  205. // 数组根据id去重
  206. export function uniqueItems(items: any) {
  207. const uniqueData = items.filter(
  208. (item: any, index: any, self: any) => index === self.findIndex((t: any) => t.id === item.id),
  209. )
  210. return uniqueData
  211. }
  212. // 跳转至登录页(自动登录)
  213. export function toLogin(duration = 0) {
  214. setTimeout(() => {
  215. uni.reLaunch({
  216. url: `/pages/login/index`,
  217. })
  218. }, duration)
  219. }
  220. // 跳转至登录页(不自动登录)
  221. export function toLoginWait(duration = 0) {
  222. setTimeout(() => {
  223. uni.reLaunch({
  224. url: `/pages/login/index?isLogout=1`,
  225. })
  226. }, duration)
  227. }
  228. // 重定向到上传系统文件
  229. export function redirectToUpload() {
  230. const url = "https://service.1ai.ltd/webview-upload/index.html"
  231. uni.redirectTo({
  232. url: `/pages/webview/index?url=${encodeURIComponent(url)}`,
  233. })
  234. }
  235. // 重定向到首页
  236. export function reLaunchToHome() {
  237. uni.reLaunch({
  238. url: `/pages/index/index`,
  239. })
  240. }
  241. // 时间转义
  242. export function timestampToDatetime(timestamp) {
  243. let str = String(timestamp)
  244. let ts = Number(str.length == 10 ? `${str}000` : str)
  245. let date = new Date(ts);
  246. let year = date.getFullYear();
  247. let month = ("0" + (date.getMonth() + 1)).slice(-2);
  248. let day = ("0" + date.getDate()).slice(-2);
  249. let hours = ("0" + date.getHours()).slice(-2);
  250. let minutes = ("0" + date.getMinutes()).slice(-2);
  251. let seconds = ("0" + date.getSeconds()).slice(-2);
  252. return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  253. }