import { View, Image, Video, BaseEventOrig, VideoProps } from "@tarojs/components";
import type { TMediaType } from "@/types/index";
import style from "./index.module.less";
import { formatSeconds } from "@/utils/index";
import { useState } from "react";
interface Props {
  media: TMediaType;
  extraClass?: string;
  isAspectRatio?:boolean
  mode?: 'widthFix'| 'aspectFill'
  editMode?: boolean
}
export default ({media, extraClass, isAspectRatio=false, mode='aspectFill'}:Props) => {
  let styleObject = {};
  const [duration, setDuration] = useState(media.duration)
  // 如果存在宽高，则需要设置 aspectRatio 值和对应高度的百分比值
  if(isAspectRatio && media.width && media.height){
    styleObject = {aspectRatio: `${media.width} / ${media.height}`, height: `${media.width / media.height * 100}%`}
  }

  const mediaClassName = extraClass ?? style.media;
  
  const handleLoadedMetaData = (event: BaseEventOrig<VideoProps.onLoadedMetaDataEventDetail>) => {
    // 如果没有 duration 则从元数据中获取
    if(!duration){
      // todo: 用元数据重新设置宽，高比
      setDuration(event.detail.duration)
    }
  }
  
  if (media.fileType === "video") {

    return (
      <View className="relative w-full h-full">
        <Video
          showCenterPlayBtn={false}
          controls={false}
          object-fit="cover"
          src={media.url}
          style={styleObject}
          className={mediaClassName}
          onLoadedMetaData={handleLoadedMetaData}
        ></Video>
        {duration && (
          <View className={style.durationStatus}>
            <View className={style.playBtn}></View>
            <View>{formatSeconds(Math.round(duration))}</View>
          </View>
        )}
      </View>
    );
  }
  return (
    <Image
      mode={mode}
      src={media.url}
      className={mediaClassName}
      lazy-load
    ></Image>
  );
}