/*
 * @Author: Nian Yi
 * @Date: 2022-05-23 13:57:10
 * @LastEditTime: 2022-05-25 10:58:20
 * @LastEditors: Nian Yi
 * @Description: 资源上传
 * @FilePath: /easyvadmin/src/scripts/components/NewUploadThumb/index.tsx
 * 奥利给
 */
import React, { useState, useCallback, useMemo } from 'react';
import { Upload } from '@easyv/antd';
import message from 'components/message';
import defaultImg from 'images/icon_upload.svg';
import styles from './index.less';

const typeConfig = {
  image: '图片',
  video: '视频',
  model: '模型',
};

function UploadThumb(
  {
    style = {},
    url = defaultImg,
    maxSize = 1024 * 200,
    type = 'image',
    onChange,
    accept,
  }: {
    style?: any;
    url: string;
    maxSize?: number;
    type?: string;
    onChange?: (file?: any) => void;
    accept?: string;
  },
  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);
  };

  const isImage = type === 'image';
  const localAccept = useMemo(()=>{
    if(accept){
      return accept
    }else{
      return isImage ? 'image/*' : 'video/*'
    }
  },[accept,isImage]);

  const width = style.width || 200;
  const height = style.height || 120;

  return (
    <div ref={refs} className={styles.containerBox} style={{ ...style }}>
      <div className={styles.container}>
        <Upload.Dragger
          showUploadList={false}
          accept={localAccept}
          beforeUpload={handleBeforeUpload}
          className={styles.thumb}>
          {!src ? (
            <div className={styles.defaultImg}>
              <img src={defaultImg} />
              <p>
                上传 {getSize(maxSize)} 以内的 {typeConfig[type]}
              </p>
            </div>
          ) : isImage ? (
            <img
              style={{ objectFit: 'contain', background: '#000' }}
              src={src}
              height={height} width={width}
              onError={handleImageError}
            />
          ) : type === 'video' ? (
            <video src={src} height={height} width={width} />
          ) : (
            <img height={height} width={width} style={{ objectFit: 'contain', background: '#000' }} src={defaultImg} />
          )}
        </Upload.Dragger>
      </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);
