import axios from 'axios';
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken, getTokenFrom, setToken } from '@/utils/auth';
import { isString } from '@/utils/is';
import qs from 'query-string';
export interface HttpResponse<T = unknown> {
  status: number;
  message: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.defaults.paramsSerializer = params => {
  return qs.stringify(params, { arrayFormat: 'bracket' });
};

axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      const tokenFrom = getTokenFrom();
      config.headers.Authorization = `Bearer ${token}`;
      config.headers['tokenFrom'] = tokenFrom;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    if (
      isString(response.headers['refresh-token']) &&
      response.headers['refresh-token'] !== ''
    ) {
      setToken(response.headers['refresh-token']);
    }
    // 二进制文件
    if (
      response.headers['content-type'] === 'application/force-download' ||
      response.headers['content-type'] === 'application/octet-stream' ||
      response.headers['content-type'] === 'application/zip' ||
      response.config.responseType === 'blob' ||
      response.headers['content-type'] ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ) {
      return response;
    }
    const res = response.data;
    if (res.code !== 0) {
      Message.error({
        content: res.message || 'Error',
        duration: 5 * 1000
      });
      if (
        [5001, 5002, 5003].includes(res.code) &&
        response.config.url !== '/api/user/info'
      ) {
        Modal.error({
          title: '警告',
          content: '登录过期，你可以选择刷新、继续保持当前页面或重新登录',
          okText: '重新登录',
          async onOk() {
            const userStore = useUserStore();
            await userStore.logout();
            window.location.reload();
          }
        });
      }
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  },
  error => {
    Message.error({
      content: error.msg || 'Request Error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);
