import React, { useState, useEffect } from 'react';
import FileViewer from 'react-file-viewer';
import { Modal, Table } from 'antd';

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

  const renderListContent = () => {
    const columns = [
      { title: '文档名称', dataIndex: 'name' },
      {
        title: '操作',
        render: (_, record) => (
          <a
            onClick={() => {
              const arr = record.name.split('.');
              const type = arr[arr.length - 1];
              const dataItem = { url: record.url, name: record.name, type };
              setImg(dataItem);
            }}
          >
            查看
          </a>
        ),
      },
    ];
    return (
      <>
        <Table columns={columns} dataSource={data} />
        {img && renderContent(img)}
      </>
    );
  };

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

export default FileViewerModal;
