import FileViewer from 'react-file-viewer';
import { Modal } from 'antd';
import { useMemo } from 'react';

const FileViewerModal = ({ data, visible, onCancel, downloadFile }) => {
  const type = useMemo(() => {
    if (!data || !data.url) return '';
    let url = data.url || '';
    let arr = url.split('.');

    return arr[arr.length - 1];
  }, [data?.url]);

  const renderContent = () => {
    if (type == 'xlsx') {
      return (
        <div>
          不支持的文件格式点击<a onClick={() => downloadFile(data)}>下载</a>
        </div>
      );
    } else if (data?.url) {
      return (
        <FileViewer
          
          key={data?.name}
          fileType={type}
          filePath={data?.url}
          onError={() => downloadFile(data)}
          errorComponent={() => (
            <div>
              文件加载错误点击<a onClick={() => downloadFile(data)}>下载</a>
            </div>
          )}
          unsupportedComponent={() => (
            <div>
              不支持的文件格式点击<a onClick={() => downloadFile(data)}>下载</a>
            </div>
          )}
        />
      );
    }
  };

  return (
    <Modal
      destroyOnClose
      title="预览"
      open={visible}
      width={1000}
      footer={null}
      onCancel={onCancel}
      bodyStyle={{ height: '680px', overflowY: 'hidden' }}
    >
      {renderContent()}
    </Modal>
  );
};

export default FileViewerModal;
