import Footer from '@/components/Footer';
import type { MenuDataItem, Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import HeaderRight from './components/HeaderRight';
import { history } from '@umijs/max';
import UserAPI from '@/api/User';
import React from 'react';
import * as Icon from '@ant-design/icons';
const isDev = process.env.NODE_ENV === 'development';

const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] => {
  return menus?.map(({ icon, routes, ...item }) => ({
    ...item,
    icon: icon && React.createElement(Icon[icon as string]),
    routes: routes && loopMenuItem(routes),
  }));
};

const formartRoutes = (menuTree: any[]) => {
  menuTree.forEach((item) => {
    item.path = item.url;
    if (item.children && item.children.length > 0 && item.category < 2) {
      formartRoutes(item.children);
    } else {
      delete item.children;
    }
  });
  return menuTree;
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  fetchUserInfo: () => any;
  menuData: any[];
  currentUser: any;
}> {
  const fetchUserInfo = async () => {
    const response:MyResponse.Content = await UserAPI.GetUserInfo();
    if (response.statusCode===200) {
      console.log('response',response);
      
      return response.data;
    }
    return null;
  };
  const response = await fetchUserInfo();
  if (response) {
    localStorage.setItem('USER_INFO', JSON.stringify(response.userInfo));
    localStorage.setItem('USER_MENU', JSON.stringify(response.menus));
    return {
      menuData: formartRoutes(response.menus),
      currentUser: response.userInfo,
      fetchUserInfo,
      settings: defaultSettings,
    };
  }
  return {
    menuData: [],
    currentUser: null,
    fetchUserInfo,
    settings: defaultSettings,
  };
}
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const config: any = {
    rightContentRender: () => <HeaderRight />,
    waterMarkProps: {
      content: '黑菠萝科技研发部',
    },
    token: {
      colorBgAppListIconHover: 'rgba(0,0,0,0.06)',
      colorTextAppListIconHover: 'rgba(255,255,255,0.95)',
      colorTextAppListIcon: 'rgba(255,255,255,0.85)',
      sider: {
        colorBgCollapsedButton: '#13C2C2',
        colorTextCollapsedButtonHover: 'rgba(0,0,0,0.65)',
        colorTextCollapsedButton: 'rgba(0,0,0,0.45)',
        colorMenuBackground: '#000',
        colorBgMenuItemCollapsedHover: 'rgba(0,0,0,0.06)',
        colorBgMenuItemCollapsedSelected: '#13C2C2',
        colorMenuItemDivider: 'rgba(255,255,255,0.15)',
        colorBgMenuItemHover: '#F5222D',
        colorBgMenuItemSelected: '#13C2C2',
        colorTextMenuSelected: '#fff',
        colorTextMenuItemHover: 'rgba(255,255,255,0.75)',
        colorTextMenu: 'rgba(255,255,255,0.75)',
        colorTextMenuSecondary: 'rgba(255,255,255,0.65)',
        colorTextMenuTitle: 'rgba(255,255,255,0.95)',
        colorTextMenuActive: 'rgba(255,255,255,0.95)',
        colorTextSubMenuSelected: '#fff',
      },
      header: {
        colorBgHeader: '#000000',
        colorMenuBackground: '#fff',
        colorHeaderTitle: '#13C2C2',
      },
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const userToken = localStorage.getItem('USER_TOKEN');
      if (userToken) {
        const userInfo = JSON.parse(userToken);
        //如果Token不存在跳转登录页面
        if (!userInfo) {
          history.push('/user/login');
        }
      } else {
        history.push('/user/login');
      }
    },
    menuDataRender: () => loopMenuItem(initialState?.menuData as any[]),
    childrenRender: (children: any) => {
      // children.pathname = history.location.pathname;
      return (
        <>
          {children}
        </>
      );
    },
    ...initialState?.settings,
  };
  if (config.menuDataRender) {
    delete config.menuDataRender;
  }
  return config;
};

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