/**
 * @author wanfeng
 * @time 2021,7,13
 * @description EasyV路由权限处理
 */
import React, { FC, Fragment, useEffect, useState } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { useHistory } from 'react-router';
import { RootState } from 'models';
import message from 'components/message';
import { useProductionInfo } from 'components/easyUse';
import { EditionType } from 'models/constant.types';

type IProps = ConnectedProps<typeof connector>;

const RouterAuthority: FC<IProps> = ({ userType, userInfo, children }) => {
  const history = useHistory();
  const [display, setDisplay] = useState(false);
  const { location } = history;
  const productionInfo = useProductionInfo();
  const { isAdmin, isLocal, isRoot } = productionInfo;
  useEffect(() => {
    if (location.pathname === '/users' && userInfo.type === 'education') {
      return;
    }

    if (isLocal) {
      setDisplay(true);
      return;
    }
    if (isAdmin === undefined) {
      return;
    }
    if (location.pathname === '/space' && isAdmin === false) {
      message.error('您无权进入管理空间!');
      history.replace('/');
    } else if (location.pathname === '/app' && userType === 'saas_basic') {
      message.error('您无权进入终端交互!');
      history.replace('/');
    } else if (location.pathname === '/constants' && userType !== 'saas_vip') {
      message.error('您无权进入组件开发!');
      history.replace('/');
    } else if (location.pathname === '/qianyi' && !isRoot) {
      message.error('您无权进入平台迁移!');
      history.replace('/');
    } else {
      setDisplay(true);
    }
    // TODO 基础版用户无权进入驾驶舱[需要在对应项目页写拦截]
    // TODO 没有用户管理权限的子用户和协作用户不允许进入用户管理页面[需要在对应项目页写拦截]
  }, [history.location.pathname, userType, isAdmin, userInfo]);
  return display ? <Fragment>{children}</Fragment> : null;
};

const mapStateToProps = ({ user }: RootState) => {
  const { userInfo } = user;
  return {
    userInfo,
    userType: window.appConfig.LOCAL ? null : (userInfo.edition?.id as EditionType),
  };
};

const connector = connect(mapStateToProps);

export default connector(RouterAuthority);
