import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from "element-plus";
import { useCommonStore } from "@/store/common";
import router from "@/router/index";

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_URL,
  timeout: 5000
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const comm = useCommonStore();
    config.headers['Access-Token'] = comm.user.token;
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, headers } = response;
    if (headers['content-type'] === "application/vnd.ms-excel;charset=utf-8") return data

    if (data.code !== 200) {
      ElMessage.error(data.msg)

      if (data.code === 1003) {
        const comm = useCommonStore();
        comm.clearStore()
        router.replace('/login');
      }
      return Promise.reject(data);
    } else {
      return data.data
    }

  },
  (error: AxiosError) => {
    return Promise.reject();
  }
);

export default service;
