/*
 * @author: ym
 * @Date: 2021-09-28 10:53:53
 * @LastEditTime: 2022-09-02 22:56:48
 * @LastEditors: chenkangxu
 * @Description:
 * @FilePath: \background-front-end\src\utils\httpRequest.js
 */
import Vue from "vue";
import axios from "axios";
import router from "@/router";
import qs from "qs";
import merge from "lodash/merge";
import { Message } from "element-ui";
import { clearLoginInfo } from "@/utils";
import commonUtil from "./common";
import des from "./des.js";

const http = axios.create({
  baseURL:
    process.env.NODE_ENV !== "production" && process.env.OPEN_PROXY
      ? "/proxyApi/"
      : window.SITE_CONFIG.baseUrl_USER,
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});

/**
 * 请求拦截
 */
http.interceptors.request.use(
  config => {
    config.headers["Authorization"] ="Bearer "+Vue.cookie.get("token"); // 请求头带上token
    // 针对post请求加密
    if (config.method.toLowerCase() === "post"/* && process.env.NODE_ENV === "production" */) {
      //如果已经转成字符串了，就不用再转了
      if (typeof config.data === "string") {
        config.data = des.encryptByDES(config.data, "u48rE-RlGbua_K_m$*#z99lt");
      } else {
        //否则要转一次
        config.data = des.encryptByDES(
          JSON.stringify(config.data),
          "u48rE-RlGbua_K_m$*#z99lt"
        );
      }
    }
    if (process.env.NODE_ENV !== "production") {
      console.log(`【请求】${config.url}`, config);
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// /**
//  * 响应拦截
//  */
// http.interceptors.response.use(response => {
//   console.log(`【响应】${response.config.url}`, response);
//   if (response.data) {
//     switch (response.data.code) {
//       case 0:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: 'success'
//         });
//         break;
//       case 401:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         clearLoginInfo()
//         router.push({
//           name: 'login'
//         });
//         break;
//       case 403:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 404:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 408:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 500:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 501:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 502:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 503:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       case 504:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//         break;
//       default:
//         commonUtil.showMessage({
//           message: response.data.msg,
//           type: "error"
//         });
//     }
//   }
//   return response
// }, error => {
//   return Promise.reject(error)
// })

/**
 * 响应拦截
 */
http.interceptors.response.use(
  response => {
    //开发环境下才可以打印日志
    if (process.env.NODE_ENV !== "production") {
      console.log(`【响应】${response.config.url}`, response);
    }
    if (response.data && response.data.code === 401) {
      // 401, token失效
      clearLoginInfo();
      router.push({ name: "login" });
      return Promise.resolve(response);
    } else if (response.data && response.data.code === 500) {
      Message.closeAll();
      Message({
        message: response.data.msg,
        type: "error"
      });
      return Promise.reject(response);
    } else {
      //请求成功的情况
      //如果是开发模式下，都要弹出
      if (process.env.NODE_ENV !== "production") {
        Message.closeAll();
        Message({
          message: response.data.msg,
          type: "success"
        });
      }
      // 生产环境下限制性弹出
      else {
        if (response.data.msg != "success" && response.data.msg != "查询成功" && Object.prototype.toString.call(response.data) === '[object Object]') {
          Message.closeAll();
          Message({
            message: response.data.msg,
            type: "success"
          });
        }
      }
      return Promise.resolve(response);
    }
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = actionName => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return (
    (process.env.NODE_ENV !== "production" && process.env.OPEN_PROXY
      ? "/proxyApi/"
      : window.SITE_CONFIG.baseUrl) + actionName
  );
};

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    t: new Date().getTime()
  };
  return openDefultParams ? merge(defaults, params) : params;
};

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = "json") => {
  var defaults = {
    t: new Date().getTime()
  };
  data = openDefultdata ? merge(defaults, data) : data;
  return contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
};

export default http;
