import React, { useEffect } from 'react';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import throttle from 'lodash/throttle';

const clearSession = () => {
  sessionStorage.removeItem('lastClickTime');
};

function EasyvRefresh() {
  const warningModalRef = useConfirmRef();

  useEffect(() => {
    clearSession();
    const clickChange = throttle(
      () => {
        const lastClickTime = sessionStorage.getItem('lastClickTime');
        const { REFRESH_TIME } = window.appConfig;
        if (lastClickTime) {
          if (Date.now() - REFRESH_TIME > parseInt(lastClickTime)) {
            warningModalRef.current?.show();
          }
        }
        sessionStorage.setItem('lastClickTime', Date.now() + '');
      },
      5000,
      {
        leading: true,
        trailing: false
      }
    );
    window.appConfig.REFRESH_TIME && document.getElementById('easyv-app')?.addEventListener('mousemove', clickChange);

    return () => {
      document.getElementById('easyv-app')?.removeEventListener('mousemove', clickChange);
      clearSession();
    };
  }, []);

  return (
    <EasyvModal.Confirm
      title="刷新提醒"
      iconType="warning"
      okText="刷新"
      onOk={() => {
        clearSession();
        window.location.reload();
      }}
      onCancel={() => {
        clearSession();
        warningModalRef.current?.close();
      }}
      onOkBtnType="primary"
      content="当前页面长时间无操作行为，是否刷新？"
      ref={warningModalRef}
    />
  );
}

export default EasyvRefresh;
