import { Button, Modal } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import { getFileUrl } from "../../utils";
import AliPlayer from "./AliPlayer";

/**
 * 视频播放组件
 */
const Video = forwardRef(({
  source = "",
  vid = "",
  playAuth = "",
  cover = "",
  autoplay = true,
  showProgress = true,
  playTime = 0,
  inline = false,
  isLive = false,
  width = "100%",
  height = "600px",
  title = "视频",
  visible: externalVisible = false,
  onCancel,
  onEnded,
  onTimeupdate,
  onGetPlayerInstance,
  aliPlayerProps = {},
}, ref) => {
  const [internalVisible, setInternalVisible] = useState(false);
  const playerRef = useRef(null);

  useImperativeHandle(ref, () => ({
    play: () => {
      playerRef.current && playerRef.current.play();
    },
    pause: () => {
      playerRef.current && playerRef.current.pause();
    },
    getPlayerInstance: () => playerRef.current && playerRef.current.getPlayerInstance(),
  }));

  const visible = onCancel ? externalVisible : internalVisible;
  const setVisible = onCancel || setInternalVisible;

  const getSource = () => {
    if (!source)
      return;
    if (source.includes("http") || source.includes("https"))
      return source;
    else return getFileUrl() + source;
  };

  useEffect(() => {
    if (!inline) {
      if (visible) {
        playerRef.current && playerRef.current.play();
      }
      else {
        playerRef.current && playerRef.current.pause();
      }
    }
  }, [visible, inline]);

  const playerElement = (
    <AliPlayer
      ref={playerRef}
      source={getSource()}
      vid={vid}
      playAuth={playAuth}
      cover={cover}
      autoplay={autoplay}
      showProgress={showProgress}
      playTime={playTime}
      isLive={isLive}
      width={width}
      height={height}
      aliPlayerProps={aliPlayerProps}
      onEnded={onEnded}
      onTimeupdate={onTimeupdate}
      onGetPlayerInstance={onGetPlayerInstance}
    />
  );

  if (!inline) {
    return (
      <Modal
        open={visible}
        width={800}
        title={title}
        footer={[
          <Button key="cancel" onClick={() => setVisible(false)}>
            关闭
          </Button>,
        ]}
        maskClosable={false}
        onCancel={() => setVisible(false)}
      >
        {playerElement}
      </Modal>
    );
  }

  return playerElement;
});

Video.displayName = "Video";

export default Video;
