import React from "react";
import Taro from "@tarojs/taro";
import { View, Image, Video } from "@tarojs/components";
import { Loading } from "@antmjs/vantui";
import { uploadFileBase64, uploadFiles } from "@/utils/request";
import { promise } from "@/utils/promise";
import icon from "@/assets/icons/uploader.png";
import closeIcon from "@/assets/icons/close.png";
import style from "./style.modules.less";

export default (props) => {
  // value 为数组
  // 单个元素结构为 { url, fileType }
  const { value, disabled = false, onChange } = props;
  const [loading, setLoading] = React.useState(false);
  const [valueCopy, setValueCopy] = React.useState(value);
  const valueCopyRef = React.useRef(valueCopy);
  valueCopyRef.current = valueCopy;

  const onAdd = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (disabled) return;

    setValueCopy(valueCopyRef.current.concat(false));
    
    setLoading(true);

    // eslint-disable-next-line no-undef
    if (IS_APP_CLIENT) {
      const p = promise((resolve, reject) => {
        // eslint-disable-next-line no-undef
        SmartCity.chooseImage({
          count : 1 // 图片张数
        },function(res){
            console.log("--------上传图片---------", res);
            const base64 = res[0].imageData;
            const fileName = res[0].name;
            const fileType = res[0].type;
    
            uploadFileBase64(base64, fileName, fileType).then(resp => {
              resolve(resp);
              // onChange((value || []).concat(resp));
            }).catch((err) => {
              console.error(err);
              reject(err);
            });
        });
      }, 10 * 1000);

      p.then((resp) => {
        setLoading(false);
        onChange((value || []).concat(resp));
      }).catch(() => {
        setValueCopy(valueCopyRef.current.filter(Boolean))
        setLoading(false);
      });
    } else {
      Taro.chooseMedia({
        maxDuration: 60,
        // sizeType: "compressed",
        success: (res) => {
          const { tempFiles } = res;
          uploadFiles(tempFiles)
            .then((resp) => {
              setLoading(false);
              onChange((value || []).concat(resp));
            })
            .catch((err) => {
              console.error(err);
              setLoading(false);
            });
        },
        fail: (err) => {
          console.error(err);
          setLoading(false);
        },
      });
    }
  };

  const onDelete = (item) => {
    if (!item) {
      setValueCopy(valueCopyRef.current.filter(Boolean));
      return;
    }

    const newVal = value.filter((x) => x.url != item.url);
    onChange(newVal);
  };

  const onPreview = (inx) => {
    const url = value.map((x) => x.url);
    // Taro.previewMedia({
    //   sources: value.map(x => ({ url: x.url, type: x.fileType })),
    //   current: inx,
    // })

    //H5
    Taro.previewImage({
      current: inx, // 当前显示图片的http链接
      urls: url,
    });
  };

  React.useEffect(() => {
    setValueCopy(value || []);
  }, [value]);

  return (
    <View className={style["uploader-wrapper"]}>
      <View className={style["uploader-box"]}>
        {!disabled && (
          <View className={style["uploader-add"]}>
            <Image src={icon} onClick={onAdd} />
          </View>
        )}
        {valueCopy.map((item, inx) => (
          <View key={item?.url || '123'} className={style["uploader-item"]}>
            {
              !item ? (
                <Loading color="gray" style={{ width: '100%', height: '100%' }} />
              ) : (
                item.fileType.indexOf("image") == 0 ? (
                  <Image src={item.url} onClick={() => onPreview(inx)} />
                ) : (
                  <Video
                    src={item.url}
                    controls={false}
                    onClick={() => onPreview(inx)}
                  />
                )
              )
            }
            {!disabled && (
              <View onClick={() => onDelete(item)} style={{ zIndex: 99 }}>
                <Image src={closeIcon} />
              </View>
            )}
          </View>
        ))}
      </View>
    </View>
  );
};