import { Carousel } from "antd";
import React, { useState, useRef, useEffect, useMemo } from "react";
import { getBannerList } from "@/services/rotationChart";

import VideoPlay from "./components/VideoPlay";

const height = "100%";
const contentStyle = {
  height,
  margin: "0 auto",
  width: "100%",
};

export default (props) => {
  const [height, setHeight] = useState('100%');
  const [current, setCurrent] = useState(0);
  const [mouse, setMouse] = useState(false);
  const [mediaList, setMediaList] = useState([]);

  const ref = useRef();
  const boxRef = useRef();
  const mouseRef = useRef(false);
  const isVideoRef = useRef(false);
  const isVideoPlayRef = useRef(false);

  const itemStyle = useMemo(() => ({
    height,
    overflow: 'hidden',
    width: '100%',
    objectFit: 'contain',
  }), [height]);

  useEffect(() => {
    getBannerList().then((res) => {
      setMediaList(
        res?.records?.map((x) => {
          if (x.type === "2") {
            return {
              ...x,
              type: "video",
              url: x.video,
            };
          } else {
            return {
              ...x,
              type: "image",
              url: x.image,
            };
          }
        })
      );
    });
    handNext();

    const boxHeight = boxRef.current.offsetHeight;
    setHeight(boxHeight ? `${boxHeight}px` : '100%');
  }, []);

  const handNext = () => {
    setTimeout(() => {
      if (!mouseRef.current && !isVideoRef.current && !isVideoPlayRef.current) {
        ref.current?.next();
      }
      handNext();
    }, 3000);
  };

  const onMouseEnter = () => {
   
    mouseRef.current = true;
  };
  const onMouseLeave = () => {
    mouseRef.current = false;
  };

  return (
    <div
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      style={{ height, overflow: "hidden", background: '#081A48' }}
      ref={boxRef}
    >
      <Carousel
        ref={ref}
        afterChange={(cur) => {
          setCurrent(cur);
        }}
      >
          {mediaList?.map((x, index) => (
            <div key={index}>
              { x.type === "image" && <img src={x.url} style={itemStyle}></img> }
              { x.type === "video" && (
                <VideoPlay
                  url={x.url}
                  isVideoPlayRef={isVideoPlayRef}
                  index={index}
                  current={current}
                  style={itemStyle}
                />
              )}
            </div>
          ))}
      </Carousel>
    </div>
  );
};
