import React, { useEffect, useState } from 'react';
import { Modal } from '@easyv/antd';
import { CloseCircleFilled } from '@easyv/react-icons';
import styles from './index.less';
import { linkLogin } from 'utils/fetch';

// 下线通知
function EasyvOfflineNot() {
  const [modal, contextHolder] = Modal.useModal();
  const [response, setResponse] = useState<Response>();

  const showConfirm = () => {
    const onOk = () => {
      // onOk
      linkLogin();
    };
    modal.error({
      title: '下线通知',
      wrapClassName: styles.offlineNot,
      icon: <CloseCircleFilled aria-label="close-circle" className="anticon anticon-close-circle" />,
      content: '您的账号已在其他地方登录，为确保账号安全，请重新登录！',
      okText: '重新登录',
      onOk: onOk
    });
  };

  useEffect(() => {
    function offlineNotify(e: CustomEvent) {
      if (e.detail) {
        setResponse(e.detail);
        showConfirm();
      }
    }
    document.addEventListener('offlineNotify', offlineNotify);

    return () => {
      document.removeEventListener('offlineNotify', offlineNotify);
    };
  }, []);

  return <>{contextHolder}</>;
}

export default EasyvOfflineNot;
