import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

const httpRequest = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    tenant: 'eec',
  },
})

// 请求拦截
httpRequest.interceptors.request.use(
  function (config) {
    if (config.url.includes('/api/cms')) {
      const defaultParams = {
        timestamp: parseInt(Date.now() / 1000),
        nonce: Math.random().toString(36).slice(-8),
      }
      // 接口请求参数
      let params = config.params || config.data
      // 排序
      const alphabeticalSort = (a, b) => {
        return a.localeCompare(b)
      }
      params = Object.assign({}, defaultParams, params)
      const str = qs.stringify(Object.assign({}, params, { salt: 'n7xAav2tSjn9Ysnr' }), { sort: alphabeticalSort })
      const strs = qs.parse(str)
      Object.keys(strs).map((item) => {
        strs[item] = Array.isArray(strs[item]) ? JSON.stringify(strs[item]) : strs[item]
      })
      params.signature = 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
      if (config.method === 'post') {
        config.data = params
      } else {
        config.params = params
      }
    }
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    if (config.headers['Content-Type'] === 'multipart/form-data') {
      const form = new window.FormData()
      for (const key in config.data) {
        form.append(key, config.data[key])
      }
      config.data = form
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { config, data } = response
    if (config.url.includes('/api/microservices') && data.code !== 200) {
      Message.error(data.message || data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { message } = error.response.data
      Message.error(message || error.response.data)
      return Promise.reject(error.response)
    } else {
      Message.error(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
