// 运行时配置
import { RunTimeLayoutConfig, RequestConfig } from '@umijs/max';
import { message } from 'antd';
import UserDropdown from '@/components/UserDropdown';
import { getToken } from '@/utils/utils';
import { history } from 'umi';
import logo from '@/assets/logo.png';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string }> {
  return { name: 'admin' };
}

export const layout: RunTimeLayoutConfig = (initialState) => {
  return {
    navTheme: 'light',
    layout: 'side',
    contentWidth: 'Fluid',
    title: '金科环境数字化管理平台',
    token: {
      sider: {
        colorMenuBackground: '#292f33',
        // colorMenuItemDivider: '#dfdfdf',
        // colorBgMenuItemHover: '#f6f6f6',
        // colorTextMenu: '#dfdfdf',
        // colorTextMenuSelected: '#fff',
        // colorTextMenuActive: 'rgba(255,255,255,0.85)',
        // colorBgMenuItemCollapsedHover: '#fff',
        // colorTextMenuItemHover: '#dfdfdf',

        colorBgCollapsedButton: '#fff',
        colorTextCollapsedButtonHover: 'rgba(0,0,0,0.65)',
        colorTextCollapsedButton: 'rgba(0,0,0,0.45)',
        colorBgMenuItemCollapsedHover: 'rgba(0,0,0,0.06)',
        colorBgMenuItemCollapsedSelected: 'rgba(0,0,0,0.15)',
        colorBgMenuItemCollapsedElevated: 'rgba(0,0,0,0.85)',
        colorMenuItemDivider: 'rgba(255,255,255,0.15)',
        colorBgMenuItemHover: 'rgba(0,0,0,0.06)',
        colorBgMenuItemSelected: 'rgba(0,0,0,0.15)',
        colorTextMenuSelected: '#fff',
        colorTextMenuItemHover: 'rgba(255,255,255,0.75)',
        colorTextMenu: 'rgba(255,255,255,0.75)',
        colorTextMenuSecondary: 'rgba(255,255,255,0.65)',
        colorTextMenuTitle: 'rgba(255,255,255,0.95)',
        colorTextMenuActive: 'rgba(255,255,255,0.95)',
        colorTextSubMenuSelected: '#fff',
      },
    },
    // fixedHeader: true,
    // fixSiderbar: true,
    rightRender(initialState, setInitialState, runtimeConfig) {
      return <UserDropdown />;
    },
    logo: logo,
  };
};

// axios配置
export const request: RequestConfig = {
  errorConfig: {
    errorThrower(res: any) {
      // const { data, code, msg } = res;
      // if (code !== 200) {
      //   const error: any = new Error(msg);
      //   error.name = 'AjaxError';
      //   error.info = { code, msg, data };
      //   throw error;
      // }
      console.log('errorThrower', res);
    },
    errorHandler(error: any, opts: any) {
      if (opts?.skipErrorHandler) throw error;
      // errorThrower 抛出的错误。
      if (error.name === 'AjaxError') {
        // 校验是否token失效
        if (tokenExpiredHandle(error.info.code)) return;
        const errorInfo: any = error.info;
        if (errorInfo) {
          message.error(errorInfo.msg || errorInfo.data);
        }
      } else if (error.response) {
        // http错误,校验token是否失效
        if (tokenExpiredHandle(error.response.status)) return;
        // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        message.error(`网络连接错误，请稍后重试(${error.response.status})`);
      } else if (error.request) {
        // 请求已经成功发起，但没有收到响应
        // \`error.request\` 在浏览器中是 XMLHttpRequest 的实例，
        // 而在node.js中是 http.ClientRequest 的实例
        message.error('网络连接错误，请稍后重试（服务器未返回数据）。');
      } else {
        // 发送请求时出了点问题
        message.error('网络连接错误，请稍后重试（请求发送失败）。');
      }
    },
  },
  requestInterceptors: [
    (config: any) => {
      if (!config.headers) config.headers = {};
      config.headers['JWT-TOKEN'] = getToken();
      return config;
    },
  ],
  responseInterceptors: [
    (res: any) => {
      const resData = res.data;
      const { code, msg, data } = resData;
      if (code !== 200) {
        const error: any = new Error(msg);
        error.name = 'AjaxError';
        error.info = { code, msg, data };
        // throw error;
        return Promise.reject(error);
      }
      return res;
    },
  ],
};
let tokenFlag: boolean = false;
// token失效校验
const tokenExpiredHandle = (code: number) => {
  if ([401, 601, 602, 603].includes(code)) {
    if (tokenFlag) return true;

    tokenFlag = true;
    setTimeout(() => {
      tokenFlag = false;
    }, 50000);
    message.error('token失效，请重新登录');

    history.push('/login');
    return true;
  } else {
    return false;
  }
};
