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 'components/UploadThumb/index.less';

function UploadModel({ width = 100, height = 60, url = defaultImg, maxSize = 1024 * 200, 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=".fbx, .glb, .zip" beforeUpload={handleBeforeUpload} className={styles.thumb}>
        {!src ? (
         <div className={styles.defaultImg}>
         <img src={defaultImg} />
         <p>
           上传 {getSize(maxSize)} 以内的文件
         </p>
       </div>
        ) : (
          <img style={{ width, height, objectFit: 'contain', background: '#000' }} src={src} onError={handleImageError} />
        )}
      </Upload.Dragger>
      <div>
        <p className={styles.desc}>格式：.glb .fbx .zip</p>
        <p className={styles.desc}>大小：{getSize(maxSize)}以内</p>
      </div>
    </div>
  );
}

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

export default React.forwardRef(UploadModel);
