import React, { useState } from "react";
import styles from "./index.module.scss";
import Lazyimg from "react-lazyimg-component";
import { baseURL } from "@/utils/http";
import imgErr from "@/assets/img/login/IMGerror.png";
import imgLoding from "@/assets/img/login/loading.gif";

type Props = {
  width?: number;
  height?: number;
  src: string;
};

function ImageLazy({ width = 100, height = 100, src }: Props) {
  // 图片地址
  const [srcLod, setSrcLod] = useState(imgLoding);
  // 是否第一次加载，如果不使用这个会加载两次
  const [isFlag, setIsFlag] = useState(false);
  /**
   * 图片加载完成
   */
  const handleOnLoad = () => {
    // 判断是否第一次加载
    if (isFlag) return;
    // 创建一个img标签
    const imgDom = new Image();
    imgDom.src = src;
    // 图片加载完成使用正常的图片
    imgDom.onload = function () {
      setIsFlag(true);
      setSrcLod(src);
    };
    // 图片加载失败使用图片占位符
    imgDom.onerror = function () {
      setIsFlag(true);
      setSrcLod(imgErr);
    };
  };

  return (
    <>
      <img
        style={{ width: width, height: height }}
        src={baseURL + srcLod}
        onLoad={handleOnLoad}
        alt=""
      />
    </>
  );
}

const MemoImageLazy = React.memo(ImageLazy);

export default MemoImageLazy;
