import { View, Image } from "@tarojs/components";
import "./index.less";
import img from "@/assets/icon/icon9.png";
import Taro from "@tarojs/taro";
import { useState } from "react";
import { Flex } from "@taroify/core";
import { Clear } from "@taroify/icons";
import api from "@/services/core/api";
import { composeImgUrl } from "@/utils";
interface PropsTypes {
  maxLength?: number;
  onChange?: (value: string[]) => void;
}
export default function (props: PropsTypes) {
  const { maxLength = 3, onChange } = props;
  const [filepaths, setFilePaths] = useState<string[]>([]);
  console.log(filepaths);
  const uploadImg = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        Taro.uploadFile({
          url: api.uploadUrl,
          name: "file",
          filePath: res.tempFiles[0].path,
          success: (res) => {
            const resData = JSON.parse(res.data);
            if (resData.code === 200) {
              setFilePaths([...filepaths, resData.data]);
              onChange && onChange([...filepaths, resData.data]);
            }
          },
        });
      },
    });
  };

  /** 删除图片列表 */
  const deleteImg = (index: number) => {
    setFilePaths(filepaths.filter((_, i) => i !== index));
    onChange && onChange(filepaths.filter((_, i) => i !== index));
  };
  return (
    <Flex gutter={16}>
      {filepaths.map((v, i) => {
        return (
          <Flex.Item span={8}>
            <View className="uploadCard">
              <Image
                mode="aspectFill"
                src={composeImgUrl(v)}
                className="uploaded_img"
              ></Image>
              <View className="uploadCard_closeBtn" onTap={() => deleteImg(i)}>
                <Clear color="#fff" />
              </View>
            </View>
          </Flex.Item>
        );
      })}
      {filepaths.length < maxLength && (
        <Flex.Item span={8}>
          <View className="uploadCard" onTap={uploadImg}>
            <Image src={img} className="uploadCard_img" />
          </View>
        </Flex.Item>
      )}
    </Flex>
  );
}
