import * as React from 'react';
import { useState, useEffect } from 'react';
import * as PropTypes from 'prop-types';

import classNames from '../../utils/classnames';
import './index.css';
import { ImageInner } from './image';

export default function Image({
  // 系统属性
  className,
  events = {},
  style,
  // 组件属性
  src,
  alt,
  mode,
  lazyLoad,
  imgPreview,
  maskClosable,
  fit,
}) {
  const [isError, setIsError] = useState(false);
  const cls = classNames({
    'weda-ui': true,
    'weda-image': true,
    'weda-image-error': isError,
    [className]: className,
  });
  const objectFit = fit || getObjectFitByWxImageMode(mode);
  const [realSrc, setRealSrc] = useState(
    /^cloud:\/\//.test(src) ? undefined : src
  );

  useEffect(() => {
    if (/^cloud:\/\//.test(src)) {
      window.app.cloud
        .getTempFileURL(src)
        .then((res) => {
          setRealSrc(res || '');
        })
        .catch(() => {
          setRealSrc('');
        });
    } else {
      setRealSrc(src);
    }
  }, [src]);

  return src === realSrc || (realSrc !== undefined && src !== realSrc) ? (
    <ImageInner
      objectFit={objectFit}
      style={style}
      className={cls}
      alt={alt}
      src={realSrc}
      setIsError={setIsError}
      events={events}
      lazyLoad={lazyLoad}
      imgPreview={imgPreview}
      maskClosable={maskClosable}
    />
  ) : null;
}

function getObjectFitByWxImageMode(mode) {
  const array = [
    {
      mode: 'scaleToFill',
      h5: 'fill',
    },
    {
      mode: 'aspectFit',
      h5: 'contain',
    },
    {
      mode: 'aspectFill',
      h5: 'cover',
    },
    {
      mode: 'widthFix',
      h5: 'cover',
    },
    {
      mode: 'heightFix',
      h5: 'contain',
    },
  ];
  const item = array.find((item) => item.mode === mode);
  return item?.h5;
}
