import axios from "axios";
import localStronge from "../api/localData";
//import { Message, Loading } from "element-ui";
import { myMessage } from "@/utils/messageOnce.js";
import router from "@/router";
import { getToken, removeToken } from "@/utils/auth"; // 引入统一的auth方法
import store from "@/store";

let data = localStronge.getServiceip();
const service = axios.create({
  baseURL: process.env.NODE_ENV === "development" ? "/apis" : "",
  // baseURL: 'http://' + data.ip + ':' + data.host ,
  timeout: 600000, // request timeout
});

service.interceptors.request.use(
  (config) => {
    console.log(111111111);
    // 使用统一的getToken方法替代直接操作sessionStorage
    const token = getToken();
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // let arr = document.getElementsByClassName('el-loading-mask')
    // for (let item of arr) {
    //     item.style.display = 'none'
    // }
    if (res.code === "101") {
      myMessage({
        message: res.msg || "Error",
        type: "error",
        duration: 2 * 1000,
      });
      return Promise.reject(new Error(res.msg || "Error"));
    } else if (res.code === "401") {
      myMessage({
        message: "请重新登录",
        type: "error",
        duration: 2 * 1000,
      });
      setTimeout(() => {
        removeToken();
        router.push("/userLogin");
      }, 1000);
      return;
    } else if (res.code === "403") {
      myMessage({
        message: "您无权访问此操作",
        type: "error",
        duration: 2 * 1000,
      });
      setTimeout(() => {
        // sessionStorage.clear();
        router.push("/403");
      }, 1000);
      return;
    }
    // if (res.code === 777) {
    //     Message({
    //         message: res.msg || 'Error',
    //         type: 'error',
    //         duration: 5 * 1000
    //     })
    //     window.location.href = `${process.env.VUE_APP_ERP_ADMIN}/#/login`
    //     return Promise.reject(new Error(res.message || 'Error'))
    // }
    // if (res.code === 5000) {
    //     // Message({
    //     //     message: res.message || 'Error',
    //     //     type: 'error',
    //     //     duration: 5 * 1000
    //     // })
    //     return res
    // }
    // if (res.code > 6000) { // token失效
    //     Message({
    //         message: res.message || 'Error',
    //         type: 'error',
    //         duration: 5 * 1000
    //     })
    //     router.replace({
    //         path: '/401'
    //     })
    // }
    // loadingInstance.close()
    return res;
  },
  (error) => {
    myMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
export default service;
