import { Footer, Question, AvatarDropdown, AvatarName } from '@/components';
// import { HomeOutlined, LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig, ResponseStructure } from './requestErrorConfig';
import React from 'react';
import { getUserInfo } from './services/login';
import { message, Space } from 'antd';
import { MyIcon, scriptUrl } from './global';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';


/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: any;
  loading?: boolean;
  menuType: "distributor" | "miniApp",
  navTheme?: "2" | "3",
  selectApp?: { appId: string, id: string, appName: string } | null,
  token: any,
}> {
  // 如果不是登录页面，执行
  const { location } = history;
  let selectApp = sessionStorage.getItem("selectApp");
  let menuType = sessionStorage.getItem("menuType") as ("distributor" | "miniApp") || 'distributor';
  let navTheme: any = localStorage.getItem("navTheme") || '2';//主题色 2白 3黑
  if (location.pathname !== loginPath) {
    const res = await getUserInfo();
    // console.log(res)
    if (res.data) {
      return {
        token: res.data.token,
        currentUser: res.data.userInfo,
        menuType,
        settings: defaultSettings as Partial<LayoutSettings>,
        navTheme,
        selectApp: selectApp ? JSON.parse(selectApp) : null
      };
    }
  }
  return {
    token: "",
    menuType: "distributor",
    navTheme,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    // 动态管理菜单
    // menu: {
    //   // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
    //   params: {
    //     userId: initialState?.menuType,
    //   },
    //   request: async (params, defaultMenuData) => {
    //     // initialState.currentUser 中包含了所有用户信息
    //     // const menuData = 
    //     console.log(defaultMenuData,initialState)
    //     return defaultMenuData;
    //   },
    // },
    iconfontUrl: scriptUrl,
    actionsRender: () => [<Question key="doc" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar || "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      hasHandledCode300 = false
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!localStorage.getItem("Token") && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    // links: initialState?.menuType === 'miniApp' ? [] : [],
    menuHeaderRender: (logo, title, props) => {
      if (props?.collapsed) {
        return false
      } else if (initialState?.selectApp) {
        return <Space>
          <MyIcon type='icon-xiaochengxu' style={{ fontSize: 30 }} />
          <strong style={{ fontSize: 20 }}>{initialState?.selectApp?.appName}</strong>
        </Space>
      } else {
        return false
      }
    },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  menuType: preInitialState?.menuType || "distributor",
                  settings,
                  token: preInitialState?.token || "",
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
    navTheme: initialState?.navTheme === '2' ? "light" : "realDark"
    // title:initialState?.selectApp ? defaultSettings?.title + '--'+initialState?.selectApp?.appName : defaultSettings?.title //标题修改
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
let hasHandledCode300 = false;
export const request: RequestConfig = {
  ...errorConfig,
  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const { data } = response as unknown as ResponseStructure;
      switch (data.code) {
        case 300:
          if (!hasHandledCode300) {
            hasHandledCode300 = true; // 设置标志位，表示已经处理过
            message.error(data.msg);
            localStorage.removeItem("Token");
            sessionStorage.removeItem("menuType");
            sessionStorage.removeItem("selectApp");
            history.push(loginPath)
          }
          break;
        case 500:
          message.error(data.msg)
          break
      }


      return response;
    },
  ],
};
