/**
 * Created by baoyinghai on 12/30/16.
 */
const _windowHandler = {};
window._windowHandler = _windowHandler;

const originalOnunload = window.onunload;

window.onunload = () => {
  window.___windowCallback && window.___windowCallback();
  originalOnunload && originalOnunload();
};

const pushWindowHandler = (key, value) => {
  _windowHandler[key] = value;
};

const getWindowHandler = key => {
  return _windowHandler[key] || {};
};

const deleteWindowHandler = key => {
  delete _windowHandler[key];
};

export const jumpToNewTab = (url, props) => {
  // TODO: 同一个按钮 参数一样的  map 优化  刷新就会丢失
  const winKey = props.buttonCode + url;
  const { openerHandle } = getWindowHandler(winKey);
  if (openerHandle) {
    // 已经打开的页面 在这里关闭掉它
    openerHandle.___windowCallback = null;
    openerHandle.close();
  }
  const newOpenHandle = window.open(url);
  if (newOpenHandle) {
    newOpenHandle.___windowCallback = (...p) => {
      deleteWindowHandler(winKey);
      if (props.needFreshPrePage === 0) return;
      // props.onRefresh(...p);
      if (props.refreshCallback) {
        props.refreshCallback();
      } else {
        location.reload();  // 舍弃
      }
    };
  }
  pushWindowHandler(winKey, { openerHandle: newOpenHandle });
};
