import RightContent from '@/components/RightContent';
import themes from '@/styles/theme.less';
import { type GlobalInitialState } from '@/types';
import { menuItemRender } from '@/utils/menuRender';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { RuntimeConfig, history } from '@umijs/max';
import { RuntimeAntdConfig } from 'umi';
import defaultSettings from '../config/defaultSettings';
import '../public/fonts/font.css';
import { getAccessToken } from './access';
import ErrorBoundary from './components/ErrorBoundary';
import './dayjsConfig';
import { removeAllPageCacheState } from './hooks/useCacheState';
import { globalGetSeverTime } from './hooks/useServerTime';
import {
  getRemoteMenu,
  getRoutersInfo,
  getUserInfo,
  patchRouteWithRemoteMenus,
  setRemoteMenu,
} from './services/session';
import './styles/menu.less';
import { needAuth } from './utils';
import { gotoLoginPage } from './utils/ui';
export { requestConfig as request } from './requestConfig';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 */
export async function getInitialState(): Promise<GlobalInitialState> {
  const fetchUserInfo = async () => {
    try {
      globalGetSeverTime();
      const response = await getUserInfo();
      return {
        ...response.user,
        avatar: response.user.avatar || require('@/assets/img/avatar-default.png'),
        permissions: response.permissions,
        roles: response.roles,
        roleNames: response.user.roles,
      } as API.CurrentUser;
    } catch (error) {
      console.error('getInitialState', error);
      gotoLoginPage();
    }
    return undefined;
  };

  // 如果不是登录页面，执行
  const { location } = history;

  // console.log('getInitialState', needAuth(location.pathname));
  if (needAuth(location.pathname)) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
      collapsed: false,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
    collapsed: false,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RuntimeConfig['layout'] = ({ initialState }) => {
  return {
    ErrorBoundary: ErrorBoundary,
    rightContentRender: false,
    waterMarkProps: {
      // content: initialState?.currentUser?.nickName,
    },
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
      params: {
        userId: initialState?.currentUser?.userId,
      },
      request: async () => {
        if (!initialState?.currentUser?.userId) {
          return [];
        }
        // console.log('get menus')
        // initialState.currentUser 中包含了所有用户信息
        // console.log('get routers')
        // setInitialState((preInitialState) => ({
        //   ...preInitialState,
        //   menus,
        // }));
        return getRemoteMenu();
      },
    },
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && needAuth(location.pathname)) {
        gotoLoginPage();
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    childrenRender: (children) => {
      // 增加一个 loading 的状态
      // if (initialState?.loading) return <PageLoading />;
      return (
        <div className="kf-page-container">
          <RightContent></RightContent>
          <div className="kf-page-container__content">{children}</div>
        </div>
      );
    },
    collapsedButtonRender: false,
    collapsed: initialState?.collapsed,
    menuProps: {
      onClick: () => {
        // 点击菜单项，删除所有的页面 state 缓存
        removeAllPageCacheState();
      },
    },
    ...initialState?.settings,
    logo: require('@/assets/img/logo.png'),
    token: {
      sider: {
        colorTextMenu: themes['textColor'],
        colorTextMenuSelected: themes['primaryColor'],
        colorTextMenuActive: themes['primaryColor'],
        colorTextMenuItemHover: themes['primaryColor'],
        colorBgMenuItemSelected: 'rgba(197, 232, 255, 0.8)',
        colorMenuBackground: themes['siderBGColor'],
      },
    },
    menuItemRender: menuItemRender(false),
    subMenuItemRender: menuItemRender(true),
  };
};

export const onRouteChange: RuntimeConfig['onRouteChange'] = async (e) => {
  const { location } = e;
  const menus = getRemoteMenu();
  // console.log('onRouteChange', menus);
  if (menus === null && needAuth(location.pathname)) {
    history.go(0);
  }
};

export const patchRoutes: RuntimeConfig['patchRoutes'] = () => {
  //console.log('patchRoutes', e);
};

export const patchClientRoutes: RuntimeConfig['patchClientRoutes'] = (e) => {
  // console.log('patchClientRoutes', e);
  patchRouteWithRemoteMenus(e.routes);
};

export function render(oldRender: () => void) {
  // console.log('render');
  const token = getAccessToken();
  if (!token || token?.length === 0) {
    oldRender();
    return;
  }
  getRoutersInfo()
    .then((res) => {
      setRemoteMenu(res);
      oldRender();
    })
    .catch(() => {
      oldRender();
    });
}

// 主题修改
export const antd: RuntimeAntdConfig = (memo) => {
  memo.theme ??= {};
  memo.theme.token = {
    colorPrimary: themes['primaryColor'],
    colorSuccess: themes['successColor'],
    colorError: themes['errorColor'],
    colorWarning: themes['warningColor'],
    colorLink: themes['primaryColor'],
    colorText: themes['textColor'],
    controlHeightLG: 46,
  };
  memo.theme.components ??= {};
  memo.theme.components.Tabs = {};
  memo.theme.components.Button = {
    defaultBg: 'rgba(22, 100, 255, 0.06)',
    defaultBorderColor: 'rgba(22, 100, 255, 0.11)',
    defaultColor: themes['textColor'],
    defaultHoverBg: 'rgba(22, 100, 255, 0.06)',
    defaultHoverBorderColor: 'rgba(22, 100, 255, 0.5)',
    defaultHoverColor: '#3F7FFF',
    defaultActiveBg: 'rgba(22, 100, 255, 0.12)',
    defaultActiveBorderColor: 'rgba(22, 100, 255, 0.75)',
    defaultActiveColor: themes['primaryColor'],
    contentFontSize: parseInt(themes['fontSize']),
  };
  memo.theme.components.Input = {
    inputFontSize: parseInt(themes['fontSizeInput']),
    inputFontSizeLG: parseInt(themes['fontSizeInputLg']),
    paddingBlockLG: 10,
  };
  memo.theme.components.Select = {
    singleItemHeightLG: 46,
    optionSelectedColor: themes['primaryColor'],
  };
  memo.theme.components.Table = {
    headerBg: 'rgba(242, 244, 247, 0.36)',
    headerBorderRadius: 4,
    // rowSelectedBg: 'rgba(22, 100, 255, 0.05)', 固定列时，横向滑动导致重叠
  };
  memo.theme.components.Tabs = {
    titleFontSize: 16,
  };
  memo.theme.components.Form = {
    labelColor: 'rgba(29, 29, 32, 0.8);',
  };
  memo.theme.components.Breadcrumb = {
    iconFontSize: parseInt(themes['fontSize']),
    linkColor: 'rgba(29, 29, 32, 0.7)',
    separatorColor: 'rgba(29, 29, 32, 0.7)',
  };
  memo.theme.components.Tree = {
    directoryNodeSelectedBg: 'rgba(22, 100, 255, 0.7)',
  };

  memo.theme.cssVar = true;
  memo.theme.hashed = false;

  memo.appConfig = {
    message: {
      // 配置 message 最大显示数，超过限制时，最早的消息会被自动关闭
      maxCount: 3,
    },
  };

  return memo;
};
