UNPKG

@tplc/business

Version:

214 lines (203 loc) 5.76 kB
import { isH5 } from '@tplc/wot/components/common/util' import { UploadMethod } from '@tplc/wot/types/components/wd-upload/types' import { uploadFile } from '../hooks/useUpload' import { parse, stringify } from 'qs' import { get } from 'lodash-es' import { getCurrentInstance } from 'vue' import { LcbAddress } from '../components/lcb-city-select/api' export function formatJson(str: string | object | undefined, defVal = {}) { if (!str) return defVal if (typeof str === 'object') return str let json = defVal try { json = JSON.parse(str) } catch (e) { json = defVal } return json } /** 获取上个页面Exposed */ export const getExposed = () => { const pages = getCurrentPages() const page = pages[pages.length - 2] return page.$vm.$.exposed } export const getCurrentPage = () => { const page = getCurrentPages().pop() as { $page: { id: string fullPath: string } __wxWebviewId__: string route: string getPageId: () => number } if (!page) { return { pageId: 0, fullPath: '', options: {}, route: '', } } const fullPath = decodeURIComponent(page.$page?.fullPath?.split('?')[1] || '') return { pageId: isH5 ? page.$page.id : page.getPageId?.(), fullPath: page.$page?.fullPath, options: parse(fullPath) as any, route: page.route, } } // 获取上个页面的pageId export const getPreviousPageId = () => { const pages = getCurrentPages() const page = pages[pages.length - 2] as { $page: { id: string } getPageId: () => number } return isH5 ? page?.$page?.id : page?.getPageId?.() } /** 合并url参数 url = /pages/data/index?id=1&name=2 urlParams = id=1&name=2&type=1 */ export const getFinalUrl = (url: string, urlParams?: string) => { if (!urlParams) return url const params = parse(urlParams) const query = parse(url.split('?')[1]) const path = url.split('?')[0] return `${path}?${stringify({ ...params, ...query, })}` } export const onPageScrollSelector = (selector: string, offsetTop = 0) => { const prefix = (uni.$lcb.layoutId ? `#${uni.$lcb.layoutId} >>> #` : '#') + selector // #ifdef H5 const query = uni.createSelectorQuery().in(getCurrentInstance()?.proxy as any) // @ts-ignore query.selectViewport().scrollOffset() query.select(prefix).boundingClientRect() query.exec((res) => { const scrollRes = res[0] const rect = res[1] const currentScrollTop = scrollRes?.scrollTop || 0 if (rect) { const absoluteTop = rect.top + currentScrollTop const adjustedScrollTop = absoluteTop - offsetTop uni.pageScrollTo({ scrollTop: adjustedScrollTop, }) } }) // #endif // #ifdef MP uni.pageScrollTo({ selector: prefix, offsetTop: -offsetTop, }) // #endif } export const getPreviewImageUrl = (url: string, width = 200) => { const isctyun = url?.indexOf('.ctyun') >= 0 const sym = url?.indexOf('?') > 0 ? '&' : '?' const suffix = isctyun ? `${sym}x-amz-process=image/resize,w_${width},m_lfit` : `${sym}x-oss-process=image/resize,m_mfit,w_${width}&imageView2/2/w/${width}` return `${url}${width > 0 ? suffix : ''}` } /** 根据屏幕宽度 图片高度宽度比例 列数与 间隙宽度 计算图片高度 */ export const calculateImageHeight = ( screenWidth: number, imageHeight = 176, imageWidth = 240, column = 2, gap = 12, ) => { return ((screenWidth - gap * (2 + column - 1)) / 2) * (imageHeight / imageWidth) } export const customUpload: UploadMethod = (file, formData, options) => { const fileName = (isH5 ? file.name : file.url?.split('/').pop()) || '' uploadFile({ name: fileName, filePath: file.url, onSuccess: (data: string) => { options.onSuccess({ data, statusCode: 200 }, file, formData) }, }) } export const getSharePath = (params?: Record<string, any>) => { const inviteUserId = uni.$lcb.userStore?.()?.userInfo?.userId const inviteTime = new Date().getTime() return `/pages/start/index?${stringify({ path: getCurrentPage().fullPath, ...getCurrentPage().options, ...params, inviteTime, inviteUserId, shareDistributorId: uni.$lcb.userStore?.()?.userInfo?.shareDistributorId, distributorId: uni.$lcb.userStore?.()?.userInfo?.distributorId, })}` } /** 获取动态数据 */ export const getDynamicData = ( text = '', { store, defaultText, }: { store?: Record<string, any> defaultText?: string }, ) => { let value = text if (text && text.includes('${')) { value = text.replace(/\$\{([^}]+)\}/g, (_, p) => { return get(store, p) ?? defaultText ?? '' }) } return value } export const calcAutoHeight = ({ originalWidth, originalHeight, targetWidth, }: { originalWidth: number originalHeight: number targetWidth: number }) => { return (originalHeight / originalWidth) * targetWidth } export const getOssImageSize = async (url: string) => { return new Promise<{ width: number height: number }>((resolve) => { uni.request({ url: `${url}?x-oss-process=image/info`, method: 'GET', success: ({ data }) => { const { ImageWidth, ImageHeight } = data as unknown as { ImageWidth: { value: number } ImageHeight: { value: number } } resolve({ width: Number(ImageWidth.value), height: Number(ImageHeight.value), }) }, }) }) } export const getCityData = (data: Record<string, unknown> = {}) => { const keys = ['addressName', 'cityId', 'provinceId', 'areaId'] return keys.reduce( (acc, key) => { if (data[key] !== undefined) { acc[key] = data[key] } return acc }, {} as unknown as LcbAddress, ) }