import { MinusCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Image, message } from 'antd';
import React from 'react';
import Upload from '../../../components/Upload';
import { SUPPORT_IMAGE_ACCEPT } from '../../../constants';
import { FileController } from '../../../services';
import styles from './index.less';

type ImgFormProps = {
  url: string;
  onChange: (url?: string) => void;
};

const ImgForm: React.FC<ImgFormProps> = (props) => {
  const { url, onChange } = props;
  const onUpload = async (files: any) => {
    const [file] = files || [];
    if (!SUPPORT_IMAGE_ACCEPT.includes(file.type)) {
      message.error('不支持的图片格式!');
      throw new Error('error');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片最大不超过2MB!');
      throw new Error('error');
    }
    const forms = new FormData();
    forms.append('type', '0');
    forms.append('picType', '9');
    forms.append('file', file);
    forms.append('isSvg', '2');
    const ret = await FileController.uploadApi(forms);
    onChange(ret.data?.url || '');
  };
  return (
    <div className={styles.imgBlock}>
      {url ? (
        <div className={styles.imgBox}>
          <div className={styles.imgClear} onClick={() => onChange()}>
            <MinusCircleOutlined />
          </div>
          <Image src={url} style={{ maxWidth: 200 }}></Image>
        </div>
      ) : (
        <Upload
          accept={SUPPORT_IMAGE_ACCEPT.join(',')}
          onUpload={onUpload}
          trigger={
            <Button type="default" icon={<UploadOutlined />} size="middle">
              上传图片
            </Button>
          }
        ></Upload>
      )}
    </div>
  );
};

export default ImgForm;
