import { message } from 'antd';
import { LOGIN_PATHNAME } from '../constants';
import { CommonController, ConfigurationController } from '../services';
import { sessionStore } from './store';
import qs from 'query-string';
import { createWatermark } from './watermark';
import { getAppIdHolder, getMenuHolder, getButtonHolder } from './initial';
import { isMatchRoute } from '.';
import { pathHolder } from './route';

const { pathname = '', search = '' } = location;
const { _groupName_ } = qs.parse(search);
sessionStore.move('group-name');
document.documentElement.setAttribute('data-layout-menu', 'hide');
document.documentElement.setAttribute('data-layout', 'hide');
document.documentElement.setAttribute(
  'data-render-root',
  ['/notFound', '/login'].map(pathHolder).includes(pathname) ? 'show' : 'hide',
);

const createLoadHanlder = (duration = 1000) => {
  // 延迟一秒后才展示loading状态，避免频繁看到loading
  let shouldLoading = true;
  setTimeout(() => {
    if (shouldLoading) {
      message.loading({ content: '加载中...', duration: 0, key: 'loading' });
    }
  }, duration);
  return () => {
    message.destroy('loading');
    shouldLoading = false;
  };
};

export default async function render(renderHandler: () => void) {
  // 获取系统配置信息 - 免登录调用的接口
  const systemConfig = await CommonController.getConfigurationApi();
  sessionStore.set('system-config', systemConfig);
  const { configValue: _configValue } = systemConfig || {};
  const configValue: ConfigurationController.SystemConfigValueFields =
    JSON.parse(_configValue || '{}');
  const { waterStatus, waterParams: _waterParams } = configValue;

  // 验证是否是免登录路由
  const loginBlackRoutes: string[] = (
    sessionStore.get('login-black-route-list') || []
  ).map(pathHolder);

  const isLoginBlack = loginBlackRoutes.some((path) =>
    isMatchRoute(path, pathname),
  );
  if (isLoginBlack) {
    return renderHandler();
  }

  const closeLoading = createLoadHanlder(1000);
  // 获取用户信息、菜单列表、按钮权限等
  try {
    const userInfo = await CommonController.getUserInfoApi();
    sessionStore.set('user-info', userInfo);

    // 添加水印
    if (waterStatus === 'y') {
      const waterParams = Object.fromEntries(
        (_waterParams || '')
          .split(/\n/)
          .filter(Boolean)
          .map((item) => item.split('=')),
      );
      const { content: _content, ...rest } = waterParams;
      const content = _content
        ? [_content]
        : [userInfo?.user?.nickName, userInfo?.medicalInfo?.orgName].filter(
            Boolean,
          );
      createWatermark({ ...rest, content });
    }

    const appId = await getAppIdHolder();
    if (appId) {
      await getMenuHolder(appId, _groupName_ as string);
      await getButtonHolder(appId);
    }
  } catch (error) {
    if (pathname !== pathHolder(LOGIN_PATHNAME)) {
      const url = qs.stringifyUrl({
        // query: { redirect: location.href },
        url: `${location.origin}${pathHolder(LOGIN_PATHNAME)}`,
      });
      location.replace(url);
    }
  }
  renderHandler();
  closeLoading();
}
