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

// 接口地址
const { VITE_REQUEST_BASE_URL } = import.meta.env;

// 图片上传
export const uploadImgURL = `${VITE_REQUEST_BASE_URL}/pms/upload/imgOsses`;
export const uploadVideoURL = `${VITE_REQUEST_BASE_URL}/ossservlet/upload/videoOss`;
export const uploadFileURL = `${VITE_REQUEST_BASE_URL}/ossservlet/upload/oss`;
// 创建服务
const service = axios.create({
  baseURL: VITE_REQUEST_BASE_URL,
  timeout: 3600000,
});

service.interceptors.request.use(
  (config: any) => {
    const token = Cookies.get('SHAREFLY-TOKEN');
    // console.log('config --->', config);
    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 (['200', '7002'].includes(data.code)) {
        return Promise.resolve(data);
      }
      // 重新登录？
      if (['605', '603', '602', '4004', '607', '2014', '2013', '5008'].includes(data.code)) {
        message.error(data.message).then();
        Cookies.remove('SHAREFLY-TOKEN');
        localStorage.removeItem('roleId');
        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);
  },
);
// 取消token
export const generateCancelToken = () => {
  let cancel = null;
  const cancelToken = new axios.CancelToken((c) => {
    cancel = c;
  });
  return {
    cancel,
    cancelToken,
  };
};

export default service;
