import { getIssuerDetail, getShareInfo } from '@/api/home' import { useTokenStore } from '@/store/token' import { getImageUrl } from '@/utils/imageUtil' /** * 分享配置选项 */ export interface ShareOptions { title?: string path?: string imageUrl?: string shareType?: 'INVITE' | 'COUPON' | string showLoading?: boolean imageSource?: 'LOCAL' | 'REMOTE' pathParamKey?: string } interface ShareInfo { shareType: 'INVITE' | 'COUPON' | string shareContentId?: string sharePath?: string } /** * 默认分享配置 */ const defaultOptions: Required = { title: '领券省心,消费超值,优质生活轻松开启!', path: '/pages/home/home', imageUrl: `${getImageUrl('@img/share.png')}`, shareType: 'INVITE', showLoading: true, imageSource: 'LOCAL', pathParamKey: 'shareRecordId', } /** * 分享hook - 用于页面生命周期中使用 * @param initOptions 自定义分享配置 * @returns 可以在onShareAppMessage中使用的异步函数 */ export function useShare(initOptions: ShareOptions = {}) { /** * 获取分享配置 - 可以直接在onShareAppMessage中调用 * @returns 完整的分享配置 */ const getShareConfig = async (customOption?: ShareOptions, extraParams?): Promise => { // 合并默认配置和自定义配置 const options = { ...defaultOptions, ...initOptions, ...customOption } // 检查用户是否已登录 const tokenStore = useTokenStore() if (!tokenStore.hasLogin) { uni.showToast({ title: '请先登录后再分享', icon: 'none', }) } try { if (options.showLoading) { uni.showLoading({ title: '获取分享信息中...', mask: true, }) } const IssuerResult = await getIssuerDetail() console.log(IssuerResult, 'IssuerResult') if (!IssuerResult || (IssuerResult?.status && IssuerResult?.status !== '1')) { throw new Error('当前用户不是发券人,无法发放优惠券') } const params: ShareInfo = { shareType: options.shareType, } if (options.shareType === 'COUPON') { if (!extraParams?.shareContentId) { throw new Error('分享优惠券时需要提供优惠券ID') } params.shareContentId = extraParams?.shareContentId || '' } else { params.sharePath = options.path } // 请求分享信息接口 const res = await getShareInfo(params) if (options.showLoading) { uni.hideLoading() } if (res !== '' && res !== null && res !== 'null') { // 拼接分享路径 const sharePath = `${options.path}${options.path.includes('?') ? '&' : '?'}${options.pathParamKey}=${res}` let imageUrl = '' if (options.imageSource === 'LOCAL') { imageUrl = options.imageUrl } else { imageUrl = `${import.meta.env.VITE_SERVER_BASEURL}${import.meta.env.VITE_SERVER_RESOURCE_BASEURL}/${options.imageUrl}` } console.log(sharePath) return { title: options.title, path: sharePath, imageUrl, } } else { uni.showToast({ title: '分享信息获取失败', icon: 'none', duration: 2000, }) } } catch (error) { if (options.showLoading) { uni.hideLoading() } uni.showToast({ title: error.message || '获取分享信息失败,请稍后重试', icon: 'none', }) } } /** * 获取朋友圈分享配置 - 可以直接在onShareTimeline中调用 * @returns 完整的朋友圈分享配置 */ const getTimelineShareConfig = async (): Promise => { const config = await getShareConfig() as WechatMiniprogram.Page.ICustomShareContent return { title: config.title, path: config.path, imageUrl: config.imageUrl, } } return { getShareConfig, getTimelineShareConfig } }