import bg1Layout from '@/assets/images/lay-bg1.webp';
import bg2Layout from '@/assets/images/lay-bg2.webp';
import bg3Layout from '@/assets/images/lay-bg3.webp';
import { AvatarDropdown, AvatarName, Footer, Icon, SelectLang } from '@/components';
import { secureLocalStorage as ls } from '@/utils/localUtils';
import { Settings as LayoutSettings } from '@ant-design/pro-components';
import mcLogoSvg from '@svgs/multi-color/mc-logo.svg';
import type { RequestConfig, RuntimeConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { App } from 'antd';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import VersionChecker from './components/VersionChecker';
import { requestConfig } from './requestConfig';
import { AntdAppInstanceCapture } from './utils/antdAppInstance';
import { userKey } from './utils/authUtils';
import { loginPath, toLoginPage } from './utils/routerUtils';

dayjs.extend(utc);

const isDev = process.env.NODE_ENV === 'development';
const appEnv = process.env.REACT_APP_ENV;

const VersionCheckComponent: React.FC = () => {
  if (appEnv !== 'prod' && appEnv !== 'test' && appEnv !== 'dev') {
    return null;
  }

  const currentBuildTime = process.env.REACT_APP_BUILD_TIME;
  if (!currentBuildTime) {
    return null;
  }

  return (
    <VersionChecker
      currentBuildTime={currentBuildTime}
      checkInterval={60 * 1000}
      notificationCooldown={5 * 60 * 1000}
    />
  );
};

let title = `${process.env.REACT_APP_NAME}`;
let waterMarkContent = '';

if (isDev) {
  waterMarkContent = `${process.env.REACT_APP_NAME} - 本地环境`;
} else if (appEnv === 'dev') {
  waterMarkContent = `${process.env.REACT_APP_NAME} - 开发环境`;
} else if (appEnv === 'test') {
  waterMarkContent = `${process.env.REACT_APP_NAME} - 测试环境`;
}

if (waterMarkContent !== '') {
  title = waterMarkContent;
}

const defSettings = {
  ...defaultSettings,
  title,
  logo: <Icon icon={mcLogoSvg} width="44px" height="44px" />,
};

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.UserInfo | null;
  fetchUserInfo?: () => Promise<API.UserInfo | null>;
}> {
  const fetchUserInfo = () => {
    return new Promise<API.UserInfo | null>((resolve) => {
      const userInfo = ls.getLocal<API.UserInfo>(userKey);
      resolve(userInfo);
    });
  };

  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defSettings as Partial<LayoutSettings>,
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    stylish: {
      sider: (token) => ({
        backgroundColor: token.colorBgLayout,
      }),
    },
    pageTitleRender: false,
    menu: {
      defaultOpenAll: true,
      ignoreFlatMenu: true,
      autoClose: false,
    },
    menuProps: {
      mode: 'inline',
      inlineIndent: 24,
    },
    actionsRender: () => [<SelectLang key="SelectLang" />],
    avatarProps: {
      size: 24,
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown menu>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: waterMarkContent,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      if (!initialState?.currentUser?.username && location.pathname !== loginPath) {
        toLoginPage();
      }
    },
    disableMobile: true,
    bgLayoutImgList: [
      {
        src: bg1Layout,
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: bg2Layout,
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: bg3Layout,
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    childrenRender: (children) => {
      return (
        <>
          {children}
          <VersionCheckComponent />
        </>
      );
    },
    ...initialState?.settings,
  };
};

export const request: RequestConfig = requestConfig;

export const locale: RuntimeConfig['locale'] = {
  onError: (err: string) => {
    if (err.includes('using message id as fallback')) return;
    if (err.includes('Missing message')) return;
    console.error(err);
  },
};

export function rootContainer(container: React.ReactNode) {
  return (
    <App>
      <AntdAppInstanceCapture />
      {container}
    </App>
  );
}
