/**
 * 页面跳转
 */
import React, { PropTypes } from 'react';
import { push } from 'react-router-redux';
import { autobind } from 'core-decorators';
import Qs from 'qs';
import { Button, Tooltip } from '../../index';
import { CONTAINER_PRE } from '../../../framework/entrance/routes';
import { showModal } from '../../../framework/pageContainer/ModalWrapper';
import { PFetch } from '../../../framework/system/fetch';
import { longRunExec } from '../../../framework/system/longRunOpt';
import { jumpToNewTab } from '../../../framework/utils/windowUtils';
import { convertTemplate, trimStart } from '../../../framework/utils/StringUtils';
import { dispatch } from '../../../framework/service/DispatchService';
import { BUTTON_INTERACTIVETYPE } from '../../../framework/constant/dictCodes';
import { getRecMenuId } from '../../../framework/service/SessionStorage';

const jump = (oldParams, actionLink, props, next, stopLoading, linkMappings) => {
  const actionLinkMappings = linkMappings || props.actionLinkMappings;
  let params = oldParams;
  if (props.beforeRouterChange) {
    params = props.beforeRouterChange(oldParams);
  }
  params.displayType = props.displayType;
  const templateType = props.templateType || props.domainType;
  const mode = props.interactiveType;
  // console.log('lalal opener', window.opener && window.opener._windowHandler);
  if (mode === BUTTON_INTERACTIVETYPE.PAGE) {
    const menuIds = getRecMenuId();
    jumpToNewTab(
      '/' + CONTAINER_PRE + convertTemplate(actionLink, params, actionLinkMappings) + '?p=' + btoa(Qs.stringify({ ...params, ...menuIds, domainType: templateType, s: '1', readonly: props.readonly })),
      props
    );
  } else if (mode === BUTTON_INTERACTIVETYPE.MODAL || mode === BUTTON_INTERACTIVETYPE.RIGHTDRAWER) {
    showModal({ ...params, s: '', modalTitle: props.buttonDescription, onRefresh: props.onRefresh, readonly: props.readonly }, templateType, convertTemplate(actionLink, params, actionLinkMappings), () => props.onRefresh && props.onRefresh());
  } else if (mode === BUTTON_INTERACTIVETYPE.PUSH_ELEMENT || (mode === BUTTON_INTERACTIVETYPE.REPLACE && !props.updateMain)) {
    dispatch(push({
      pathname: '/' + CONTAINER_PRE + convertTemplate(actionLink, params, actionLinkMappings),
      query: { p: btoa(Qs.stringify({ ...params, domainType: templateType })) }
    }));
  } else if (mode === BUTTON_INTERACTIVETYPE.REPLACE) {
    if (props.updateMain) {
      props.updateMain(actionLink, null, null, { ...params, domainType: templateType });
    }
  } else if (mode === BUTTON_INTERACTIVETYPE.REFRESH) {
    props.onRefresh && props.onRefresh(params);
  } else if (mode === BUTTON_INTERACTIVETYPE.CANCEL || mode === BUTTON_INTERACTIVETYPE.GOBACK) {
    window.close();
  }
  if (props.isModal && props.modalCallback) {
    props.modalCallback(); // fresh pre page
  }
  if (props.needCloseCurrentpage === 1) {
    window.close();
  }
  next();
};

export default {
  next: jump
};
