import type { RequestConfig } from "@umijs/max";
import { message, Modal, Dropdown, MenuProps, theme } from "antd";
import { BulbOutlined, LogoutOutlined } from '@ant-design/icons';
import { baseUrl } from './constants/index'
import routes from '../config/routes'
import { history } from '@umijs/max';
import {
  ProBreadcrumb,
} from '@ant-design/pro-components';

import { GetUserMenulist} from '@/apis/api';
export async function getInitialState(): Promise<{ permissions: object[] }> {
 
  const token = sessionStorage.getItem('token');
  let permissions = [];
  if (!token) {
    sessionStorage.clear();
    history.push('/login');
    return { permissions };
  }
  try {
    const res = await GetUserMenulist();
    permissions = flattenPermissions(res.data.menulist);

  } catch (error) {
    console.error('Failed to fetch user permissions:', error);
  }

  if (permissions.length === 0) {
    history.push('/login');
  }

  return { permissions };
}

function flattenPermissions(permissions: { id: number; action: string; childs?: { id: number; action: string }[] }[]): string[] {
  const flattenedPermissions: string[] = [];

  permissions.forEach(permission => {
    flattenedPermissions.push(permission.action);
    if (permission.childs) {
      flattenedPermissions.push(...flattenPermissions(permission.childs));
    }
  });

  return flattenedPermissions;
}



export const layout = () => {
  return {
    name: '菊城人才市场',
    logo: '/images/logo_1.jpg',
    // copy from pro site
    navTheme: 'dark',
    primaryColor: '#1890ff',
    layout: 'mix',
    contentWidth: 'Fluid',
    fixedHeader: true,
    fixSiderbar: true,
    // splitMenus: true,
    siderWidth: 240,
    title: '菊城人才市场',
    pwa: false,
    iconfontUrl: '',
    headerContentRender: () => (<> <ProBreadcrumb /></>),
    avatarProps: {
      src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
      size: 'small',
      title: '管理员',
      render: (props, dom) => {
        return (
          <Dropdown
            menu={{
              items: [
                {
                  key: 'logout',
                  icon: <LogoutOutlined />,
                  label: '退出登录',
                }
              ],
              onClick: ({ key }) => {
                sessionStorage.clear();
                history.replace('/login');
              }
            }}
          >
            {dom}
          </Dropdown>
        );
      }
    },
    token: {
      sider: {
        //侧边菜单的配置 ，这里具体看文档
        colorBgMenuItemSelected: '#19be6e',
        colorTextMenuItemSelected: '#ffffff',
      },
    },
  };
};

export function onRouteChange({
  location,
}) {
  sessionStorage.setItem('path', location.pathname)
}


export const request: RequestConfig = {
  baseURL: baseUrl,
  errorConfig: {
    // 错误抛出
    errorThrower: (res) => {
      const { success, data, errorCode, errorMessage, showType } = res;
      if (!success) {

      }
    },
  },
  // 配置请求头
  requestInterceptors: [
    (config: object) => {
      // 拦截请求配置，进行个性化处理。
      const token = sessionStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `${token}`;
      }
      return config;
    },
  ],
  // 配置响应拦截
  responseInterceptors: [
    (response) => {
      const msgModel = (val: String, code: number) => {
        Modal.error({
          title: val,
          centered: true
        });
      }
      // 拦截响应数据，进行个性化处理
      const { data } = response;
      switch (data.code) {
        case -1:
          msgModel(data.msg, data.code)
          break;
        case 0:
          break;
        case 1:
          return response;
          break;
        case 401:
          msgModel(data.msg, data.code)
          sessionStorage.clear();
          history.push('/login');
          break;
        case 403:
          msgModel(data.msg, data.code)
          break;
        case 404:
          break;
        case 600:
          if (data.errors && Object.keys(data.errors).length > 0) {
            msgModel(data.errors, data.code)
          } else {
            msgModel(data.msg, data.code)
          }
      }
      return response;
    }
  ]
}



