import { NavItemType, SpaceShipState } from 'models/spaceship.types';
import { deepFindOne } from './utils';

export const pathNameIsSharedPortal: (pathname?: string) => boolean = (
  pathname = window.location.pathname,
) => {
  return /\/sharedPortal\//i.test(pathname);
};

export const getPortalId: (pathname?: string) => number = (pathname = window.location.pathname) => {
  const pathnameArr = pathname.split('/').filter((d) => d);
  let portalId = pathnameArr[pathnameArr.length - 1];
  // 如果是门户分享路由则解析路由并返回门户ID
  if (pathNameIsSharedPortal(pathname)) {
    const portalIdObj = JSON.parse(window.atob(portalId));
    portalId = portalIdObj.portalId;
    return +portalId;
  }
  return +portalId;
};

// 这里获取
export const getSharedPortalId: (pathname?: string) => number | null = (
  pathname = window.location.pathname,
) => {
  // 如果是门户分享路由则解析路由并返回门户ID
  if (pathNameIsSharedPortal(pathname)) {
    return getPortalId();
  }
  return null;
};

export const pathnameIsSpaceShip: (pathname?: string) => boolean = (
  pathname = window.location.pathname,
) => {
  return /\/sharedPortal\/|\/spaceShipEdit\/|\/spaceShipPreview\//i.test(pathname);
};

/**
 *
 * @returns id门户id， 驾驶舱预览时从路由的哈希里读取当前菜单打开方式和当前菜单选中的key，openWasy为1时代表当前页打开，2新建页面打开,existHash是否存在hash，存在则代表是驾驶舱预览或者驾驶舱分享
 */
export const getRouterConfig: () => {
  id: number;
  openWay?: 1 | 2;
  curSelectedKey?: number;
  existHash: boolean;
} = () => {
  const id = getPortalId() as number;
  return {
    id,
    openWay: Number(location.hash.match(new RegExp(/openWay=([^&]*)/))?.[1]) as 1 | 2,
    curSelectedKey: Number(location.hash.match(new RegExp(/curSelectedKey=([^&]*)/))?.[1]),
    existHash: !!location.hash,
  };
};

// 通过菜单配置信息确认是新建页面打开
export const jumpByNavConfig = (data: NavItemType) => {
  if (/\/spaceShipEdit\//i.test(window.location.pathname) || data?.openWay === 1) {
    return;
  }
  const { pathname, origin } = window.location;
  window.open(`${origin}${pathname}#openWay=2&curSelectedKey=${data.id}`);
};

//这里是获取当前选中的菜单的子级存在引用类型为外链或者应用的菜单的数据
export const getCurSelectedKeyById = (data: NavItemType[]) => {
  return (
    deepFindOne(
      data || [],
      (item: NavItemType) => [1, 2, -1].includes(item.quoteType),
      `children`,
    ) || {}
  );
};

// 根据level拿到中文菜单
export const getLevelToChinese = (level: NavItemType['level']) => {
  const data = { 1: '一', 2: '二', 3: '三', 4: '四' };
  return data[level] ? `${data[level]}级菜单` : '';
};

// 判断当前路由是否时驾驶舱编辑页
export const pathNameIsSpaceShipEdit: (pathname?: string) => boolean = (
  pathname = window.location.pathname,
) => {
  return /\/spaceShipEdit\//i.test(pathname);
};

export const getHeight = (curPortalBaseInfo: SpaceShipState['curPortalBaseInfo']) => {
  if (pathNameIsSpaceShipEdit()) {
    return 'calc(100vh - 64px)';
  } else {
    if (curPortalBaseInfo?.navBarLayout === 2) {
      return 'calc(100vh - 60px)';
    }
    return '100vh';
  }
};
