import axios from 'axios';
import type { AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

import router from '../router'



let loading = undefined as any;
let loadingCount = 0;
function startLoading() {
  if (!loading) {
    loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  loadingCount++;
}
function endLoading() {
  loadingCount--;
  if (loadingCount <= 0) {
    loading.close();
  }
}

// 创建 axios 实例
const service = axios.create({
  baseURL: '',
  //baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }
    if (localStorage.getItem('token')) {
      console.log('token', "Bearer " + localStorage.getItem('token'))
      config.headers.Authorization = "Bearer " + localStorage.getItem('token')
    }

    if (config.url === '/button/perm/list') {
      return config;
    } else {
      startLoading();
      return config;
    }
  },
  (error: any) => {
    endLoading();
    loadingCount = 0;
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message } = response.data;
    const { authorization } = response.headers;
    if (authorization) {
      localStorage.setItem('token', authorization)
    }
    if (code === '0') {
      endLoading();
      return response.data;
    }
    if (code === 'UndefinedCode') {
      endLoading();
      return response.data;
    }
    if (code === '500') {
      endLoading();
      return response.data;
    }

    endLoading();
    return response.data;

  },
  (error: any) => {
    endLoading();
    loadingCount = 0;
    console.log(error);
    if (error.response.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      const redirctPath = window.location.pathname.split('/wms-sap')[1]
      router.push(`/login?redirect=${redirctPath}`);
    }else {
      return Promise.reject(error);
    }
  }
);

// 导出 axios 实例
export default service;
