import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import { useState } from 'react';

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('请上传 JPG 或 PNG 图片!');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('图片大小必须小于 10MB!');
  }

  return isJpgOrPng && isLt10M;
}

const UploadButton = (props) => (
  <div>
    {props.loading ? <LoadingOutlined /> : <PlusOutlined />}
    <div style={{ marginTop: 8 }}>上传</div>
  </div>
);

export default (props) => {
  const { value, onChange } = props;

  const [loading, setLoading] = useState(false);

  const handleChange = (info) => {
    console.log(info,'--333-')
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'error') {
      setLoading(false);
      return;
    }

    if (info.file.status === 'done') {
      setLoading(false);
      onChange(info.file.response);
    }
  };

  const uploadFile = () => {};

  return (
    <Upload
      // customRequest={uploadFile}
      action={'/api/upload'}
      accept='image/*'
      listType="picture-card"
      className="image-uploader"
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {value ? (
        <img src={value} alt="avatar" style={{ width: '100%', height: '100%' }} />
      ) : (
        <UploadButton loading={loading} />
      )}
    </Upload>
  );
};
