// 运行时配置

import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import {
  ProLayoutProps,
  ProSchemaValueEnumObj,
  ProTable,
} from '@ant-design/pro-components';
import { RequestConfig, history, useModel } from '@umijs/max';
import { App, Avatar, ConfigProvider, Dropdown, MenuProps } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { usercontrollerGetuser } from './servers/api/user';

// 设置 dayjs 全局语言为中文
dayjs.locale('zh-cn');

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档:https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{
  user?: Record<string, any>;
  categoryList?: ProSchemaValueEnumObj;
  sites?: API.SiteConfig[];
}> {
  if (!localStorage.getItem('token') || history.location.pathname === '/login')
    return {};

  const { data: user } = await usercontrollerGetuser();
  return { user };
}

export const layout = (): ProLayoutProps => {
  const { initialState } = useModel('@@initialState');
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: '我的账号',
      disabled: true,
    },
    {
      type: 'divider',
    },
    {
      key: '3',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: async () => {
        //TODO 清理服务器登陆状态
        localStorage.removeItem('token');
        history.push('/login');
      },
    },
  ];

  return {
    menu: {
      locale: false,
    },
    layout: 'mix',
    actionsRender: () => (
      <Dropdown key="avatar" menu={{ items }}>
        <div style={{ cursor: 'pointer' }}>
          <Avatar size="large" icon={<UserOutlined />} />
          <span style={{ marginLeft: 8 }}>{initialState?.name}</span>
        </div>
      </Dropdown>
    ),
  };
};

export const request: RequestConfig = {
  baseURL: UMI_APP_API_URL,
  requestInterceptors: [
    (url: string, options: any) => {
      const token = localStorage.getItem('token');
      return {
        url,
        options: {
          ...options,
          headers: {
            ...options.headers,
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        },
      };
    },
  ],
  errorConfig: {
    errorHandler: (error: any) => {
      if (error?.response?.status === 401) {
        localStorage.removeItem('token');
        history.push('/login');
      }
    },
  },
};

export const onRouteChange = ({ location }: { location: Location }) => {
  const token = localStorage.getItem('token');

  // 白名单，不需要登录的页面
  const whiteList = ['/login', '/track'];

  if (!token && !whiteList.includes(location.pathname)) {
    // 没有 token 且不在白名单内，跳转到登录页
    history.push('/login');
  }
};

export function rootContainer(container: React.ReactNode) {
  // 全局过滤空字段逻辑
  (ProTable as any).defaultProps = {
    ...(ProTable as any).defaultProps,
    beforeSearchSubmit: (params: any) => {
      return Object.fromEntries(
        Object.entries(params).filter(
          ([_, value]) => value !== undefined && value !== null && value !== '',
        ),
      );
    },
  };
  return (
    <ConfigProvider>
      <App>{container}</App>
    </ConfigProvider>
  );
}
