import { View } from "@tarojs/components";
import MediaItem from "@/components/media-item/index";
import style from "./index.module.less";
import IconDeleteGray16 from "@/components/icon/IconDeleteGray16";
import IconPlusGray16 from "@/components/icon/IconPlusGray16";
import type { TMediaType } from "@/types/index";
import Taro from "@tarojs/taro";


export interface IndexProps {
  list: TMediaType[];
  onNewUpload: ()=>  void;
  onChange?: (list: TMediaType[]) => void;
  onDelete?: (index:number, item: TMediaType) => void;
}

const Index = ({onNewUpload, list, onChange, onDelete }: IndexProps) => {
  
  // 预览媒体
  const handlePreview = (e: any, index: number, item: TMediaType) => {
    e.stopPropagation();
    Taro.previewMedia({
      current: index,
      //@ts-ignore
      sources: list.map((item) => {
        return {
          url: item.url,
          type: item.fileType,
        }
      }),
    })
  };
  
  return (
    <View className="grid grid-cols-3 gap-x-8 gap-y-12 justify-center">
      <View className="flex">
        <View className={style.addImageBtn} onClick={onNewUpload}>
          <IconPlusGray16 />
        </View>
      </View>
      {list.map((item, index) => {
        return (
          <View className="flex" onClick={(e) => handlePreview(e, index, item)}>
            <View className={style.imageItem}>
              <MediaItem media={item}></MediaItem>
              <View className={style.deleteButton} onClick={(e:any)=> {
                e.stopPropagation();
                onDelete && onDelete(index, item)
              }}>
                <IconDeleteGray16 />
              </View>
            </View>
          </View>
        );
      })}
    </View>
  );
};

export default Index;
