import React from 'react'

import { Upload, Button, message } from 'antd'
import ImgCrop from 'antd-img-crop'
import { UploadOutlined } from '@ant-design/icons'
import { UploadFile } from 'antd/es/upload/interface'

type UploadWrapperProps = {
  value?: string
  onChange?: (value: string) => void
  imgCrop?: boolean
}

const ImgUploadWrapper: React.FC<UploadWrapperProps> = props => {
  const initValue = props.value
    ? [
        {
          uid: '-1',
          name: 'cover.png',
          status: 'done' as const,
          url: props.value,
          thumbUrl: props.value,
          size: 1,
          type: '1'
        }
      ]
    : undefined
  const [fileList, setFileList] = React.useState<UploadFile[] | undefined>(initValue)

  const handleChange = (info: { fileList: UploadFile[] }) => {
    let fileList = [...info.fileList]
    fileList = fileList.slice(-1)
    fileList = fileList.map(file => {
      if (file.response) {
        if (file.error) {
          message.error(`封面上传失败`)
        } else {
          message.success(`封面上传成功`)
          file.url = file.response.data
          if (props.onChange) {
            props.onChange(file.response.data)
          }
        }
      }
      return file
    })
    setFileList(fileList)
  }

  const uploadProps = {
    action: `${document.location.origin}/service/vmp_api_upload/api/img/uuid`,
    // action: `https://vmp.hzinsights.com/service/vmp_api_img/api/img`, //开发环境测试
    onChange: handleChange,
    multiple: false,
    listType: 'picture' as const
  }

  const ImgUploadElement = (
    <Upload {...uploadProps} fileList={fileList}>
      <Button icon={<UploadOutlined />}>Upload</Button>
    </Upload>
  )
  return props.imgCrop ? (
    <ImgCrop modalTitle="图片剪裁" aspect={4 / 3}>
      {ImgUploadElement}
    </ImgCrop>
  ) : (
    ImgUploadElement
  )
}

export default ImgUploadWrapper
