import React from 'react'

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

type UploadWrapperProps = {
  articleID: number
  insertPdf: any
  value?: string
  onChange?: (value: string) => void
}

const FileUploadWrapper: React.FC<UploadWrapperProps> = props => {
  const initValue = props.value
    ? [
        {
          uid: '-1',
          name: 'file.pdf',
          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.response.code !== 0) {
          message.error(`pdf上传失败:${file.response.ErrMsg}`)
        } else {
          message.success(`pdf上传成功，开始插入图片`)
          file.url = file.response.data.pdfLinkPath.replace(/\s+/g, '%20')
          if (props.onChange) {
            props.onChange(file.response.data.pdfLinkPath.replace(/\s+/g, '%20'))
          }
          props.insertPdf(file.response.data.pdfLinkPath, file.response.data.linkPath)
        }
      }
      return file
    })
    setFileList(fileList)
  }

  const uploadProps = {
    action: `${document.location.origin}/service/vmp_api_pdf2svg/api/file`,
    data: { partition_id: props.articleID },
    onChange: handleChange,
    multiple: false,
    listType: 'picture' as const
  }
  return (
    <Upload {...uploadProps} fileList={fileList}>
      <Button icon={<UploadOutlined />}>上传并插入超链接+图片</Button>
    </Upload>
  )
}

export default FileUploadWrapper
