import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useAppConfig } from '@/composables/useAppConfig'
const appConfig = useAppConfig()

const httpRequest = axios.create({
  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\/[meta|msg]/.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)
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { data } = response
    // 未登录
    if (data.code === 4001) {
      location.href = `${appConfig.loginURL || import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      return Promise.reject(data)
    }
    if (data.code === 1) {
      ElMessage.error(data.message || data.msg)
      return Promise.reject(data)
    }
    if (import.meta.env.VITE_STATIC_URL) {
      try {
        const regex = /(http|https):\/\/(.*?)saas-lab-api/gi
        return JSON.parse(JSON.stringify(data).replaceAll(regex, import.meta.env.VITE_STATIC_URL))
      } catch (error) {
        console.log(error)
      }
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        location.href = `${appConfig.loginURL || import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      } else if (status === 401 || 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
