import axios from 'axios'
//import { message } from 'ant-design-vue'
import router from '@/router/index'
import { getCache } from './authority';
import config from './config';
import SM2 from './sm2';
import { getUrlParams } from './tools';
import { useTokenStore } from '@/stores/token';

// 创建实例时配置默认值
const httpInstance = axios.create({
  baseURL: '/operate',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  transformRequest: function transformRequest(data, headers) {
	const hasJSONContentType = () => {
	  const contentType = (headers && headers['Content-Type']) || '';
	  return contentType.indexOf('application/json') > -1;
	};
	if (typeof data === 'string' && hasJSONContentType()) {
	  return data;
	}
	axios.defaults.transformRequest.forEach((tr) => tr(data, headers));
  }
})

// 添加请求拦截器
httpInstance.interceptors.request.use(
  function (axconfig) {
	axconfig.headers['content-type'] = 'application/json';
	const tokenStore = useTokenStore();
    const hasToken = tokenStore.token.value || getCache('ebike-token');
    const { url, method, data } = axconfig;
    if(!url.includes("/auth/loginByPwd")){
      if (hasToken) {
        axconfig.headers['Authorization'] = hasToken;
      }
    }
    let endata = null;
    let nurl = null;
	if (method.toLowerCase() == "get") {
		if (url.includes("?")) {
			nurl = url.substring(0, url.indexOf("?") + 1);
			var params = getUrlParams(url);
			for (const key in params) {
				let keyData = params[key];
				if (params.hasOwnProperty(key)) {
					if (nurl.toLowerCase().endsWith("?")) {
						nurl += key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
					} else {
						nurl += "&" + key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
					}
				}
			}
		} else {
			if (Object.keys(data).length > 0) {
				nurl = url + "?";
			}
			else
			{
				nurl = url;
			}
			Object.keys(data).forEach((key) => {
				let keyData = data[key];
				if (data.hasOwnProperty(key)) {
					if (nurl.toLowerCase().endsWith("?")) {
						nurl += key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
					} else {
						nurl += "&" + key + "=" + SM2.sm2Encrypt(keyData, config.sm2PublicKey);
					}
				}
			});
		}
	} else {
		if (data["content-type"]) {
			if (data["content-type"] == "application/x-www-form-urlencoded") {
				axconfig.headers['content-type'] = 'application/x-www-form-urlencoded';
				let formData = new Formdata();
				Object.keys(data).forEach((key) => {
					if (key.toLowerCase() == "content-type") return false;
					let enKeyData = SM2.sm2Encrypt(data[key], config.sm2PublicKey)
					formData.append(key, enKeyData);
				});
				endata = formData;
			}
		} else {
			endata = SM2.sm2Encrypt(JSON.stringify(data), config.sm2PublicKey);
		}
	}
    axconfig.url = nurl || url;
    axconfig.data = endata || data;
    return axconfig;
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
httpInstance.interceptors.response.use(
  (res) => {
    //统一错误提示
    //token失效
    const { data: response } = res || {}
    if (response?.error && response?.error === 'Token has expired') {
      router.push('/login')
      return
    }
    return res?.data
  },
  function (error) {
    // //统一错误提示
    console.log('errRes', error)
    return Promise.reject(error)
  }
)

//导出axios实例
export default httpInstance
