import axios from 'axios';
import SocketIO from '../utils/socketio';
import Restart from './Restart';

window.restart = Restart.restartApp;

export async function counterInterval(dispatch, expiresIn, reload) {
  window.socket =
    window.socket ||
    new SocketIO(axios.defaults.baseURL, {
      query: `token=${window.auth.token}`,
      single: true,
    });
  window.socket.connect();
  // window.socket =
  //   window.socket ||
  //   io(axios.defaults.baseURL, {
  //     query: {token: window.auth.token},
  //   });
  window.authInterval = window.setInterval(() => {
    dispatch({type: 'admin/auth'});
  }, 8 * 60 * 60 * 1000); // 每8小时更新一次
  window.socketInterval = window.setInterval(() => {
    if (window.auth && window.socket.disconnected) {
      // 已授权，并且处于掉线状态
      if (!window.socketDisconnected) {
        window.socketDisconnected = true;
      } else {
        // 连续掉线超时，重启应用
        Restart.restartApp();
      }
    }
  }, window.retryTimeout); // 每半分钟检查socket连接
  if (reload) {
    Restart.restartApp();
  }
}
