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('token --->', 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', '2014', '2013', '5008'].includes(data.code)) {
        message.error(data.message).then();
        Cookies.remove('SHAREFLY-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;
