import React, { useState, useEffect } from 'react';
import { YIconProps } from './icon.interface';
// import * as Icons from '@ant-design/icons';
import { createFromIconfontCN } from '@ant-design/icons';
import { IconImageStyled } from './styles';

const YwCloudIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_2333532_pgh4pfp7w8s.js',
});

interface Icon {
  [key: string]: any;
}

// const icons = Icons as Icon;
export const YIcon: React.FC<YIconProps> = ({
  name,
  type,
  size,
  width,
  height,
  color,
  style,
}) => {
  // type: primary/error/warning/success/default/black/white

  const reducefontSize = (size: YIconProps['size']) => {
    let fontSize = '16px';
    if (size) {
      if (typeof size === 'number') {
        fontSize = `${size || 16}px`;
      } else {
        fontSize = size;
      }
    }
    return fontSize;
  };

  const reduceSize = (width?: number, height?: number) => {
    return {
      width: width ? `${width}px` : 'auto',
      height: height ? `${height}px` : 'auto',
    };
  };

  const reduceSizeAndWidthAndHeight = (
    width?: number,
    height?: number,
    size?: YIconProps['size'],
  ) => {
    if ((width || height) && !size) {
      const newSize = reduceSize(width, height);
      return {
        width: newSize.width,
        height: newSize.height,
        fontSize: newSize.height,
      };
    } else {
      const fontSize = reducefontSize(size);
      return {
        width: width ? width : fontSize,
        height: height ? height : fontSize,
        fontSize,
      };
    }
  };

  const renderIcon = (name: string) => {
    const fontSize = reducefontSize(size);
    // const Icon = icons[name];
    let iName: string = name || '';
    if (iName !== '' && iName.indexOf('ywcloud') < 0) {
      const Icon = require(`@ant-design/icons/${name}.js`).default;
      return (
        <Icon style={{ fontSize, ...style }} className={`${type}-color`} />
      );
    }
  };

  if (!name) {
    return null;
  }
  /* ywcloud Iconfont 图标 */
  if (name.indexOf('ywcloud') >= 0) {
    const newSize = reduceSizeAndWidthAndHeight(width, height, size);
    const newStyle = {
      color,
      ...newSize,
      ...style,
    };
    return <YwCloudIcon type={name} style={newStyle} />;
  } else if (name.indexOf('http') >= 0) {
    /* 自定义图片图标 */
    const fontSize = reduceSize(width, height);
    return (
      <IconImageStyled
        src={name}
        width={fontSize.width}
        height={fontSize.height}
        style={style || {}}
      />
    );
  } else {
    return <span style={style || {}}>{renderIcon(name)}</span>;
  }
};
