import React, { useState } from 'react';
import { setProperty } from '@/utils/css';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Upload from './Upload';
import styles from './style.less';

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

  return isImage && isLt10M;
}

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

export default (props) => {
  const { value, onChange, width = 200, ratio = 1 } = props;

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

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

    if (info.file.status === 'done') {
      setLoading(false);
      const { url, fileType } = info.file.response;
      // console.log('--------方--url-.>', url);
      onChange(url);
    }
  };

  const previewUrl = getRealPath ? getRealPath(value) : value;
  // console.log('--------previewUrl----->', previewUrl);
  React.useEffect(() => {
    setProperty('--cust-upload-ratio', ratio);
  }, [ratio]);

  React.useEffect(() => {
    setProperty('--cust-upload-width', `${width}px`);
  }, [width]);

  // console.log('-----里层----->value,', value);
  return (
    <Upload
      listType="picture-card"
      className={styles['ant-upload']}
      style={{ width: '200px' }}
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {value ? <img src={previewUrl} className="cust-img-thumb" alt="avatar" style={{ width: '100%', height: '100%' }} /> : <UploadButton loading={loading} />}
    </Upload>
  );
}
