import React, { useCallback, useState ,useEffect} from 'react'
import { Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { RcFile } from 'antd/lib/upload';
import { CameraOutlined } from '@ant-design/icons';
import style from './index.less'
/**上传图片单独组件*/
type Props={
    callbakc:(fileData:{file:File,fileUrl:any})=>void
}
function UpImg(props:Props) {
    const [fileList, setFileList] = useState<any[]>([])
    const [previewVisible, setPreviewVisible] = useState<boolean>(false)
    const [fileUrl, setFileUrl] = useState<any>('')
    const [file, setFile] = useState<any>({})
     //文件上传获取
     const fileChanage = useCallback((e: any) => {
        try {
            let file = e?.target?.files || e
            if (file) {
                setFile(file[0] || file)
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload=function(e){
                    setFileUrl(this.result)
                }
            }
        } catch (err) {
            console.log(err)
        }
    }, [])
    //回调
    useEffect(()=>{
        if(fileUrl){
            props.callbakc({file,fileUrl})
        }
    },[file,fileUrl])
    return <div className={style.upimgBox}>
        <ImgCrop rotate>
            <Upload
                // listType="picture-card"
                accept='image/gif,image/jpeg,image/png,image/jpg'
                beforeUpload={function (file: RcFile) {
                    fileChanage(file)
                    return false
                }}
                // fileList={fileList}
                showUploadList={false}
                onChange={(newFileList: any) => {
                    setFileList([...newFileList.fileList])
                }}
                onPreview={(file: any) => {
                    setPreviewVisible(true)
                    setFileUrl(file.thumbUrl)
                }}
            >
                <div className={style.xj}><CameraOutlined style={{color:'#1890ff',fontSize:20}}/></div>
            </Upload>
        </ImgCrop>
    </div>
}
export default UpImg