import axios from 'axios';
import { clearAuthTokens } from './auth';
import { ElMessage } from 'element-plus';

const request = axios.create({
  timeout: 5000
});

// 是否正在刷新token
let isRefreshing = false;
// 等待刷新token的请求队列
let requestsQueue = [];

// 执行队列中的请求
const processQueue = (error, token = null) => {
  requestsQueue.forEach(prom => {
    if (error) {
      prom.reject(error);
    } else {
      prom.resolve(token);
    }
  });
  requestsQueue = [];
};

// 判断是否是需要登录才能访问的API
const isAuthRequiredApi = (url) => {
  // 这些API需要登录才能访问，如果未登录会返回401
  const authRequiredApis = [
    '/user/info',
    '/post/publish',
    '/notification',
    '/user/info/avatar',
    '/user/info/update',
    '/user/info/password'
  ];
  
  return authRequiredApis.some(api => url.includes(api));
};

//响应拦截器
request.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return response.data;
    }
    return Promise.reject(response.data);
  },
  error => {
    console.error('请求错误:', error);
    
    // 如果响应状态码是401或500，可能是token过期或格式错误
    if (error.response && (error.response.status === 401 || 
        (error.response.status === 500 && error.response.data?.message?.includes('token')))) {
      const originalRequest = error.config;
      
      // 判断是否是需要登录的API
      const needAuth = isAuthRequiredApi(originalRequest.url);
      
      // 如果是500错误且与token相关，直接清除token并拒绝请求
      if (error.response.status === 500 && error.response.data?.message?.includes('token')) {
        console.error('Token格式错误:', error.response.data.message);
        clearAuthTokens();
        if (needAuth) {
          ElMessage.warning('登录已失效，请重新登录');
        }
        return Promise.reject(error);
      }
      
      // 防止重复刷新token
      if (!isRefreshing) {
        isRefreshing = true;
        
        // 尝试使用refreshToken获取新的accessToken
        const refreshToken = localStorage.getItem('refreshToken');
        const accessToken = localStorage.getItem('accessToken');
        
        if (!refreshToken || !accessToken || typeof refreshToken !== 'string' || typeof accessToken !== 'string') {
          if (needAuth) {
            ElMessage.warning('请先登录');
          }
          // 只有当token格式明显不正确时才清除
          if ((refreshToken && typeof refreshToken !== 'string') || 
              (accessToken && typeof accessToken !== 'string')) {
            clearAuthTokens();
          }
          isRefreshing = false;
          return Promise.reject(error);
        }
        
        // 调用check-login接口刷新token
        return axios.post('/user/check-login', null, {
          headers: {
            'Authorization': `Bearer ${accessToken}`,
            'X-Refresh-Token': refreshToken
          }
        }).then(res => {
          if (res.data && res.data.code === 200 && res.data.data) {
            // 更新token
            const { accessToken, refreshToken } = res.data.data;
            localStorage.setItem('accessToken', accessToken);
            localStorage.setItem('refreshToken', refreshToken);
            
            // 更新原始请求的Authorization头
            originalRequest.headers['Authorization'] = `Bearer ${accessToken}`;
            originalRequest.headers['X-Refresh-Token'] = refreshToken;
            
            // 处理队列中的请求
            processQueue(null, accessToken);
            
            // 重新发送原始请求
            return axios(originalRequest);
          } else {
            processQueue(new Error('刷新Token失败'), null);
            if (needAuth) {
              // 不清除token，只提示用户
              ElMessage.warning('请先登录');
            }
            return Promise.reject(error);
          }
        }).catch(err => {
          processQueue(err, null);
          if (needAuth) {
            // 只有在确认token格式错误时才清除
            if (err.response && err.response.status === 500 && 
                err.response.data?.message?.includes('token')) {
              clearAuthTokens();
            }
            ElMessage.warning('请先登录');
          }
          return Promise.reject(err);
        }).finally(() => {
          isRefreshing = false;
        });
      } else {
        // 将请求加入队列
        return new Promise((resolve, reject) => {
          requestsQueue.push({
            resolve: token => {
              originalRequest.headers['Authorization'] = `Bearer ${token}`;
              resolve(axios(originalRequest));
            },
            reject: err => {
              reject(err);
            }
          });
        });
      }
    }
    
    return Promise.reject(error);
  }
);

//请求拦截器
request.interceptors.request.use(
  config => {
    console.log('Request:', config.url);
    // 只对非认证相关的API添加token
    if (!config.url.includes('/captcha') && !config.url.includes('/verify-captcha') && 
        !config.url.includes('/user/login') && !config.url.includes('/user/register')) {
      const token = localStorage.getItem('accessToken');
      const refreshToken = localStorage.getItem('refreshToken');
      
      // 检查token格式是否正确
      if (token && refreshToken && typeof token === 'string' && typeof refreshToken === 'string') {
        config.headers['Authorization'] = `Bearer ${token}`;
        config.headers['X-Refresh-Token'] = refreshToken;
        console.log('添加token到请求头:', config.url);
      } else if ((token && typeof token !== 'string') || 
                 (refreshToken && typeof refreshToken !== 'string')) {
        // 只有当token格式明显错误时才清除
        console.warn('Token格式不正确，清除token');
        clearAuthTokens();
      } else if (!token || !refreshToken) {
        // 如果没有token但访问需要认证的API，尝试从localStorage恢复
        const userId = localStorage.getItem('userId');
        const username = localStorage.getItem('username');
        
        if (userId && username) {
          console.warn('访问需要认证的API但没有token，可能需要重新登录');
        }
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

export default request;