import { Image, Video, VideoProps } from "@tarojs/components";
// import style from "../index.module.less";
import { useEffect, useRef } from "react";
import Taro from "@tarojs/taro";

interface Props {
  source: string;
  className: string;
}

export const AvatarMedia = ({ source, className }: Props) => {
  
  const videoRef = useRef<React.ComponentType<VideoProps>|null>(null);
  const videoContext = useRef<Taro.VideoContext|null>(null);
  const videoId = useRef(`video-${Math.random().toString(36).substr(2, 9)}`);

  const videoErrorCallback = (e) =>  {
    console.log('Video error info:')
    console.log(e.detail)
 }

 // 处理 ios 上无法循环播放的 bug
 const handleOnEnded = () => {
  if(videoContext.current){
    videoContext.current.seek(0)
    videoContext.current.play()
  }
 }


  useEffect(() => {
    if (videoRef.current) {
      videoContext.current = Taro.createVideoContext(videoId.current, this);
    }
  }, []);

  if (source.lastIndexOf('.mp4') > -1) {
    return (
      <Video
        id={videoId.current}
        ref={videoRef}
        controls={false}
        showCenterPlayBtn={false}
        loop={true}
        muted={true}
        autoplay
        onEnded={handleOnEnded}
        objectFit="cover"
        className={className}
        onError={videoErrorCallback}
        // src="https://cdn.wehome.cn/cmn/mp4/3/META-H8UKWHWU-YAUTZH7ECGRDC57FD3NI3-CUGVCS8M-CD.mp4"
        src={source}
      />
    );  
  }

  return (
    <Image
      mode="widthFix"
      className={className}
      src={source}
    />
  );
};
