import React, { useMemo, useState } from 'react';
import { Upload, Button, Spin } from '@easyv/antd';
import message from 'components/message';
import { uploadAssets } from 'utils/upload';
import sourceImg from 'images/sourceImg.png';

const accept = {
  1: 'image/*',
  2: 'video/*',
  3: '.fbx, .glb, .zip'
};

const size = {
  1: 2,
  2: 200,
  3: 150
};

function getBase64(file) {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader();
    let imgResult: any = '';
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgResult = reader.result;
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
}

export default function Dragger({ prefixCls, type, onSize, value, onChange, uploadType, ...args }: any) {
  const [loading, setLoading] = useState(false);
  const [src, setSrc] = useState<any>('');

  const reselect = () => {
    const upload: any = document.querySelector(`.${prefixCls}-upload input[id=${uploadType}]`);
    upload.click();
  };

  const fileType = useMemo(() => {
    switch (type) {
      case 1:
        return 'image';
        break;
      case 2:
        return 'video';
      default:
        return 'assets';
        break;
    }
  }, [type]);

  const beforeUpload = (file: File) => {
    if (file.size > size[type] * 1024 * 1024) {
      message.error(`${file.name}不能大于${size[type]}M`);
    } else {
      setLoading(true);
      previewFile(file);
      const fileName = `data/${fileType}/${file.name}`;
      // 1 图片；2 视频 ; 其他 assets
      uploadAssets({ path: fileName, file }).then((path) => {
        onChange(path);
        if (type === 3) {
          onSize(file.size);
        }
        setLoading(false);
      });
    }
    return false;
  };

  const previewFile = (file) => {
    getBase64(file).then((str) => {
      setSrc(str);
    });
  };

  return (
    <div className={`${prefixCls}-upload`}>
      <Spin spinning={loading}>
        <Upload.Dragger {...args} accept={accept[type]} showUploadList={false} beforeUpload={beforeUpload}>
          <div className={`${prefixCls}-dragger`}>
            <i className={`${prefixCls}-dragger-icon`} />
            <p>单击或拖放文件至此处进行上传</p>
            {type === 3 ? (
              <p>
                文件大小不超过{size[type]}MB，支持格式.fbx
                <br />
                (包含fbx、jpg、obj等格式文件的压缩包) /.glb .zip
              </p>
            ) : (
              <p>不得超过{size[type]}M</p>
            )}
          </div>
        </Upload.Dragger>
        {value && (
          <div className={`${prefixCls}-upload-preview`}>
            {type === 1 || type === 3 ? <img src={type === 3 ? sourceImg : src} /> : <video src={src} />}
            <div className={`${prefixCls}-upload-preview-operate`}>
              <Button type="primary" onClick={reselect}>
                更改
              </Button>
            </div>
          </div>
        )}
      </Spin>
    </div>
  );
}
