import React, { useEffect } from 'react';
import { Button, Empty } from 'antd';
import { FilePreviewProps, FilePreviewModelProps } from './interface';
import { aliyunFn } from '../common/aliyunFn';
import { YModalStyle, LoadingStyle } from './styles';
import { useModel } from './useModel';


const ModalBody: React.FC<FilePreviewProps> = (props) => {
  const { previewInfo, wrapId = '', aliyun, filePreviewStatus } = props;
  useEffect(() => {
    if (!aliyun) return;
    let filePreviewBox: any;
    if (previewInfo.previewURL && filePreviewStatus === 3) {
      setTimeout(() => {
        filePreviewBox = aliyun.config({
          mount: document.querySelector(`#YUpload-filePreview-wrap-${wrapId}`),
          url: previewInfo.previewURL
        })
        filePreviewBox.setToken({token: previewInfo.accessToken})
      })
    }
    return () => {
      filePreviewBox?.destroy();
    }
  }, [previewInfo.previewURL]);
  
  return (
    <LoadingStyle
      className="YUpload-filePreview-wrap"
      id={`YUpload-filePreview-wrap-${wrapId}`}
    />
  );
};

const FileModal: React.FC<FilePreviewModelProps> = (props) => {
  const { hideModal, wrapId, getRef } = props;
  const {
    noData,
    previewData,
    filePreviewStatus,
    hide,
    show,
    refresh,
    setFilePreviewStatus
  } = useModel(props);
  const aliyun = React.useRef();
  const baseProps = {
    filePreviewStatus,
    aliyun: aliyun.current,
    previewInfo: previewData
  }

  getRef({ show, hide, filePreviewStatus });

  useEffect(() => {
    aliyun.current = aliyunFn({}, wrapId);
  }, []);

  return hideModal ? (
    <>
      {!noData && filePreviewStatus !== 0  && filePreviewStatus !== 2 ? (
        <ModalBody {...baseProps} wrapId={wrapId} />
      ) : (
        <>
          {noData && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          {!noData && filePreviewStatus === 2 && (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} >
              <Button onClick={() => refresh()}>重新加载</Button>
            </Empty>
          )}
        </>
      )}
    </>
  ) :(
    <YModalStyle
      displayName
      visible={filePreviewStatus === 3}
      footer={null}
      content={() => (<ModalBody {...baseProps} />)}
      size="large"
      onOk={() => setFilePreviewStatus(0)}
      onCancel={() => setFilePreviewStatus(0)}
    />
  );
};

export default FileModal;
export const YFilePreview = FileModal;