import { View, Image, Video } from "@tarojs/components";
import style from "./index.module.less";
import Taro from "@tarojs/taro";
import MediaItem from "@/components/media-item/index";
import type { TMediaType } from "@/types/index";
interface Props {
  mediaList: TMediaType[];
  layout: string;
  editMode?: boolean
}

const Index: React.FC<Props> = ({ layout, mediaList, editMode=false }) => {
  
  // 预览媒体
  const handlePreview = (e: any, index: number, item: TMediaType) => {
    if(editMode){
      return;
    }
    e.stopPropagation();
    Taro.previewMedia({
      current: index,
      //@ts-ignore
      sources: mediaList.map((item) => {
        return {
          url: item.url,
          type: item.fileType,
        }
      }),
    })
  };

  const renderEmpty = ()=> {
    return <View className={editMode ? 'px-16': ''}><View className="component-card-empty">
      <View className="component-card-content">
        <View className="component-card-empty-figure"></View>
        <View className="component-card-empty-tips">点击配置图片/视频</View>
      </View>
    </View>
    </View>
  }

  // 渲染媒体列表
  const renderList = () => {
    if(mediaList.length === 0){
      return renderEmpty()
    }
    // 单个媒体大尺寸显示
    if (mediaList.length === 1) {
      const item = mediaList[0];
      return (
        <View className={editMode ? "px-16": ''}>
          <View
            className={editMode ? style.figureSingle: style.figureSingleLarge}
            onClick={(e) => handlePreview(e, 0, item)}
          >
            <MediaItem mode="widthFix" media={item} extraClass={style.singleMedia} isAspectRatio></MediaItem> 
          </View>
        </View>
      );
    }
    // 竖向平铺
    if (layout === "full") {
      return (
        <View className="flex flex-col gap-8 items-center">
          {mediaList.map((item, index) => {
            return (
              <View
                className={editMode ? style.figureItemFull : style.figureItemFullLarge }
                key={index}
                onClick={(e) => handlePreview(e, index, item)}
              >
                <MediaItem  isAspectRatio mode="widthFix" media={item} extraClass={editMode ? style.mediaFull: style.mediaFullLarge}></MediaItem>
                
              </View>
            );
          })}
        </View>
      );
    }
    // 横向一行 3 个展示
    return (
      <View className="flex justify-center">
        <View className="grid grid-cols-3 gap-x-8 gap-y-12 justify-center">
          {mediaList.map((item, index) => {
            return (
              <View
                className={editMode ? style.figureItem : style.figureItemLarge }
                key={index}
                onClick={(e) => handlePreview(e, index, item)}
              >
                <MediaItem media={item}></MediaItem>
              </View>
            );
          })}
        </View>
      </View>
    );
  };

  return <View className={`w-full`}>{renderList()}</View>;
};

export default Index;
