import React, { useState, useEffect, useMemo, useRef } from 'react';
import './index.less';

function ImageCard({ src, defaultSrc='/micro-apps/micro-dep-librarys/images/error/imageError.png', alt, onError, className = '', ...props }) {
  const [isError, setErrorStatus] = useState(!src);
  const imgKey = useRef(Math.random());

  const imgSrc = useMemo(() => (isError || !src ? defaultSrc : src), [defaultSrc, isError, src]);

  useEffect(() => {
    imgKey.current = Math.random();
    setErrorStatus(null);
  }, [src]);

  function onImageError(e) {
    setErrorStatus(true);
    onError && onError(e);
  }
  return <img {...props} className={`lm-t-c-image-card ${className}`} key={imgKey.current} data-src={src} src={imgSrc} alt={alt} onError={onImageError} lazzy="true" />;
}

export default React.memo(ImageCard);
