import Footer from '@/components/Footer';
import { type MenuDataItem, type Settings as LayoutSettings, PageContainer, ProBreadcrumb, ProCard } 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/sys/service';
import React from 'react';
import * as Icon from '@ant-design/icons';
const isDev = process.env.NODE_ENV === 'development';

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


const formartRoutes = (menuTree: any[]) => {
  menuTree.forEach((item) => {
    item.path = item.url;
    item.component = item.component;
    // item.icon = item.icon || 'SettingOutlined'
    if (item.routes && item.routes.length > 0 && item.category < 2) {
      formartRoutes(item.routes);
    } else {
      delete item.routes;
    }
  });
  // menuTree = menuTree.filter((item,index)=>item.routes.length = 0 && item.component == null&& item.category < 2)
  // 要保留的属性列表
const keepProps = ['name', 'path','routes','icon'];
// 使用map和扩展运算符删除多余的属性
const filteredEntities = menuTree.map(entity => {
  // 创建一个只包含要保留属性的对象
  const filtered:any = {};
  keepProps.forEach(prop => {
    if (entity.hasOwnProperty(prop)) {
      filtered[prop] = entity[prop];
    }
  });
  return filtered;
});
return filteredEntities;
};

/**
 * @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) {
    sessionStorage.setItem(`USER_INFO-${response.userInfo.userId}`, JSON.stringify(response.userInfo));
    sessionStorage.setItem(`USER_MENU-${response.userInfo.userId}`, 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: {
      layout: {
        bgLayout: '#001529'
      },
      // colorBgAppListIconHover: '#fff',
      // colorTextAppListIconHover: 'rgba(255,255,255,0.95)',
      // colorTextAppListIcon: 'rgba(255,255,255,0.85)',
      sider: {
        // colorBgCollapsedButton: '#0960bd',
        // colorTextCollapsedButtonHover: '#fff',
        // colorTextCollapsedButton: '#fff',
        colorMenuBackground: '#001529',//菜单背景色
        //colorBgMenuItemCollapsedHover: '#fff',
        colorBgMenuItemCollapsedElevated: '#001529',
        colorBgMenuItemCollapsedSelected: '#0960bd',
        colorMenuItemDivider: 'rgba(255,255,255,0.15)',
        colorBgMenuItemHover: '#0960bd',
        colorBgMenuItemSelected: '#0960bd',
        colorTextMenuSelected: '#ffffff',
        colorTextMenuItemHover: '#fff',
        colorTextMenu: '#fff',
        colorTextMenuSecondary: '#fff',
        colorTextMenuTitle: '#fff',//系统名称
        // colorTextMenuActive: '#fff',
        colorTextSubMenuSelected: '#fff',
        // },
        header: {
          colorBgHeader: '#ffffff',
          colorMenuBackground: '#000',
          colorHeaderTitle: '#ffffff',
        },
        // pageContainer:{
        //   paddingInlinePageContainerContent: 20,
        //   paddingBlockPageContainerContent:10
      },
      pageContainer: {
        colorBgPageContainer: '#f5f5f5',
        colorBgPageContainerFixed: '#0960bd'
      },
    },
    headerContentRender: () => <ProBreadcrumb />,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const userToken = sessionStorage.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 (process.env.NODE_ENV === 'development') {
  //   if (config.menuDataRender) {
  //     delete config.menuDataRender;
  //   }
  // }
  return config;
};

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