// 运行时配置
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';
import { useModel } from '@umijs/max';
import { queryCurrentV2 } from './services/user';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

dayjs.locale('zh-cn');

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

  let permission = {};
  user.Permissions?.forEach((item: any) => {
    permission = {
      ...permission,
      ...item.Menus,
    };
  });
  return {
    user: {
      ...user,
      Permission: permission,
    },
  };
}

export const layout: RunTimeLayoutConfig = (initialState) => {
  return {
    navTheme: 'light',
    layout: 'mix',
    title: '',
    token: {
      header: {
        colorBgHeader: '#292f33',
        colorHeaderTitle: '#fff',
        colorTextMenu: '#dfdfdf',
        colorTextMenuSecondary: '#dfdfdf',
        colorTextMenuSelected: '#fff',
        colorBgMenuItemSelected: '#22272b',
        colorTextRightActionsItem: '#dfdfdf',
      },
      sider: {
        colorMenuBackground: '#fff',
        colorMenuItemDivider: '#dfdfdf',
        colorTextMenu: '#595959',
        colorTextMenuSelected: 'rgba(42,122,251,1)',
        colorBgMenuItemSelected: 'rgba(230,243,254,1)',
      },
    },
    // fixedHeader: true,
    // fixSiderbar: true,
    rightRender: () => <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);
          return error.info;
        }
      } 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) {
        let error: any = {};
        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;
  }
};
