import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { isEqual, cache, logger } from '@zenview/micro-utils';
import { RenderRoute, RenderComponents } from './Render';
import './index.less';

class AppRoute extends React.Component {
  constructor() {
    super();
    //可能存在路由创建但是没有render 导致UI无法渲染
    this.isRender = false;
    this.state = { match: undefined, location: undefined, history: undefined };
  }
  shouldComponentUpdate(props, state) {
    if (!window._IS_RUN_MICRO_BASIC || !this.isRender) {
      return true;
    }
    const currentId = cache.getCache('currentTabKey', 'session');
    return currentId === props.tabId && props.location.pathname === state.location?.pathname;
  }
  componentWillUnmount() {
    logger.debug('路由销毁');
  }
  setRouteProps = (newMatch, newLocation, history) => {
    if (!isEqual(this.props.match, newMatch)) {
      this.setState({ match: newMatch, location: newLocation, history });
    }
  };
  renderRoute = (params) => {
    return <RenderRoute {...params} setRouteProps={this.setRouteProps} />;
  };
  renderComponent = () => {
    this.isRender = true;
    return <RenderComponents state={this.state} props={this.props} />;
  };

  render() {
    const { match, location } = this.state;
    const { path, routes, exact, sensitive, strict, children } = this.props;
    const isRouteMath = match && location;
    return (
      <>
        <Switch>
          {routes ? (
            routes.map((item) => <Route exact={!!item.exact} sensitive={!!item.sensitive} strict={!!item.strict} key={item.path} path={item.path} component={this.renderRoute} />)
          ) : (
            <Route exact={!!exact} strict={!!strict} sensitive={!!sensitive} path={path} component={this.renderRoute} />
          )}
          {children}
        </Switch>
        {isRouteMath && this.renderComponent()}
      </>
    );
  }
}

export default AppRoute;
