import React, { useState, useCallback } from 'react';
import { Upload } from '@easyv/antd';
import message from 'components/message';
import defaultImg from 'images/default.png';
import styles from './index.less';

function UploadThumb({ width = 100, height = 60, url = defaultImg, maxSize = 1024 * 200, type = 'image', onChange }, refs) {
  const [src, setSrc] = useState(url);

  const handleBeforeUpload = useCallback(
    (file) => {
      const isLarger = file.size > maxSize;

      if (isLarger) {
        message.error(`文件大小超出${getSize(maxSize)}`);
      } else {
        setSrc(window.URL.createObjectURL(file));
        onChange(file);
      }
      return false;
    },
    [maxSize]
  );

  const handleImageError = () => {
    setSrc(defaultImg);
  };

  return (
    <div ref={refs} className={styles.container}>
      <Upload.Dragger
        showUploadList={false}
        accept={type === 'image' ? 'image/*' : 'video/*'}
        beforeUpload={handleBeforeUpload}
        className={styles.thumb}>
        {!src ? (
          <div style={{ color: '#999' }}>
            <i className="icon iconfont icon-btn_addgroup" />
            <div>点击上传</div>
          </div>
        ) : type === 'image' ? (
          <img style={{ width, height, objectFit: 'contain', background: '#000' }} src={src} onError={handleImageError} />
        ) : (
          <video src={src} style={{ width, height }} />
        )}
      </Upload.Dragger>
      <div>
        <p className={styles.desc}>单击重新上传</p>
        <p className={styles.desc}>{getSize(maxSize)}以内100*60px图片</p>
      </div>
    </div>
  );
}

function getSize(size) {
  return size / 1024 < 1024 ? `${Math.floor(size / 1024)}KB` : `${Math.floor(size / 1024 / 1024)}M`;
}

export default React.forwardRef(UploadThumb);
