import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useState } from 'react';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';

interface uploadProps {
  onChange: (value: any) => void;
  value: any;
  maxCount: number;
}

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

/**
 * 上传图片组件
 * @param props
 * @constructor
 */
const UploadCommon: React.FC<uploadProps> = (props) => {
  const { value, onChange, maxCount } = props;
  const [fileList, setFileList] = useState(value || []);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  // 查看弹框关闭
  const handleCancel = () => setPreviewOpen(false);

  // 查看
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
    onChange(newFileList);
  };

  return (
    <div>
      <Upload
        action="/web/v1/files"
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        maxCount={maxCount}
      >
        {<PlusOutlined />}
      </Upload>
      <Modal open={previewOpen} footer={null} onCancel={handleCancel}>
        <img alt="图片" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};
export default UploadCommon;
