import { upload } from '@/utils/upload'
import { PlusOutlined } from '@ant-design/icons'
import { Button, Upload } from 'antd'

export default function AppUpload({ value, onChange, ...props }: any) {
  const generateFileList = (file: any) => {
    if (!file || !file.name || !file.url) return []
    return [
      {
        uid: Date.now().toString(),
        name: file.name,
        status: 'done',
        url: file.url,
      },
    ]
  }
  const fileList = generateFileList(value)

  const [file] = fileList

  // 自定义上传
  const customRequest = async ({ onSuccess, onError, file }: any) => {
    try {
      const url = await upload(file)
      onChange?.({ name: file.name, url })
      onSuccess(url)
    } catch (error) {
      onError(error)
    }
  }

  return (
    <Upload customRequest={customRequest} fileList={fileList} showUploadList={false} maxCount={1} {...props}>
      <Button type="primary" shape="circle" size="large" icon={<PlusOutlined />} />
      <span style={{ marginLeft: '10px' }}>{file?.name}</span>
    </Upload>
  )
}
