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

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/gif';
  if (!isJpgOrPng) {
    message.error('请上传 JPG,PNG 或 GIF 图片!');
  }
  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>
);

const defaultInput = x => ({ uid: x, url: x });
const defaultOutput = x => x.url;

export default (props) => {
  const { value, onChange, input = defaultInput, output = defaultOutput } = props;

  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState();
  const [fileList, setFileList] = useState([]);

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

    if (info.file.status === 'removed') {
      toggleChange(info.fileList)
    }
  };

  const handleSuccess = ({url}) => {
    setLoading(false)
    const inx = fileList?.length ? fileList.length + 1 : 1
    const list = fileList.concat({
      url,
      uid: `new-${inx}`,
      status: 'done'
    })
    toggleChange(list)
  }

  const toggleChange = (list) => {
    onChange(list.map(x => output(x)))
  }

  const handlePreview = (file) => {
    setPreviewImage(file.url)
    setPreviewVisible(true)
  }

  useEffect(() => {
    const lst = (value || []).map((it) => {
      const { uid, url } = input(it)
      return {
        uid,
        url,
        status: 'done',
        raw: it,
      }
    })
    setFileList(lst)
  }, [value])

  return (
    <>
      <Upload
        listType="picture-card"
        className="image-uploader"
        fileList={fileList}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        onPreview={handlePreview}
        onSuccess={handleSuccess}
      >
        <UploadButton loading={loading} />
      </Upload>
      <Modal
        visible={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
}

