import React, { useEffect, useState } from 'react';
import { Upload } from '@easyv/antd';
import message from 'components/message';
import isObject  from 'lodash/isObject';
import style from './index.less';
import { UploadChangeParam, UploadFile } from '@easyv/antd/lib/upload/interface';

function isImage(str) {
  const reg = /(png|jpg|jpeg|webp|icon|svg|ico)$/;
  return reg.test(str);
}

type ImageUploadInterface = {
  title: string;
  dpr?: string;
  size: number;
  format: string;
  imgUrl?: string | null |  Blob;
  defaultImgUrl: string;
  onChange: (info?: UploadChangeParam) => void;
};

const ImageUpload = ({ title, dpr = '', size, format, onChange, imgUrl, defaultImgUrl }: ImageUploadInterface) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
      useEffect(()=>{
        if(imgUrl){
          const url:any = isObject(imgUrl) && imgUrl.size ? window.URL.createObjectURL(imgUrl) :imgUrl;
          setFileList([
            {
              uid: '-1',
              name: 'image.png',
              status: 'done',
              url,
              size: 1,
              type: 'image/png'
            }
          ])
        }else{
          setFileList([]);
        }
      },[
        imgUrl  
      ])

  const beforeUpload = (file) => {
    const type = file.type.split('/')[1];
    if (!isImage(type)) {
      message.error('请选择图片');
      return false;
    }
    const isLt2M = file.size / 1024 < size;
    if (!isLt2M) {
      message.error('超出图片大小限制，请上传规则图片');
      return false;
    }
    onChange(file);
    setFileList([
      {
        uid: file.uid,
        name: file.name,
        status: 'done',
        url: window.URL.createObjectURL(file),
        size: 1,
        type: file.type //不要固定媒体类型
      }
    ]);
    return false;
  };

  const handlePreview = (file) => window.open(file.url);

  const handleDelete = () => {
    setFileList([]);
    onChange();
  };

  const defaultCover = (
    <div className={style.img}>
      <img style={{ objectFit: 'scale-down' }} src={defaultImgUrl} alt="avatar" />
    </div>
  );

  return (
    <div className={style.wrap}>
      <div className={style.title}>{title}</div>
      <div className={style.file_select_wrap}>
        <Upload
          name="file"
          accept=".png,.jpg,.jpeg,.webp"
          listType="picture-card"
          fileList={fileList}
          onPreview={handlePreview}
          onRemove={handleDelete}
          beforeUpload={beforeUpload}>
          {fileList.length === 1 ? null : defaultCover}
        </Upload>
      </div>
      <div className={style.text}>
        <div>单击图片重新上传</div>
        {size ? <div>图片大小：≤{size}KB</div> : null}
        {dpr ? <div>建议分辨率：{dpr}</div> : null}
        <div>建议格式：{format}</div>
      </div>
    </div>
  );
};
export default ImageUpload;
