import axios from 'axios';
import config from '../public/config.js';
import { Toast } from 'tdesign-mobile-vue'

const instance = axios.create({
  baseURL: config.httpApi, // 设置基础URL
  timeout: 60000
});

// 定义Token刷新状态变量
let isRefreshing = false;
let requestQueue = [];

// 添加请求拦截器
instance.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json';

  if (config.data && typeof config.data === 'object') {
    config.data = JSON.stringify(config.data);
  }

  // 获取URL最后一段
  const url = window.location.href;
  const lastSegment = url.substring(url.lastIndexOf('/'));

  // 如果不是登录请求
  if (config.url !== 'Login/Login') {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    } else if (lastSegment != '/login') {
      handleTokenExpiration();
    }
  }

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

// 添加响应拦截器
instance.interceptors.response.use(response => {
  return response;
}, async error => {
  const originalRequest = error.config;

  // 检测到Token过期(401错误)
  if (error.response && error.response.status === 401 && !originalRequest._retry) {

    // 防止重复刷新
    if (!isRefreshing) {
      isRefreshing = true;
      originalRequest._retry = true;

      try {
        // 尝试刷新Token
        const newToken = await refreshToken();

        // 用新Token重试原始请求
        originalRequest.headers['Authorization'] = `Bearer ${newToken}`;

        // 处理队列中等待的请求
        requestQueue.forEach(subscriber => subscriber(newToken));
        requestQueue = [];

        return instance(originalRequest);
      } catch (refreshError) {
        // 刷新失败处理
        handleTokenExpiration();
        return Promise.reject(refreshError);
      } finally {
        isRefreshing = false;
      }
    }

    // 如果正在刷新Token，将请求加入队列
    return new Promise((resolve, reject) => {
      requestQueue.push((token) => {
        originalRequest.headers['Authorization'] = `Bearer ${token}`;
        resolve(instance(originalRequest));
      });
    });
  }

  return Promise.reject(error);
});

export default instance;

// Token刷新方法 (优化版)
async function refreshToken() {
  try {
    const username = localStorage.getItem('rememberedUsername');
    const password = localStorage.getItem('rememberedPassword');

    if (!username || !password) {
      throw new Error('登录凭证已过期');
    }

    const response = await instance.post('Login/Login', {
      username,
      password
    });

    if (response.data.isok) {
      const newToken = response.data.response.accessToken;
      localStorage.setItem('token', newToken);
      return newToken;
    } else {
      throw new Error('Token更新失败');
    }
  } catch (error) {
    console.error('Token刷新失败:', error);
    throw error;
  }
}

// Token过期处理
function handleTokenExpiration() {
  Toast({
    theme: 'error',
    direction: 'column',
    message: '登录已过期，请重新登录',
  });
  setTimeout(() => {
    localStorage.removeItem('token');
    window.location.href = '/login';
  }, 1000);
}
