// 运行时配置
import { App, message, theme } from 'antd';
import { history } from '@umijs/max';

import NProgress from "nprogress";
import "nprogress/nprogress.css";

import Footer from '@/components/Footer';
import HeaderNav from '@/components/HeaderNav';
import defaultConfig from '../config/defaultConfig';
import defaultTheme from '../config/defaultTheme';

import routes from '../config/routes';
import { getToken, setAuthority } from '@/utils/auth';
import { formatMenuData } from '@/utils/func';

import services from '@/services/admin';
const { authUser, authPermission } = services.AuthController;

const loginPath = '/login';
const nologin = '/showdata';

message.config({
  top: 100,
  duration: 3,
  maxCount: 1,
});

//请求拦截器
const requestInterceptor = (config) => {
  NProgress.start();

  // 拦截请求配置，进行个性化处理。
  const token = getToken();
  const accessToken = `Bearer ${token}`;
  config.headers.Authorization = accessToken;
  config.headers['Content-Type'] = 'application/json';
  config.headers['Accept'] = 'application/json';

  console.log(config);

  // 分页字段修改
  if (config.params && config.params.current) {
    config.params.page = config.params.current;
    config.params.pagesize = config.params.pageSize;
    delete config.params.current;
    delete config.params.pageSize;
  }
  // 分页字段修改
  if (config.data && config.data.current) {
    config.data.page = config.data.current;
    config.data.pagesize = config.data.pageSize;
    delete config.data.current;
    delete config.data.pageSize;
  }


  config.url.includes('https://');
  let url = `${process.env.API_URL}${config.url}`;

  if (config.url.includes('https://')) {
    url = config.url;
  }

  return { ...config, url };
};

// 拦截响应数据，进行个性化处理
const responseInterceptor = async (response) => {
  NProgress.done();

  if (response?.data?.show) {
    const { data, show, msg, code } = response?.data;

    switch (show) {
      case 1:
        message.success(msg, 3);
        break;
      case 2:
        message.error(msg, 3);
        break;
    }
  }

  // if (response?.data?.success === false) {
  //   const error = new Error('errorMessage');
  //   error.name = 'BizError';
  //   error.info = 'res';
  //   throw error;
  // }

  return response;
};

export const request = {
  timeout: 20000,
  // other axios options you want
  errorConfig: {
    errorHandler(error) {
      NProgress.done();

      if (error?.response?.status === 401 && history?.location?.pathname !== nologin) {
        history.push(loginPath);
        message.error('请登录', 3);
      } else {

        if (error?.response?.data?.msg) {
          message.error(error?.response?.data?.msg, 3);
        } else {
          message.error(error?.message, 3);
        }
      }

    },
    errorThrower(res) {
      const { success, data, code, show, msg } = res;

      if (!success) {
        message.error(msg, 3);
        // const error = new Error(errorMessage);
        // error.name = 'BizError';
        // error.info = res;
        // throw error;
      }
    }
  },
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptor]
};


export async function getInitialState() {

  const fetchAuthUser = async () => {
    try {
      const { data } = await authUser();
      return data;
    } catch (error) {

    }
    return undefined;
  };

  const fetchAuthPermission = async () => {
    try {
      const { data } = await authPermission();
      const action = [];
      data?.items.forEach((item) => {
        if (item.type === 2) {
          action.push(item.path);
        }
      });

      return {
        menu: formatMenuData(data.tree),
        action: action
      };
    } catch (error) {
    }
    return undefined;
  };

  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const authUserData = await fetchAuthUser();
    const authPermissionData = await fetchAuthPermission();

    return {
      fetchAuthUser: fetchAuthUser,
      fetchAuthPermission: fetchAuthPermission,
      userInfo: authUserData,
      authPermissionMenu: authPermissionData?.menu,
      authPermissionAction: authPermissionData?.action,
      config: defaultConfig,
      themeConfig: defaultTheme
    };
  }
  return {
    fetchAuthUser: fetchAuthUser,
    fetchAuthPermission: fetchAuthPermission,
    config: defaultConfig,
    themeConfig: defaultTheme
  };
}


// ProLayout 支持的api https://procomponents.ant.design/components/layout
// { initialState, loading, error, refresh, setInitialState }
export const layout = ({ initialState, loading, error, refresh, setInitialState }) => {
  return {
    ...defaultConfig,
    fixedHeader: true,
    waterMarkProps: {
      content: defaultConfig.title
    },
    avatarProps: {
      src: initialState?.userInfo?.avatar,
      size: 'small',
      title: initialState?.userInfo?.mobile,
    },
    headerContentRender: () => (<HeaderNav />),
    footerRender: () => <Footer />,
    menuDataRender: (menuData) => {
      const menu = routes.concat(initialState?.authPermissionMenu || []);
      return menu;
    },
    childrenRender: (children, props) => {
      return (
        <>
          {children}
        </>
      );
    },
  };
};
//import { RuntimeAntdConfig } from '@umijs/max';

//https://umijs.org/docs/max/antd#%E8%BF%90%E8%A1%8C%E6%97%B6%E9%85%8D%E7%BD%AE
export const antd = (memo) => {
  //const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState');

  const token = {
    token: {
      //主题色
      colorPrimary: '#13A8A8',
    }
  };
  // memo.theme = { ...defaultTheme };


  //darkAlgorithm暗黑，compactAlgorithm紧凑
  //memo.theme.algorithm = theme.darkAlgorithm; // 配置 antd5 的预设 dark 算法

  memo.appConfig = {
    message: {
      // 配置 message 最大显示数，超过限制时，最早的消息会被自动关闭
      maxCount: 1,
    }
  }

  return memo;
};

