import React,{useEffect} from 'react';
import ReactDOM from 'react-dom';
import styles from './index.less';
import Popup from '@/components/Popup/index.jsx';

const toastList=[];
const runNext=()=>{
  let props = toastList[0];
  if(props){
    const {message,delay,resolve,position}=props;
    let popup = Popup(resolve,{cantouch:true});
    ReactDOM.render(
      <Toast destory={popup.destory} message={message} delay={delay} position={position}/>,
      popup.dom
    );
  }
}

const Toast=props=>{
  const {
    message,
    delay=1000*2,
    destory,
    position='top'
  }=props;
  useEffect(()=>{
    setTimeout(()=>{
      destory();
      toastList.shift();
      runNext();
    },delay);
  },[])
  const ANITYPE={
    'center':'animate__slideInDown',
    'top':'animate__slideInDown',
    'bottom':'animate__slideInUp'
  }
  return (
    <section className={styles.wrap} data-position={position}>
      <div className={styles.content+ ` ${ANITYPE[position]} animate__animated animate__fast`} dangerouslySetInnerHTML={{ __html:message }}>
      </div>
    </section>
  )
}


const ShowToast=props=>{
  if(typeof props === 'string'){
    props = {message:props}
  }
  return new Promise((resolve) => {
    props.resolve = resolve;
    toastList.push(props);
    if(toastList.length===1){
      runNext();
    }
  });
}

export default ShowToast;