import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getToken } from '@/utils/auth';
import { useUserStoreHook } from '@/store/modules/user';

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.NODE_ENV==='development'? import.meta.env.VITE_APP_BASE_API:window.webConfig.webApiBaseUrl,
  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`
      );
    }
    const user = useUserStoreHook();
    if (user.Token) {
      config.headers.token = getToken();
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
let isSwitch = false
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, statusText } = response;
    if (status === 200) {
      isSwitch = false
      if (response.data.code == 401) {
        ElMessage({
          message: response.data.msg,
          type: 'error'
        });
        return response.data;
      } else if (response.data.code == 1) {
        ElMessage({
          message: response.data.msg,
          type: 'error'
        });
        return response.data;
      }
      return response.data;
    } else {
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      ElMessage({
        message: statusText || '系统出错',
        type: 'error'
      });
      isSwitch = false
      return Promise.reject(new Error(statusText || 'Error'));
    }
  },
  (error: any) => {
    if (error.response.data) {
      const { status, msg } = error.response.data;
      // token 过期,重新登录
      if (status === '403'||status === 403) {
        // ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
        //   confirmButtonText: 'OK',
        //   type: 'warning'
        // }).then(() => {
          // localStorage.clear();
          // window.location.href = '/';
      //   });
      // } else {
        if(isSwitch == true || error.response.config.url == '/user/me'){
          return
        }
        isSwitch = true
        ElMessage({
          message: msg || '当前页面已失效',
          type: 'error'
        });
        setTimeout(() => {
          // localStorage.clear();
          window.location.href = '/';
        }, 1500)
      
        
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
