import { FC, useMemo, useState, useRef, useEffect } from 'react' import { ForbidFill, CameraOutline } from 'antd-mobile-icons' import { useSearchParams } from 'react-router-dom' import { Image, ImageViewer, ImageUploader, Toast } from 'antd-mobile' import { isAlipayIDE } from '@/utils' import { ChooseImageAction, BasicPictureValueType } from '@/types' import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader' import { flowApi } from '@/services/flow' import { useAppDispatch } from '@/store/storeHooks' import styled from 'styled-components' const ossHost = import.meta.env.VITE_OSS_HOST interface PictureFieldProps { value?: BasicPictureValueType required: boolean maxCount?: number maxSize?: number uniqueKey?: string onChange?: (value: BasicPictureValueType) => void hostUrl?: string actionUrl?: string } const PictureField: FC = ({ value = [], maxCount = 20, maxSize = 10 * 1024 * 1024, onChange, uniqueKey = '', actionUrl = '/qy/common/uploadWorkOrderImg/noLogin' }) => { const [searchParams] = useSearchParams() const companyKey = searchParams.get('companyKey') || '' const shopUniqueKey = searchParams.get('shopUniqueKey') || '' const [fileList, setFileList] = useState([]) const valueRef = useRef>(value) const storeDispatch = useAppDispatch() const formatMaxSize = maxSize / 1024 / 1024 const ImgList = value.map((pic, index) => { return (
{ e.stopPropagation() handleDelImage(index) }} /> { e.stopPropagation() handleImagePreview(index) }} fit="cover" src={`${ossHost}/${pic}`} style={{ borderRadius: 6 }} />
) }) const triggerValue = (changedValue: BasicPictureValueType) => { onChange?.(changedValue) } const onValueChange = (value: BasicPictureValueType) => { triggerValue(value) } // 点击上传图片 通知小程序 const handleUploadImage = () => { if (window?.my && !isAlipayIDE) { my.postMessage({ action: 'chooseImage', option: { maxSize: 3, // 小程序要求图片小于3M count: maxCount - value?.length || 0 } }) my.onMessage = (e: ChooseImageAction) => { const { action, data } = e if (action === 'chooseImage') { onValueChange([...value, ...data]) } } } } // 删除图片 const handleDelImage = (index: number) => { const tempList = value.slice() tempList.splice(index, 1) onValueChange(tempList) } // 预览图片 const handleImagePreview = (index: number) => { ImageViewer.Multi.show({ images: previewImages, defaultIndex: index }) } const isUpLimit = useMemo(() => { return value.length - maxCount >= 0 }, [value, maxCount]) const previewImages = useMemo(() => { return value.map(pic => `${ossHost}/${pic}`) }, [value]) const beforeUpload = (file: File) => { if (file.size > maxSize) { Toast.show(`请选择小于 ${formatMaxSize}M 的图片`) return null } return file } const asyncUpload = async (file: File) => { const formData = new FormData() formData.append('file', file) const fileName = `${uniqueKey}_${ valueRef.current?.length + 1 }_${new Date().getTime()}.jpg` formData.append('fileName', fileName) try { const res = await storeDispatch( flowApi.endpoints.uploadFile.initiate({ url: `${actionUrl}?companyKey=${companyKey}&shopUniqueKey=${shopUniqueKey}`, formData }) ) const { data } = res as { data: string } if ('error' in res && res.error) { throw res.error } else if (data) { return { url: `${ossHost}/${data}`, extra: data } } } catch (e) { Toast.show('图片上传失败') } return { url: '', extra: '' } } const handleUploadChange = (items: ImageUploadItem[]) => { const filterItems = items.filter(item => !!item.url) // setFileList(filterItems) const tempUrlList = filterItems ?.map(item => (item?.extra as string) || '') .filter(item => item) onValueChange([...tempUrlList]) } useEffect(() => { const newImgList = value.map(t => { return { extra: t, url: `${ossHost}/${t}` } }) setFileList(newImgList) }, [value]) return ( <>
{window?.my && !isAlipayIDE ? ( <> {ImgList} {!isUpLimit && (
上传图片
)} ) : ( handleUploadChange(items) } upload={asyncUpload} showUpload={fileList.length < maxCount} beforeUpload={beforeUpload} onCountExceed={exceed => { Toast.show( `最多选择 ${maxCount} 张图片,你多选了 ${exceed} 张` ) }} /> )}

最多添加{maxCount}张图片,每张最大{window?.my ? 3 : formatMaxSize}Mb

) } const ImageUploadBox = styled.div` .adm-image-uploader-upload-button-wrap { border: 1px dashed #cccccc; border-radius: 4px; } ` export default PictureField