import { message } from 'antd';
import moment from 'moment';

/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */
export default function access(initialState: {
  userInfo: { token: ''; roles: []; name: ''; userName: '' };
  expires: 0;
}) {
  checkIsTokenExpires();
  return initialState.userInfo ?? {};
}

export function checkIsTokenExpires() {
  const expires = parseInt(localStorage.getItem('expires') || '0');
  const now = moment().unix();
  const user = localStorage.getItem('user');
  if (expires - now <= 0) {
    localStorage.removeItem('user');
    if (user) {
      message.error('会话已过期，请重新登录');
      window.location.href = '/chat';
      return true;
    }
  }
  return false;
}
