import React, { useCallback, useState } from 'react'
import { UploadOutlined } from '@ant-design/icons';
import { Upload, Button } from 'antd';
import { uploadFile } from '@/services/rotationChart';

const customRequest = ({ file, onError, onSuccess }) => {
  const data = new FormData();
  data.append('file', file);

  uploadFile(data).then((res) => {
    onSuccess(res.url)
  }).catch((err) => {
    onError(err);
  })

  return {
    abort() {
      console.log('upload progress is aborted.');
    },
  };
}

export default (props) => {
  const { value, onChange, preview, ...inputProps } = props;
  const [loading, setLoading] = useState(false);

  const onUpload = useCallback((e) => {
    const { files } = e.target;
    if (!files || files.length < 1) return;

    setLoading(true);
    const data = new FormData();
    data.append('file', files[0]);

    uploadFile(data).then((res) => {
      setLoading(false);
      if (typeof onChange === 'function') {
        onChange(res.url)
      }
    }).catch((err) => {
      setLoading(false);
      // onError(err);
    })

  }, [onChange])

  const onClick = () => {
    const input = document.createElement('input');
    input.type = 'file';
    Object.assign(input, inputProps);    
    input.addEventListener('change', onUpload);
    // input.removeEventListener('change', onUpload);
    input.click();
  }

  return (
    <div>
      <Button icon={<UploadOutlined />} onClick={onClick}>上传文件</Button>
      {
        value && typeof preview === 'function' && preview(value)
      }
    </div>
  )
}
