import * as React from 'react';
import * as PropTypes from 'prop-types';
import { TcbImage } from '../form/uploader/uploaderPc';
import classNames from '../../utils/classnames';
import './index.css';

const CLASS_PREFIX = 'g-uploader-view';

/**
 * 图片上传-展示组件
 */
export default function UploaderView({
  srcList, // 兼容 cloud:和https: 协议，兼容 字符串和字符串数组
  alt = '[加载失败]',
  gutter = 8,
  height = 100,
  width = 100,
  events = {},
  isZoom = true,
  isEmptyPlace = true,
  className,
  id,
  style
}) {
  const cls = classNames({
    [CLASS_PREFIX]: true,
    [className]: className,
  });

  // 成功事件，返回加载成功的链接
  const [successList, setSuccessList] = React.useState([]);
  // 失败事件，返回加载失败的链接
  const [errorList, setErrorList] = React.useState([]);

  React.useEffect(() => {
    events.load && events.load({ success: successList, error: errorList });
  }, [successList, errorList]);

  const boxStyle = {
    marginRight: gutter,
    marginBottom: gutter,
    height: height,
    width: width,
  };

  const values = []
    .concat(srcList)
    .filter((d) => typeof d === 'string' && d !== '');

  return (
    <div className={cls} id={id} style={style}>
      <div className={`${CLASS_PREFIX}__image-list`}>
        {values.map((d, i) => {
          const imgProps = {
            fileID: d,
            className: `${CLASS_PREFIX}__image`,
            alt: alt,
            isZoom,
            onLoad: () => setSuccessList((list) => [...list, d]),
            onError: () => setErrorList((list) => [...list, d]),
          };
          return (
            <div
              className={`${CLASS_PREFIX}__image-box`}
              key={`${d}-${i}`}
              style={boxStyle}
              title={d}
            >
              <TcbImage {...imgProps} />
            </div>
          );
        })}
        {values.length === 0 && isEmptyPlace && (
          <div className={`${CLASS_PREFIX}__image-box`} style={boxStyle}>
            <img className={`${CLASS_PREFIX}__image`} alt="暂无图片" />
          </div>
        )}
      </div>
    </div>
  );
}

UploaderView.propTypes = {
  srcList: PropTypes.oneOfType([PropTypes.array, PropTypes.string]), // 图片 src 列表
  alt: PropTypes.string, // 替代文字
  isZoom: PropTypes.bool, // 能否点击放大
  gutter: PropTypes.number, // 图片间距
  height: PropTypes.number, // 图片最大高度
  width: PropTypes.number, // 图片最大宽度
  isEmptyPlace: PropTypes.bool, // 是否展示空值
  events: PropTypes.objectOf(PropTypes.func), // 组件事件
  className: PropTypes.string, // 类，修改测试story,测试2
  id: PropTypes.string,
  style: PropTypes.object
};
