authRedirect.js 3.46 KB
/*
 * @Date: 2025-01-25 10:00:00
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-09-04 15:33:00
 * @FilePath: /lls_program/src/utils/authRedirect.js
 * @Description: 授权重定向处理工具函数
 */
import Taro from '@tarojs/taro'
import { routerStore } from '@/stores/router'

/**
 * 获取当前页面完整路径(包含参数)
 * @returns {string} 完整的页面路径
 */
export const getCurrentPageFullPath = () => {
  const pages = getCurrentPages()
  if (pages.length === 0) return ''

  const currentPage = pages[pages.length - 1]
  const route = currentPage.route
  const options = currentPage.options

  // 构建查询参数字符串
  const queryParams = Object.keys(options)
    .map(key => `${key}=${encodeURIComponent(options[key])}`)
    .join('&')

  return queryParams ? `${route}?${queryParams}` : route
}

/**
 * 保存当前页面路径到路由存储
 * @param {string} customPath - 自定义路径,如果不提供则使用当前页面路径
 */
export const saveCurrentPagePath = (customPath) => {
  const router = routerStore()
  const path = customPath || getCurrentPageFullPath()
  router.add(path)
}

/**
 * 跳转到授权页面
 * @param {string} returnPath - 授权完成后要返回的页面路径
 */
export const navigateToAuth = (returnPath) => {
  // 保存返回路径
  if (returnPath) {
    saveCurrentPagePath(returnPath)
  } else {
    saveCurrentPagePath()
  }

  // 跳转到授权页面
  Taro.navigateTo({
    url: '/pages/auth/index'
  })
}

/**
 * 授权完成后返回原页面
 * @param {string} defaultPath - 默认返回路径,如果没有保存的路径则使用此路径
 */
export const returnToOriginalPage = (defaultPath = '/pages/Dashboard/index') => {
  const router = routerStore()
  const savedPath = router.url

  if (savedPath && savedPath !== '') {
    // 清除保存的路径
    router.remove()

    // 判断是否是首页,如果是首页使用reLaunch,否则使用redirectTo
    if (savedPath.includes('Dashboard/index') || savedPath === 'pages/Dashboard/index') {
      Taro.reLaunch({
        url: `/${savedPath}`
      })
    } else {
      Taro.redirectTo({
        url: `/${savedPath}`
      })
    }
  } else {
    Taro.reLaunch({
      url: defaultPath
    })
  }
}

/**
 * 检查页面是否来自分享
 * @param {Object} options - 页面参数
 * @returns {boolean} 是否来自分享
 */
export const isFromShare = (options) => {
  // 检查是否有分享相关的参数或标识
  return options && (options.from_share === '1' || options.scene)
}

/**
 * 处理分享页面的授权逻辑
 * @param {Object} options - 页面参数
 * @param {Function} callback - 授权成功后的回调函数
 */
export const handleSharePageAuth = async (options, callback) => {
  const sessionid = wx.getStorageSync('sessionid')

  if (!sessionid) {
    // 没有授权,需要先授权
    if (isFromShare(options)) {
      // 来自分享,保存当前页面路径用于授权后返回
      saveCurrentPagePath()
    }

    // 跳转到授权页面
    Taro.navigateTo({
      url: '/pages/auth/index'
    })
    return false
  }

  // 已授权,执行回调
  if (callback && typeof callback === 'function') {
    callback()
  }
  return true
}

/**
 * 为分享链接添加分享标识参数
 * @param {string} path - 原始路径
 * @returns {string} 添加分享标识后的路径
 */
export const addShareFlag = (path) => {
  const separator = path.includes('?') ? '&' : '?'
  return `${path}${separator}from_share=1`
}