import type { MenuDataItem, Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { decryptData } from '@/utils/utils';
import defaultSettings from '../config/defaultSettings';
import '../public/font.css';
import { AvatarDropdown } from './components/RightContent/AvatarDropdown';
import { errorConfig } from './requestErrorConfig';

const loginPath = '/login';

type CurrentUser = {
  username?: string;
  nickname?: string;
  avatar?: string;
  realName?: string;
  phone?: string;
  permissionKeys?: string[];
};

type InitialState = {
  settings?: Partial<LayoutSettings>;
  currentUser?: CurrentUser;
  permission?: Record<string, boolean>;
  loading?: boolean;
};

const ensureMenuKeys = (menuData: MenuDataItem[], parentKey = 'menu'): MenuDataItem[] =>
  menuData.map((item, index) => {
    const key = item.key || item.path || `${parentKey}-${String(item.name || index)}`;

    return {
      ...item,
      key,
      children: item.children ? ensureMenuKeys(item.children, String(key)) : item.children,
    };
  });

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialState> {
  // 如果不是登录页面，执行
  const { location } = history;

  if (location.pathname !== loginPath && !decryptData(localStorage.getItem('userInfo'))) {
    history.replace(loginPath);
  }
  return {
    permission: decryptData(localStorage.getItem('access')) || {},
    currentUser: decryptData(localStorage.getItem('userInfo')) || {},
    settings: { ...defaultSettings, fixedHeader: true } as Partial<LayoutSettings>,
  };
};

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    avatarProps: {
      render: () => {
        return <AvatarDropdown />;
      },
    },
    waterMarkProps: {
      content: '',
    },
    // 自定义 403 页面
    unAccessible: <div></div>,
    // 自定义 404 页面
    noFound: <div></div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      return (
        <>
          {children}
          <SettingDrawer
            disableUrlParams
            enableDarkTheme
            settings={initialState?.settings}
            onSettingChange={(settings) => {
              setInitialState((preInitialState) => ({
                ...preInitialState,
                settings,
              }));
            }}
          />
        </>
      );
    },
    ...initialState?.settings,
    menuDataRender: ensureMenuKeys,
    pageTitleRender: () => '管理后台',
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
