import axios from "axios";
import { Notification } from "element-ui";
import {
  generateAesKey,
  encryptBase64,
  encryptWithAes,
} from "../utils/encryption/crypto.js";
import { encrypt } from "../utils/encryption/jsencrypt.js";
import { isString } from "./is.js";
import { joinTimestamp } from "./helper.js";
import store from "../store/index.js";
// 基本配置
const instance = axios.create({

  timeout: 20000, // 设置超时时间，单位为ms
});
function setObjToUrlParams(baseUrl, obj) {
  let parameters = "";
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      parameters += key + "=" + encodeURIComponent(obj[key]) + "&";
    }
  }
  if (parameters.length > 0) {
    parameters = parameters.slice(0, -1);
  }
  if (/\?$/.test(baseUrl)) {
    return baseUrl + parameters;
  } else {
    return baseUrl.replace(/\/?$/, "?") + parameters;
  }
}



// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = 'Bearer ' + localStorage.getItem("token"); // 设置请求头部分，这里举例使用了localStorage存储的token作为身份标识


    const params = config.params || {};
    const data = config.data || false;
    const joinTime = true;
    const joinParamsToUrl = config.joinParamsToUrl; // 接口参数是否需要��接到 URL 后面


    if (config.method?.toUpperCase() === "GET") {

   
      if (!isString(params)) {
        config.params = Object.assign(
          params || {},
          joinTimestamp(joinTime, false)
        );
      } else {
        // 兼容restful风格
        config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
        config.params = undefined;
      }
    } else {
      if (!isString(params)) {
        if (
          config.hasOwnProperty("data") &&
          config.data &&
          Object.keys(config.data).length > 0
        ) {
          config.data = data;
          config.params = params;
        } else {
          // 非 GET 请求如果没有提供 data，则将 params 视为 data
          config.data = params;
          config.params = undefined;
        }
        if (joinParamsToUrl) {
          config.url = setObjToUrlParams(
            config.url,
            Object.assign({}, config.params, config.data)
          );
        }
      } else {
        // 兼容 restful 风格
        config.url = config.url + params;
        config.params = undefined;
      }
    }
    config.headers["clientId"] = "e5cd7e4891bf95d1d19206ce24a7b32e";
    //接口请求参数是否需要加密
    if (config.encrypt) {
      const aesKey = generateAesKey();
      config.headers["encrypt-key"] = encrypt(encryptBase64(aesKey));
      //   console.log(config.data, aesKey);
      if (typeof config.data === "object") {
        config.data = encryptWithAes(JSON.stringify(config.data), aesKey);
      } else {
        config.data = encryptWithAes(config.data, aesKey);
      }
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const data = response.data;

    // console.log(data);
    if (data && data.code !== 200) {
      // 根据接口返回的状态码判断是否有错误
      if (data.code === 401) {
        // 登出操作
        localStorage.removeItem("token");

        store.dispatch("SILENCE_LOGIN", {});
        return
      }
      Notification.error({
        title: data.code,
        message: data.msg,
      });
      return Promise.reject(new Error(data.msg));
    } else {
      return data;
    }
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

export default instance;
