import { AvatarDropdown, AvatarName, Question } from '@/components';
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, useModel } from '@umijs/max';
import { message } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { scriptUrl } from './global';
import { errorConfig, ResponseStructure } from './requestErrorConfig';
import { getMenu } from './services/global';
import { getUserInfo } from './services/login';
import { flattenRoutes } from './utils/generateNewLocalMenu';
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';
  token?: any;
  menu?: any;
}> {
  // 如果不是登录页面,执行
  const { location } = history;
  let menuType = (sessionStorage.getItem('menuType') as 'distributor' | 'miniApp') || 'distributor';
  let navTheme: any = localStorage.getItem('navTheme') || '2'; //主题色 2白 3黑
  if (location.pathname !== loginPath && localStorage.getItem('Admin-Token')) {
    const res = await getUserInfo();
    if (res.data) {
      return {
        token: res.data.token,
        currentUser: res.data.userInfo,
        menuType,
        settings: defaultSettings as Partial<LayoutSettings>,
        navTheme,
      };
    }
  }
  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 {
    // 动态管理菜单
    splitMenus: true, //切割菜单
    menu: {
      locale: false, //关闭国际化
      params: {
        //token变化重新获取
        token: initialState?.token,
      },
      request: async () => {
        //需要在routes.tsx中配置一份完整的路由
        let menu = await getMenu(['book']); //线上获取路由
        let flatMenu = flattenRoutes(menu);
        setInitialState({ ...initialState, menu: flatMenu });
        history.push(flatMenu[flatMenu['/'].redirect].redirect); //获取到本地路由后跳转到有权限的页面
        return menu;
      },
    },
    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: (location: any) => {
      //页面发生变化触发
      hasHandledCode300 = false;
      let obj = initialState?.menu || {};
      if (obj[location.pathname] && obj[location.pathname].redirect) {
        //强制调整到正确的路由地址
        history.push(obj[location.pathname].redirect);
      }
      // // 在小程序页面禁止用户点击回退按钮返回分享页面
      // if (sessionStorage.getItem("menuType") == 'miniApp' && location?.pathname?.match(/^\/distributor/)) {
      //   console.log("miniApp", location)
      //   history.replace('/miniApp');
      // }
      // // 在分销平台首页禁止用户点击回退按钮返回到小程序页面
      // if (sessionStorage.getItem("menuType") == 'distributor' && location?.pathname?.match(/^\/miniApp/)) {
      //   console.log("distributor", location)
      //   history.replace('/distributor');
      // }
      // // 如果没有登录,重定向到 login

      if (!localStorage.getItem('Admin-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={initialState?.selectApp?.appType === 1 ? "icon-weixin" : "icon-douyinzhanghao"} style={{ fontSize: 30 }} />
    //       <strong style={{ fontSize: 18 }}>{initialState?.selectApp?.appName}</strong>
    //     </Space>
    //   } else {
    //     return false
    //   }
    // },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children: any) => {
      // if (initialState?.loading) return <PageLoading />;
      const { init, state } = useModel('global', (ret) => ({
        init: ret.init,
        state: ret.state,
      }));
      if (!state?.enumList && localStorage.getItem('Admin-Token')) {
        init(); //初始全局
      }
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  menuType: preInitialState?.menuType || 'distributor',
                  settings,
                  token: preInitialState?.token || '',
                  // menu: preInitialState?.menu || [],
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
    navTheme: initialState?.navTheme === '2' ? 'light' : 'realDark',
    // title:<span style={{fontSize:24,fontFamily:'cursive'}}>{defaultSettings?.title}</span>
    // 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 310:
          if (!hasHandledCode300) {
            hasHandledCode300 = true; // 设置标志位,表示已经处理过
            message.error(data.msg);
            localStorage.removeItem('Admin-Token');
            sessionStorage.removeItem('menuType');
            sessionStorage.removeItem('selectApp');
            history.push(loginPath);
          }
          break;
        // case 500:
        //   message.error(data.msg)
        //   break
      }

      return response;
    },
  ],
};