import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import Lazyimg from "react-lazyimg-component";
import { baseURL } from "@/utils/http";
import imgLoding from "@/assets/img/loading.gif";
import imgErr from "@/assets/img/IMGerror.png";
import { EyeOutlined } from "@ant-design/icons";
import { useDispatch } from "react-redux";

type Props = {
  width?: number | string;
  height?: number;
  src: string;
  noLook?: boolean;
  offline?: boolean;
};

function ImageLazy({
  width = 100,
  height = 100,
  src,
  noLook,
  offline = false,
}: Props) {
  const dispatch = useDispatch();

  // 图片占位符
  const [placeholderUrl, setPlaceholderUrl] = useState(
    src ? imgLoding : imgErr
  );

  // 默认不能预览图片，加载成功之后能预览
  const [lookImg, setLookImg] = useState(false);

  useEffect(() => {
    if (src) {
      // 进页面查看图片的加载情况
      // 创建一个img标签
      const imgDom = document.createElement("img");
      imgDom.src = offline ? src : baseURL + src;

      // 不管图片加载成功或者失败，都删除掉，提高性能
      // 图片加载成功
      imgDom.onload = function () {
        setLookImg(true);
        imgDom.remove();
      };
      // 图片加载失败
      imgDom.onerror = function () {
        setPlaceholderUrl(imgErr);
        imgDom.remove();
      };

      return () => {
        // 离开页面也删掉掉元素
        imgDom.remove();
      };
    }
  }, [offline, src]);

  // 点击预览图片
  const lookBigImg = useCallback(() => {
    dispatch({
      type: "login/lookBigImg",
      payload: { url: offline ? src : baseURL + src, show: true },
    });
  }, [dispatch, offline, src]);

  return (
    <div className={styles.ImageLazy} style={{ width: width, height: height }}>
      <div className="lazyBox">
        <Lazyimg
          src={src ? (offline ? src : baseURL + src) : ""}
          width={width}
          height={height}
          placeholder={placeholderUrl}
          alt=""
        />

        {/* 图片预览 */}
        {noLook || !lookImg ? null : (
          <div className="lookImg" onClick={lookBigImg}>
            <EyeOutlined />
            &nbsp;
            <div>预览</div>
          </div>
        )}
      </div>
    </div>
  );
}

const MemoImageLazy = React.memo(ImageLazy);

export default MemoImageLazy;
