import { Form, Image, Upload } from "antd";
import { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
const isImage = (url) =>
  /\.(png|jpe?g|gif|bmp|webp|svg)(\?.*)?$/i.test(url || "");

export default function AttachmentUpload({ name, label, disabled = false, maxCount, accept }) {
  const [previewImage, setPreviewImage] = useState("");

  return (
    <>
      <Form.Item
        name={name}
        label={label}
        valuePropName="fileList"
        getValueProps={(value) => {
         
          if (Array.isArray(value)) {
            return { fileList: value };
          }
          return {
            fileList: value
              ? value.split(",").map((item) => ({
                  url: item,
                  uid: item,
                  status: "done",
                  name: "附件",
                }))
              : [],
          };
        }}
        getValueFromEvent={({ fileList }) => {
         
          return (
            fileList?.map((file) => ({
              url: file.response?.data?.url || file.url,
              uid: file.uid,
              status: file.status,
              name: file.name,
              percent: file.percent,
            })) || []
          );
        }}
      >
        <Upload
          disabled={disabled}
          listType="picture-card"
          maxCount={maxCount}
          accept={accept}
          action={`${window.process.env.app.API_HOST}/safetyEval/file/upload`}
          onPreview={(file) => {
            if (isImage(file.url || file.thumbUrl)) {
              setPreviewImage(file.url || file.thumbUrl);
            } else {
              window.open(file.url || file.thumbUrl);
            }
          }}
        >
          <button style={{ border: 0, background: "none" }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传附件</div>
          </button>
        </Upload>
      </Form.Item>
      <Image
        style={{ display: "none" }}
        preview={{
          visible: !!previewImage,
          src: previewImage,
          onVisibleChange: (visible) => {
            if (!visible) setPreviewImage("");
          },
        }}
      />
    </>
  );
}
