// import Request from "@/utils/axios";
// 创建axios实例;
// const request = new Request({
//   // axios中请求配置有baseURL选项，表示请求URL公共部分
//   baseURL: process.env.VUE_APP_BASE_URL,
//   // 超时
//   timeout: 1000 * 30,
//   interceptors: {
//     requestInterceptor: (config) => {
//       console.log(1);
//       return config;
//     },
//     requestInterceptorCatch: (config) => {
//       console.log(2);
//       return config;
//     },
//     responseInterceptor: (error) => {
//       console.log(3);
//       return error;
//     },
//     responseInterceptorCatch: (error) => {
//       console.log(4);
//       return error;
//     }
//   },
//   headers: {
//     "Content-Type": "application/json;charset=utf-8"
//   }
// });

import qs from "qs";
import axios from "axios";
import cache from "@/utils/cache";
import errorCode from "@/utils/errorCode";
import store from "@/store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css";
import { serialize } from "@/utils/util";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";

// 是否显示重新登录
export const isRelogin = { show: false };

// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: process.env.VUE_APP_BASE_URL,
  // 超时
  timeout: 10000
});

// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
// request拦截器
request.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    NProgress.start(); // start progress bar
    const isToken = (config.headers || {}).isToken === false;
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
    const token = store.getters.access_token;
    if (token && !isToken && config.headers) {
      config.headers["Authorization"] = "Bearer " + token; // token
    }
    if (config.method === "get") {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }
    // headers中配置serialize为true开启序列化
    if (config.method === "post" && config.headers.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }
    if (!isRepeatSubmit && (config.method === "post" || config.method === "put")) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === "object" ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      };
      const sessionObj = cache.session.getJSON("sessionObj");
      if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
        cache.session.setJSON("sessionObj", requestObj);
      } else {
        const s_url = sessionObj.url; // 请求地址
        const s_data = sessionObj.data; // 请求数据
        const s_time = sessionObj.time; // 请求时间
        const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = "数据正在处理，请勿重复提交";
          console.warn(`[${s_url}]: ` + message);
          return Promise.reject(new Error(message));
        } else {
          cache.session.setJSON("sessionObj", requestObj);
        }
      }
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (res: any) => {
    NProgress.done();
    // 未设置状态码则默认成功状态
    const code = Number(res.status) || 200;
    // 获取错误信息
    const msg = res.data.msg || errorCode[code] || errorCode["default"];
    // 二进制数据则直接返回
    // if (res.request.responseType === "blob" || res.request.responseType === "arraybuffer") {
    //   return res.data;
    // }
    if (code !== 200 || res.data.code === 1) {
      ElMessage({
        message: msg,
        type: "error"
      });
      return Promise.reject("error");
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error) => {
    NProgress.done();
    const status = error.response.status;
    const msg = error.response.data.msg;
    if (status === 424) {
      ElMessageBox.confirm("令牌状态已过期，请点击重新登录", "系统提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        store.dispatch("LogOut").then(() => {
          // 刷新登录页面，避免多次弹框
          window.location.reload();
        });
      });
      return Promise.reject(error);
    }

    // let { message } = error;
    // if (message === "Network Error") {
    //   message = "后端接口连接异常";
    // } else if (message.includes("timeout")) {
    //   message = "系统接口请求超时";
    // } else if (message.includes("Request failed with status code")) {
    ElMessage({
      message: msg,
      type: "error",
      duration: 5 * 1000
    });
    // }
    return Promise.reject(error);
  }
);

export default request;
