import React, { useEffect, useState } from 'react';
import { View, Image } from '@tarojs/components';
import className from 'classnames';
const success = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/toast/icon-success.png';
const fail = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/toast/icon-fail.png';

interface IToastProps {
  /** 是否展示 */
  isOpen?: boolean;
  /** 显示的消息的内容 */
  content?: JSX.Element | string;
  /** 是否模态 */
  modal?: boolean;
  /** 消失时间 */
  time?: number;
  /** 提示图 */
  icon?: 'success' | 'fail' | string;
  /** tip消失后的callback */
  onTipDisappear?: () => void;
}

/**
 * 轻提示组件
 */
const Toast: React.FC<IToastProps> = ({
  isOpen = false,
  modal = false,
  time = 2000,
  content = '',
  icon = '',
  onTipDisappear = () => {},
}) => {
  const [visible, setVisible] = useState<boolean>(isOpen);

  /* eslint-disable */
  useEffect(() => {
    setVisible(isOpen);
    // isOpening手动关闭
    visible && !isOpen && onTipDisappear();
  }, [isOpen]);

  useEffect(() => {
    // 自动关闭
    visible &&
      !!time &&
      setTimeout(() => {
        setVisible(false);
        onTipDisappear();
      }, time);
  }, [visible]);
  /* eslint-enable */

  const containerBox = className(['wm-toast', modal && 'wm-toast-modal']);
  const container = className([
    'container',
    !!icon
      ? icon === 'success' || icon === 'fail'
        ? 'icon-container'
        : 'icon-common'
      : null,
  ]);

  const renderIcon = () => {
    if (!icon) return null;
    let url: string;
    if (icon === 'success') {
      url = success;
    } else if (icon === 'fail') {
      url = fail;
    } else {
      url = icon;
    }
    return (
      <View className='icon-box'>
        <Image className='icon' src={url} />
      </View>
    );
  };

  return visible ? (
    <View className={containerBox}>
      <View className={container}>
        {renderIcon()}
        {!!content && content}
      </View>
    </View>
  ) : null;
};

export default Toast;
