import { CURRENT } from './renderAuthorize';

const checkPermissions = (
  authority,
  flatMenu,
  currentAuthority,
  target,
  Exception,
) => {
  const client = (window.globalConfig && window.globalConfig.client) || 'city';
  const filterPath = [
    { name: '/', path: '/' },
    { name: '/', path: `/?client=${client}` },
    {
      name: 'civbase',
      path: `/civbase/?client=${client}`,
    },
    { name: 'industry', path: '/industry' },
    { name: 'openapi', path: '/openapi' },
    { name: 'civweb4', path: `/civweb4/` },
    {
      name: 'civweb4',
      path: `/civweb4/?client=${client}`,
    },
    { name: '404', path: '/404' },
    { name: '403', path: '/403' },
    { name: '500', path: '/500' },
  ];

  if (!authority) {
    return target;
  }
  if (Array.isArray(flatMenu)) {
    const data = flatMenu.concat(filterPath);
    if (/web_console/.test(authority.path)) {
      return {
        target,
        validate: true,
      };
    }
    const findIndex = data.findIndex(item => item.path === authority.path);
    if (findIndex > -1) {
      return {
        target,
        validate: true,
      };
    }

    return {
      target: Exception,
      validate: false,
    };
  }
  throw new Error('unsupported parameters');
};

function check(authority, flatMenu, target, Exception) {
  return checkPermissions(authority, flatMenu, CURRENT, target, Exception);
}

export default check;