import axios, { AxiosResponse } from 'axios';
import { message } from 'antd';
import Cookies from 'js-cookie';
import { Base64 } from 'js-base64';

const { REACT_APP_BASE_URL } = process.env;
export const uploadImgURL = `${REACT_APP_BASE_URL}ossservlet/upload/imgOss`;
export const uploadVideoURL = `${REACT_APP_BASE_URL}ossservlet/upload/videoOss`;
export const uploadFileURL = `${REACT_APP_BASE_URL}ossservlet/upload/oss`;
const service = axios.create({
  baseURL: REACT_APP_BASE_URL,
  timeout: 6000,
});
service.interceptors.request.use(
  (config: any) => {
    const token = Cookies.get('SXTB-TOKEN');
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, status } = response;
    // 当接口返回正常时执行
    if (status === 200) {
      // 如果不报错就直接返回数据
      if (data.code === '200') {
        return Promise.resolve(data);
      }
      // 重新登录？
      if (['605', '603', '602', '4004', '607'].includes(data.code)) {
        message.error(data.message).then();
        Cookies.remove('SXTB-TOKEN');
        setTimeout(() => {
          window.location.reload();
        }, 1000);
        // 阻止后续代码执行
        return Promise.reject(data);
      }
      // 文件/base64导出判断
      if (data instanceof Blob || Base64.isValid(data)) {
        return Promise.resolve(data);
      }
      // 如果还有其他报错那么就弹出报错信息(不需要对每个接口的报错做单独判断)
      message.error(data.message || '啊呀，出错了').then();
      return Promise.reject(data);
    }
    // 网络错误或链接超时
    message.error(data.message).then();
    return Promise.reject(data);
  },
  (error) => {
    if (error.response) {
      message.error(`${error.response.status},${error.response.statusText}`, 1).then();
    }
    return Promise.reject(error);
  },
);

export const generateCancelToken = () => {
  let cancel = null;
  const cancelToken = new axios.CancelToken((c) => {
    cancel = c;
  });
  return {
    cancel,
    cancelToken,
  };
};

export default service;
