import { Button, Upload, message } from 'antd'
import { useState } from 'react'
import { uploadFile } from '@/utils/oss'
import './index.less'

export default function UploadImage({ value, onChange }) {
  const [uploading, setUploading] = useState(false)

  const uploadProps = {
    name: 'file',
    accept: '.jpg,.png',
    showUploadList: false,
    beforeUpload: async file => {
      const suffixArr = ['jpg', 'png']
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}格式的书籍`)
        return false
      } else if (file.size >= 1024 * 1024) {
        message.error(`请上传大小在1M以内的图片`)
        return false
      }
    },
    customRequest: async ({ file }) => {
      try {
        setUploading(true)
        const url = await uploadFile(file)
        setUploading(false)
        onChange(url)
        return true
      } catch (error) {
        message.error('上传文件失败，请重试')
        setUploading(false)
        return false
      }
    }
  }

  return (
    <div className="upload-image">
      {value && <img src={value} width={88} height={88} style={{ borderRadius: 5 }} />}
      <div className="upload-image-main">
        <Upload {...uploadProps}>
          <Button type="primary" ghost loading={uploading}>
            点击上传
          </Button>
        </Upload>
        <span className="tips">尺寸：只能上传jpg/png文件，且不超过1M</span>
      </div>
    </div>
  )
}
