import React from 'react'; import { Upload, Modal, message, Tabs, Result } from 'antd'; import { PlusOutlined, CheckCircleFilled } from '@ant-design/icons'; import ImgCrop from 'antd-img-crop'; import classnames from 'classnames'; import { UploadFile, UploadChangeParam, RcFile } from 'antd/lib/upload/interface'; import { uuid } from '@/utils/tools'; import { get, PUBLISH_SERVICE } from '@/services'; import styles from './index.less'; import { getImageBases } from '@/services/common/api'; const { TabPane } = Tabs; // 维护图片分类映射 const wallCateName: any = { icon: '图标', bg: '背景', uploaded: '上传', }; function getBase64(file: File | Blob) { return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result as string); reader.onerror = error => reject(error); }); } interface PicturesWallType { fileList?: UploadFile<any>[]; action?: string; headers?: any; withCredentials?: boolean; maxLen?: number; onChange?: (v: any) => void; cropRate?: number | boolean; isCrop?: boolean; type?: 'CityTemp'|'icon'|'androidMenu'|'menuNew', value?: string | string[], } class PicturesWall extends React.Component<PicturesWallType> { state = { previewVisible: false, previewImage: '', wallModalVisible: false, previewTitle: '', imgBed: [], curSelectedImg: '', prevProps:{}, fileList: this.props.value ? Array.isArray(this.props.value) ? this.props.value.map((v) => ({ url: v, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', })) as UploadFile<any>[]: [{ url: this.props.value, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', }] as UploadFile<any>[] : [], }; static getDerivedStateFromProps = (props, state) => { const fileList = state.fileList; const shouldUpdate = props.value && fileList.every(f => Array.isArray(props.value) ? !props.value.some(v => f.url === v) : f.url !== props.value) if(props.value !== state.prevProps.value && shouldUpdate){ return { provProps: props, fileList: Array.isArray(props.value) ? props.value.map((v) => ({ url: v, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', })) as UploadFile<any>[]: [{ url: props.value, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', }] as UploadFile<any>[] } } return { prevProps: props }; } update = () =>{ if(this.props.value){ this.setState({ fileList: Array.isArray(this.props.value) ? this.props.value.map((v) => ({ url: v, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', })) as UploadFile<any>[]: [{ url: this.props.value, uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', }] as UploadFile<any>[] }) } } handleCancel = () => this.setState({ previewVisible: false }); handleModalCancel = () => this.setState({ wallModalVisible: false }); handlePreview = async (file: UploadFile<any>) => { if (!file.url && !file.preview) { file.preview = await getBase64(file.originFileObj!); } this.setState({ previewImage: file.url || file.preview, previewVisible: true, previewTitle: file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1), }); }; handleWallSelect = (url: string) => { this.setState({ wallModalVisible: true, }); }; handleImgSelected = (url: string) => { this.setState({ curSelectedImg: url, }); }; handleWallShow = () => { this.setState({ wallModalVisible: true, }); }; handleModalOk = () => { const { maxLen = 1 } = this.props; const fileList = [ { uid: uuid(8, 16), name: '熊猫运维中台系统', status: 'done', url: this.state.curSelectedImg, }, ]; this.props.onChange && this.props.onChange( maxLen === 1 ? fileList[0].url : fileList.map(f => f.url)); this.setState({ fileList, wallModalVisible: false }); }; handleChange = ({ file, fileList }: UploadChangeParam<UploadFile<any>>) => { const { maxLen = 1 } = this.props; this.setState({ fileList }); if (file.status === 'done') { const files = fileList.map(item => { const { status, data, name, thumbUrl } = item; const url = item.response && item.response.data || thumbUrl ; return { uid: uuid(8, 16), name, status, url }; }); this.setState({fileList: files}) this.props.onChange && this.props.onChange( maxLen === 1 ? files[0].url : files.map(f => f.url)); } }; handleBeforeUpload = (file: RcFile) => { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif'; if (!isJpgOrPng) { message.error('只能上传格式为jpeg/png/gif的图片'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('图片必须小于2MB!'); } return isJpgOrPng && isLt2M; }; componentDidMount() { const { type = ''} = this.props; getImageBases(type).then(res => { if(res.code === 0){ this.setState({imgBed: res.data}) } }) } getImageUrl(path){ if(path&&path.indexOf('http') === 0){ return path } if(path&&path.indexOf('data:') === 0) { return path } if(path && path.indexOf('assets') === 0) { return `${window.location.origin}/Web4/${path}`.replace(/\\/g, '/') } return `${window.location.origin}/${path}`.replace(/\\/g, '/') } render() { const { previewVisible, previewImage, fileList, previewTitle, wallModalVisible, imgBed, curSelectedImg, } = this.state; const { action = `${window.location.origin}${PUBLISH_SERVICE}/FileCenter/UploadSingleFile` , headers, withCredentials = true, maxLen = 1, cropRate = 375 / 158, isCrop, } = this.props; const uploadButton = ( <div> <PlusOutlined /> <div className="ant-upload-text">上传</div> </div> ); return ( <> {isCrop ? ( <ImgCrop modalTitle="裁剪图片" modalOk="确定" modalCancel="取消" rotate={true} aspect={cropRate as number} > <Upload fileList={fileList.map(f => ({...f, url: this.getImageUrl(f.url) }))} onPreview={this.handlePreview} onChange={this.handleChange} name="singleFile" listType="picture-card" className={styles.avatarUploader} action={action} withCredentials={withCredentials} headers={{ // 'x-requested-with': localStorage.getItem('user') || '', Authorization: 'Bearer ' + localStorage.getItem('token') || '', ...headers, }} beforeUpload={this.handleBeforeUpload} > {fileList.length >= maxLen ? null : uploadButton} </Upload> </ImgCrop> ) : ( <Upload fileList={fileList.map(f => ({...f, url: this.getImageUrl(f.url) }))} onPreview={this.handlePreview} onChange={this.handleChange} name="singleFile" listType="picture-card" className={styles.avatarUploader} action={action} withCredentials={withCredentials} headers={{ // 'x-requested-with': localStorage.getItem('user') || '', Authorization: 'Bearer ' + localStorage.getItem('token') || '', ...headers, }} beforeUpload={this.handleBeforeUpload} > {fileList.length >= maxLen ? null : uploadButton} </Upload> )} <div className={styles.wallBtn} onClick={this.handleWallShow}> 从图片库选择 </div> <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={this.handleCancel} > <img alt="预览图片" className={styles.svgBg} style={{ width: '100%' }} src={this.getImageUrl(previewImage)} /> </Modal> <Modal visible={wallModalVisible} title="图片库" okText="确定" cancelText="取消" width={860} onCancel={this.handleModalCancel} onOk={this.handleModalOk} > <Tabs defaultActiveKey={imgBed[0]?.moduleName} tabPosition="left" style={{ height: 520 }}> {imgBed.map((item, i) => { return ( <TabPane tab={item.moduleName} key={item.moduleName}> <div className={styles.imgBox}> {item.child?.map(m => m.fileUrls).flat(Infinity).map((item: string, i: number) => { return ( <div className={classnames( styles.imgItem, curSelectedImg === item ? styles.seleted : '', )} key={i} onClick={() => this.handleImgSelected(item)} > <img src={this.getImageUrl(item)} alt="熊猫运维中台系统" /> <span className={styles.iconBtn}> <CheckCircleFilled /> </span> </div> ); })} </div> </TabPane> ); })} <TabPane tab="更多" key="more"> <Result status="500" title="温馨提示" subTitle="更多素材, 正在筹备中..." /> </TabPane> </Tabs> </Modal> </> ); } } export default PicturesWall;