// 自定义axios
import axios from "axios";
import router from "@/router";
import { Message } from "element-ui";
import { isMockEnabled, setupMock, setupGlobalMock } from "@/mock";

console.log(router, Message);

// 接口前缀：Mock 模式用相对路径；否则用环境变量或默认远程地址
const REMOTE_URL = "http://81.70.146.224:11500";
let URL = "";
if (isMockEnabled()) {
  URL = "";
  setupGlobalMock();
} else if (process.env.VUE_APP_API_BASE_URL) {
  URL = process.env.VUE_APP_API_BASE_URL;
} else if (process.env.NODE_ENV === "development") {
  URL = REMOTE_URL;
} else {
  URL = REMOTE_URL;
}

if (isMockEnabled()) {
  console.log("[Mock] 已启用本地 Mock 数据，无需连接后端");
} else {
  console.log("[API] baseURL:", URL);
}

const token = localStorage.getItem("token");

const serve = axios.create({
  baseURL: URL,
  timeout: 5000,
  headers: {
    Authorization: `${token}`,
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  dataType: "json",
});

if (isMockEnabled()) {
  setupMock(serve);
}

// 请求拦截：每次请求带上最新 token
serve.interceptors.request.use((config) => {
  const latestToken = localStorage.getItem("token");
  if (latestToken) {
    config.headers.Authorization = latestToken;
  }
  return config;
});

// 响应拦截
serve.interceptors.response.use((res) => {
  if (res.data.code == 200) {
    return res.data;
  } else if (res.data.code == 101) {
    Message.error(res.data.msg);
  } else if (res.data.code == 199) {
    Message.error(res.data.msg);
  } else if (res.data.code == 401) {
    Message.error(res.data.msg);
  } else if (res.data.code == 188) {
    Message.error(res.data.msg);
  } else if (res.data.code == 500) {
    Message.error(res.data.msg);
    Message.error(res.data.msg);
  } else {
    Message.error(res.data.msg);
  }
});

export { serve };
export let http = (url, method = "post", data) => {
  if (method == "get") {
    return new Promise((resolve, reject) => {
      serve({
        method: method,
        url: url,
        params: data,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  } else {
    return new Promise((resolve, reject) => {
      serve({
        method: method,
        url: url,
        data: data,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
};
