import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import styles from './Back.less';

function Back({ url }) {
  // 跳转之后清除历史记录
  const handleLink = () => {
    if (/\/create\/([0-9]+)$/.test(window.location.pathname)) {
      const from = JSON.parse(sessionStorage.getItem('linkFrom') || '[]');
      from.pop();
      sessionStorage.setItem('linkFrom', JSON.stringify(from));
    }
  };

  return <Link className={'icon iconfont icon-btn_arrowsleft ' + styles.back} to={url} onClick={handleLink} />;
}

const getBackUrl = ({ panelsById, screensById }) => {
  const panelUrlReg = /\/create\/([0-9]+)\/panel_([0-9]+)\/([0-9]+)$/;
  if (panelUrlReg.test(window.location.pathname)) {
    let topScreenId, panelId;
    window.location.pathname.replace(panelUrlReg, (_m, p1, p2) => {
      topScreenId = p1;
      panelId = p2;
      return _m;
    });
    try {
      const panel = panelsById[panelId];
      if (panel.screenId == topScreenId) {
        return `/create/${topScreenId}`;
      } else {
        const screen = screensById[panel.screenId];
        const newPanelId = screen.panelId;
        return `/create/${topScreenId}/panel_${newPanelId}/${panel.screenId}`;
      }
    } catch (error) {
      return getFromUrl();
    }
  } else {
    return getFromUrl();
  }
};

//处理是否来源于其他屏的跳转
const getFromUrl = () => {
  const from = JSON.parse(sessionStorage.getItem('linkFrom') || '[]');
  if (from.length > 0) {
    return from[from.length - 1];
  } else {
    return '/';
  }
};

const mapStateToProps = ({ panelsById, screensById }) => {
  return {
    url: getBackUrl({ panelsById, screensById })
  };
};

export default connect(mapStateToProps)(Back);
