import axios from 'axios';
import { notification } from 'antd';
import RoutePath from '@/routes/routePath';
import { history } from 'umi';
import { CACHE_TOKEN } from '@/constants/cacheKey';

// create an axios instance
const request = axios.create({
  baseURL: '/tbg/api/v1', //
  timeout: 10000, // request timeout
});
// request interceptor
request.interceptors.request.use(
  (memo: any) => {
    memo.headers.Authorization = localStorage.getItem(CACHE_TOKEN);
    return memo;
  },
  (error) => {
    return Promise.reject(error);
  },
);

request.interceptors.response.use(
  (response) => {
    const res: any = response.data;
    if (res.code !== 200) {
      if (res.code === 401 || res.code === 10001) {
        notification.error({
          message: '错误信息',
          description: '登录失效',
        });
        history.replace(RoutePath.LOGIN);
        localStorage.removeItem(CACHE_TOKEN);
        return Promise.reject(new Error('Login expiration'));
      }
      notification.error({
        message: '错误信息',
        description: res.msg,
      });
      return Promise.reject(res.msg || 'Error');
    }
    return res.data;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export const baseRequestForm = (url: string, data: object, ...rest: any) => {
  const form = new FormData();
  Object.keys(data).map((key) => {
    form.append(key, data[key]);
    return key;
  });
  return request({
    url,
    method: 'post',
    body: form,
    ...rest,
  });
};

export const baseRequestGet = (url: string, params) => request({ url, method: 'get', params });

export const baseRequestPost = (url: string, data) => request({ url, method: 'post', data });

export default request;
