import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";

import IconDeleteGray16 from "@/components/icon/IconDeleteGray16";

import style from "./index.module.less";
import { uploadImage } from "@/utils/http";

interface IProps {
  url?: string
  setUrl: (url: string)=> void
}
export default function Index({url, setUrl}:IProps) {

  const handleAddPoster = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      async success(chooseImageRes) {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        const res = await uploadImage(tempFilePaths[0]);
        if (res?.publicUrl) {
          setUrl(res.publicUrl);
        }
      },
    });
  };


  const onDelete = () => {
    setUrl('')
  }


  // 渲染封面
  const renderPoster = (src?: string) => {
    if (src) {
      return (
        <View className="w-full overflow-hidden relative">
          <View className={style.deleteButton} onClick={(e:any)=> {
                e.stopPropagation();
                onDelete()
              }}>
                <IconDeleteGray16 />
              </View>
          <Image className={style.cover} mode="widthFix" src={src}></Image>
        </View>
      );
    }
    return (
      <>
        <View>
          <Image
            src="https://cdn.wehome.cn/cmn/png/100/META-H8UKVHWU-KIGP3BIL7M5AYC6XHNUA2-VDZCWI2M-O91.png"
            className={style.iconAdd}
          ></Image>
        </View>
        <View className="text-gray-4 text-12 leading-20 text-center">
          上传展示图
        </View>
      </>
    );
  };




  return ( <View className="flex flex-col gap-6 w-full">
    <View className="flex w-full items-center">
      <View className="flex-1">
        封面图
      </View>
    </View>
    <View
      className={`${style.coverContainer}`}
      onClick={handleAddPoster}
    >
      {renderPoster(url)}
    </View>
  </View>
  );
}
