import { Store } from "antd/es/form/interface";
import React, { useEffect } from "react";
// 声明 EasyPlayerPro 的类型
declare global {
  interface Window {
    EasyPlayerPro?: any; // 或者定义更精确的类型
  }
}

// 创建 Player 组件
const EasyPlayer = (props: Store) => {
  const myRef = React.useRef(null); // 用于引用 DOM 元素
  const easyPro = React.useRef<any>(null); // 存储播放器实例

  // 配置项
  const config = {
    isLive: true,
    bufferTime: 0.2,
    stretch: false,
    MSE: true,
    WCS: true,
    hasAudio: false,
  };
  const init = () => {
    if (easyPro.current) {
      easyPro.current?.destroy().then(() => {
        if (props.url) {
          create();
        }
      });
    } else {
      if (props.url) {
        create();
      }
    }
  };
  // 在组件挂载后创建播放器实例
  useEffect(() => {
    init()

    return () => {
      if (easyPro.current) {
        easyPro.current.destroy();
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [props.url]);

  // 创建播放器实例
  const create = () => {
    easyPro.current = new window.EasyPlayerPro(myRef.current, {
      isLive: config.isLive,
      bufferTime: config.bufferTime,
      stretch: false,
      MSE: config.MSE,
      WCS: config.WCS,
      hasAudio: config.hasAudio,
      watermark: { text: { content: "easyplayer-pro" }, right: 10, top: 10 },
      isMute: false,
    });
    play();
  };

  // 播放视频
  const play = () => {
    if (!easyPro.current) return create();
    easyPro.current
      ?.play(props.url)
      .then(() => {
        console.log("player started");
      })
      .catch((e) => {
        console.error("player error", e);
      });
  };

  return (
    <div
      style={{ width: "100%", height: "100%", backgroundColor: "#000000" }}
      ref={myRef}
    ></div>
  );
};
export default EasyPlayer;
