import React, { 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/login/loading.gif";
import imgErr from "@/assets/img/login/IMGerror.png";
import classNames from "classnames";
import { EyeOutlined } from "@ant-design/icons";
import { Image } from "antd";

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

function ImageLazy({ width = 100, height = 100, src, noLook }: Props) {
  const [defaultUrl, setDefaultUrl] = useState(src?imgLoding:imgErr);
  const [defaultShow, setDefaultShow] = useState(true);

  const onLoad = (val: any) => {
    let flag = false;
    // console.log(val);
    val.target.onload = function () {
      setDefaultShow(false);
      flag = true;
    };
    // 5秒后图片还没有加载出来为错误
    window.setTimeout(() => {
      if (!flag) setDefaultUrl(imgErr);
    }, 5000);
  };

  // 点击预览图片
  const [visible, setVisible] = useState(false);

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

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

      <img
        className={classNames("showImg", defaultShow ? "active" : "")}
        src={defaultUrl}
        alt=""
      />

      {/* 预览图片 */}
      <Image
        style={{ display: "none" }}
        preview={{
          visible,
          src: baseURL + src,
          onVisibleChange: (value) => {
            setVisible(value);
          },
        }}
      />
    </div>
  );
}

const MemoImageLazy = React.memo(ImageLazy);

export default MemoImageLazy;
