|
- import { inviteApi } from '@/api/index.js'
- import { useUserStore } from '@/store/user.js'
-
- const DEFAULT_SHARE = {
- title: 'AI在线|开箱即用的 AI 工具箱',
- imageUrl: '',
- path: '/pages/toolbox/toolbox'
- }
-
- const shareState = {
- loaded: false,
- loading: null,
- token: '',
- share: {},
- config: {}
- }
-
- function appendQuery(path, query = {}) {
- let nextPath = path || DEFAULT_SHARE.path
- const pairs = Object.keys(query)
- .filter((key) => query[key] !== undefined && query[key] !== null && query[key] !== '')
- .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
-
- if (!pairs.length) return nextPath
- nextPath += nextPath.includes('?') ? '&' : '?'
- return nextPath + pairs.join('&')
- }
-
- function getInviteCode() {
- const userStore = useUserStore()
- userStore.restore()
- const user = userStore.userInfo || {}
- return user.open_id || user.user_open_id || user.invite_code || uni.getStorageSync('open_id') || ''
- }
-
- export function getInviteSharePath(options = {}) {
- const inviteCode = getInviteCode()
- // 与邀请好友页保持同一落地逻辑:统一进入邀请落地页。
- // 未登录时 invite_code 为空,好友仍能进入活动说明;登录用户会携带自己的 open_id。
- const path = `/pages/invite/landing?invite_code=${encodeURIComponent(inviteCode)}`
- return appendQuery(path, { source: options.source })
- }
-
- export async function preloadInviteShare() {
- const userStore = useUserStore()
- userStore.restore()
- const currentToken = userStore.token || ''
-
- if (!currentToken) {
- shareState.loaded = true
- shareState.token = ''
- shareState.share = {}
- shareState.config = {}
- return shareState
- }
- if (shareState.loaded && shareState.token === currentToken) return shareState
- if (shareState.loading) return shareState.loading
-
- shareState.loading = inviteApi.getMy({}, { authSilent: true })
- .then((res) => {
- const data = res.data || {}
- shareState.share = data.share || {}
- shareState.config = data.config || {}
- shareState.token = currentToken
- shareState.loaded = true
- return shareState
- })
- .catch(() => {
- shareState.loaded = true
- return shareState
- })
- .finally(() => {
- shareState.loading = null
- })
-
- return shareState.loading
- }
-
- export function buildShareOptions(options = {}) {
- const share = shareState.share || {}
- const config = shareState.config || {}
- const path = appendQuery(
- options.path || share.path || getInviteSharePath(),
- { source: options.source }
- )
-
- return {
- title: options.title || share.title || config.share_title || DEFAULT_SHARE.title,
- path,
- imageUrl: options.imageUrl || share.image || config.share_image || DEFAULT_SHARE.imageUrl
- }
- }
-
- export function showPageShareMenu() {
- preloadInviteShare()
- try {
- uni.showShareMenu({ withShareTicket: true })
- } catch (e) {}
- }
|