import Vue from "vue";
import axios from "axios";
import router from "@/router";
import qs from "qs";
import merge from "lodash/merge";
import { clearLoginInfo } from "@/utils";
import {
  encrypt,
  decrypt,
  urlSafeBase64Decode,
  urlSafeBase64Encode
} from "../utils/cryptojs";
var ifShangxian = 1; //1线上，0线下   /login页面还有一个验证码请求参加密

const http = axios.create({
  timeout: 1000 * 30,
  // withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});

/**
 * 请求拦截
 */
http.interceptors.request.use(
  config => {
    config.headers["token"] = Vue.cookie.get("token"); // 请求头带上token
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
  response => {
    if (response.data && response.data.code === 401) {
      // 401, token失效
      sessionStorage.clear();
      clearLoginInfo();
      router.push({ name: "login" });
    }

    if (ifShangxian == 1) {
      // console.log(response.data,'导出',response.data.type)
      if (response.data.type) {
      } else {
        const decryptData = decrypt(urlSafeBase64Decode(response.data));
        response.data = JSON.parse(decryptData);
      }
    }
    // console.log('解密',response.data)
    return 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
  // return 'http://iyfpk3.natappfree.cc/sqx_fast/' + actionName; // 开发
  // return 'https://www.daweilinli.com/sqx_fast/' + actionName

  // return 'http://192.168.161.190:8171/sqx_fast/' + actionName
  // return 'https://mxys.chuanghai-tech.com/sqx_fast/' + actionName; //  线上
  return "https://mxys.chuanghai-tech.com/wm-test/wm-api/sqx_fast/" + actionName;// 测试
};

http.adornUrl2 = actionName => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/tao/]前缀做代理拦截!
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/tao/' : window.SITE_CONFIG.baseUrl) + actionName
  return "/api" + actionName;
};
http.adornWss = actionName => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
  // return 'wss://www.daweilinli.com/wss/' + actionName
  // return 'wss://mxys.chuanghai-tech.com/wss/' + actionName
  return "wss://mxys.chuanghai-tech.com/wss-test/" + actionName;
};
/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = false) => {
  setTimeout(function() {
    // console.log(params,'gggg6')
  }, 1000);

  var defaults = {
    t: new Date().getTime()
  };
  if (ifShangxian == 1) {
    if (params) {
      // console.log(params,'gggg6')
      var arr = Object.entries(params); //对象转为数组
      var b = [];
      // console.log(arr,'j')
      arr.forEach((element, index) => {
        // console.log(element[1],index,element[1]==undefined)
        if (element[1] == undefined) {
          element[1] == "";
          arr[index][1] = urlSafeBase64Encode(encrypt(""));
        } else {
          arr[index][1] = urlSafeBase64Encode(encrypt(element[1].toString()));
        }
      });
      b = arr;
      // console.log(arr,'加密后的参数');

      var acc = Object.fromEntries(b); //数值还原
      // console.log(acc,'加密后的参数');
      var returnItem = openDefultParams ? merge(defaults, acc) : acc; //线上
      // console.log(urlSafeBase64Encode(encrypt('5564')),'gggg2')
      return returnItem;
      // return urlSafeBase64Encode(encrypt(returnItem.toString())) // **加密**
    } else {
      return openDefultParams ? merge(defaults, params) : params;
    }
  } else {
    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 = false, contentType = "json") => {
  var defaults = {
    t: new Date().getTime()
  };
  data = openDefultdata ? merge(defaults, data) : data;
  if (ifShangxian == 1) {
    if (data) {
      // console.log(data,'l')
      var returnItem =
        contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
      // console.log(urlSafeBase64Encode(encrypt(returnItem.toString())),'lo')
      return '"' + urlSafeBase64Encode(encrypt(returnItem.toString())) + '"'; // **加密**
    } else {
      return contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
    }
  } else {
    return contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
  }
};

export default http;
