import axios from "axios";
import router from "@/router/index.js";
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';
//const baseURL = "https://gep.ljsea.top/";
const baseURL = "https://uc.ljsea.top/";
//const baseURL= "http://localhost:8084";
//const baseURL="https://pm.ljsea.top";
//const baseURL = "https://gep.ljsea.xyz/";

let isRefreshing = false;
let requests = [];

const request = axios.create({
  baseURL: baseURL,
});

// 请求拦截器 - 添加token
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      config.headers.token = token;
    }
    return config;
  }
);

// 响应拦截器
request.interceptors.response.use(
  result => {
    if(result.status !== 200) {
      router.push("/login");
    }

    if(result.data.message === "NOT_LOGIN" || [2, 3, 4].includes(result.data.code)) {
      // 检测到token过期
      if (isRefreshing == false) {
        isRefreshing = true;
        // 这里需要替换为实际的refresh token请求
        return axios.post('https://uc.ljsea.top/user/refresh_token', {
          refresh_token: localStorage.getItem("refresh_token")
        },{
          headers: {
            'Authorization': `Bearer ${localStorage.getItem("refresh_token")}`
          }
        }).then(res => {
          const token = res.data["data"]["access_token"];
          localStorage.setItem("token", token);
          //alert("token: " + token);
          
          // 重试所有挂起的请求
          requests.forEach(cb => cb(token));
          requests = [];
          isRefreshing = false;
          
          // 重试当前请求
          const config = result.config;
          config.headers.Authorization = `Bearer ${token}`;
          return request(config);
        }).catch(err => {
          // 刷新token失败，跳转登录
          ElMessage.error('登录已过期，请重新登录！');
          router.push("/login");
          return Promise.reject(err);
        });
      } else if (isRefreshing) {
        // 正在刷新token，将请求放入队列
        return new Promise(resolve => {
          requests.push(token => {
            //alert("new token: " + token);
            result.config.headers.Authorization = `Bearer ${token}`;
            result.config.headers.token = token;
            resolve(request(result.config));
          });
        });
      } 
    }

    if(result.data.code == 7) {
      ElMessage.error('该用户已存在，请重新输入！');
      return null;
    }

    if(result.data.code == 1) {
      ElMessage.error('请求失败，请稍后重试！');
    } else {
      return result.data;
    }
  }
);

export default request;