import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
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 (config.url && /^\/api\/learn|^\/api\/meta/.test(config.url)) {
      // 默认参数
      const defaultHeaders = {
        timestamp: Date.now(),
        nonce: Math.random().toString(36).slice(-8),
        signature: 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
      }
      // config.headers = Object.assign(config.headers, defaultHeaders)
      config.params = Object.assign(config.params || {}, defaultHeaders)
    }

    if (config.headers?.['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data, { skipNulls: true })
    }
    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 === 4001) {
      location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      return Promise.reject(data)
    }
    if ([4008, 4011, 4012, 4013].includes(data.code)) {
      // 未授权
      router.push('/401')
      return Promise.reject(data)
    }

    if (Object.hasOwnProperty.call(data, 'code') && data.code !== 0 && data.code !== 200) {
      ElMessage.error(data.message || data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      } else if (status === 402) {
        // 未授权
        router.push('/401')
      } else {
        ElMessage.error(message)
        console.error(`${status}: ${message}`)
      }
    } else {
      console.log(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default httpRequest
