// axios二次封装
import axios from "axios"; // 引入 axios
// import baseUrl from "./env"; // 基础url
import Vue from "vue";
import code from "./state_code"; // 状态码维护
import store from "@/store";
let that = new Vue();
const service = axios.create({
  validateStatus(status) {
    return status >= 200 && status <= 504; // 合法状态码
  },
  baseURL: process.env.VUE_APP_API, // 基础请求路径
  timeout: 10000, // 请求超时
});
// 重复尝试此时
service.defaults.retry = 3;
// 重试延时
service.defaults.retryDelay = 15000;
// 开启重试
service.defaults.shouldRetry = true;
// 请求拦截
service.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["Accept-Language"] = "zh-CN";
    // token
    config.headers["Authorization"] = store.state.common.token;
    if (config.method === "post") {
      if (!config.data) {
        config.data = {};
      }
    }
    console.log(config);
    return config;
  },
  (error) => {
    const {
      response: { status, statusText },
    } = error;
    that.$msg.error({
      message: status,
      description: statusText,
    });
  }
);
// response 拦截器
service.interceptors.response.use(
  (response) => {
    return new Promise((resolve, reject) => {
      if (response.status !== 200) {
        // 请求失败
        reject(response);
      } else {
        const { returnCode, returnMsg } = response.data || {};
        // 判断token有效
        const TOKENSTATE = code.TOKEN_INVLIDE_TO_LOGIN(returnCode);
        // 全局错误拦截
        const PUBSTATE = code.PUB_ERR(returnCode, returnMsg, response.config);
        // 请求成功，但逻辑或者业务有错，返回具体数据，根据业务决定是否要提示 有token失效全局异常不返回
        if (TOKENSTATE && PUBSTATE) {
          resolve(response.data);
        }
      }
    }).catch(() => {
      console.log("that?", response);
      that.$msg.error({
        message: response.config.url,
        description: response.status + " : " + response.statusText,
      });
    });
  },
  (err) => {
    // 失败
    let message = "请求异常,请检测网络!";
    if (err.response) {
      message = err.response.data.message;
    }
    that.$msg.error({
      message: message,
      description: err,
    });
  }
);

export default service;
