import axios from 'axios'
// import queryString from 'query-string'
import qs from 'qs'
import { Message } from 'element-ui'
import router from '../router'

const httpRequest = axios.create({
  timeout: 60000,
  withCredentials: true,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function (config) {
    // 权限接口单独签名
    // https://gitlab.ezijing.com/root/api-documents/-/blob/master/ezijing_permissions/%E7%AD%BE%E5%90%8D%E9%AA%8C%E8%AF%81.md
    if (/^\/api\/permissions/.test(config.url)) {
      // 默认参数
      const defaultHeaders = {
        timestamp: parseInt(Date.now() / 1000),
        nonce: Math.random().toString(36).slice(-8),
        'secret-id': import.meta.env.VITE_SECRET_ID,
        'secret-key': import.meta.env.VITE_SECRET_KEY,
        signature: 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
      }
      config.headers = Object.assign(config.headers, defaultHeaders)
    }

    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 formData = new window.FormData()
      for (const key in config.data) {
        formData.append(key, config.data[key])
      }
      config.data = formData
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { data } = response
    // 正常返回
    if (data.code === 0 || !Object.keys(data).includes('code')) {
      return data
    }
    // 未登录
    if (data.code === 4001) {
      window.location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(window.location.href)}`
    }
    // 没有权限
    if (data.code === 4008) {
      router.push('/401')
    }
    Message({ message: data.message, type: 'error' })
    return Promise.reject(data)
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        window.location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(window.location.href)}`
      } else {
        Message.error(message || error.response.data)
      }
      return Promise.reject(error.response)
    } else {
      console.log(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
