import { Button, Space } from "antd";
import { useState } from "react";
import { getFileName } from "../../utils";
import Pdf from "../Pdf";

/**
 * 在查看页面中PDF查看组件
 */
const PreviewPdf = (props) => {
  const {
    files = [],
    nameKey = "",
    urlKey = "",
    name = "",
    url = "",
  } = props;

  const [visible, setVisible] = useState(false);
  const [currentSrc, setCurrentSrc] = useState("");
  const [currentName, setCurrentName] = useState("");

  const previewPdf = (src, name) => {
    setVisible(true);
    setCurrentSrc(src);
    setCurrentName(name);
  };

  const onCancel = () => {
    setVisible(false);
    setCurrentSrc("");
    setCurrentName("");
  };

  const extractFileName = (item) => {
    return item.name || item.fileName || item[nameKey] || getFileName(item.filePath || item[urlKey]);
  };

  // 单个文件预览模式
  if (files.length === 0 && name && url) {
    return (
      <>
        <Space>
          <span>{name}</span>
          <Button type="primary" size="small" onClick={() => previewPdf(url, name)}>
            预览
          </Button>
        </Space>
        <Pdf
          visible={visible}
          file={currentSrc}
          name={currentName}
          onCancel={onCancel}
        />
      </>
    );
  }

  // 多文件预览模式
  if (files.length > 0 && !name && !url) {
    return (
      <>
        {files.map(item => (
          <div key={item.filePath || item[urlKey]} style={{ marginTop: 5 }}>
            <Space>
              <span>{ extractFileName(item)}</span>
              <Button
                type="primary"
                size="small"
                onClick={() => previewPdf(item.filePath || item[urlKey], extractFileName(item))}
              >
                预览
              </Button>
            </Space>
          </div>
        ))}
        <Pdf
          visible={visible}
          file={currentSrc}
          name={currentName}
          onCancel={onCancel}
        />
      </>
    );
  }

  return null;
};

PreviewPdf.displayName = "PreviewPdf";

export default PreviewPdf;
