import axios, { type AxiosRequestConfig } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTenantStore } from '@/stores/tenant'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '/api',
  timeout: 180000
})

service.interceptors.request.use(
  (config) => {
    const tenantStore = useTenantStore()
    if (tenantStore.currentTenantId) {
      config.headers['X-Tenant-Id'] = tenantStore.currentTenantId
    }
    const apiKey = import.meta.env.VITE_APP_API_KEY
    if (apiKey) {
      config.headers['X-API-Key'] = apiKey
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    return res
  },
  (error) => {
    console.log('err' + error)
    let { message, response } = error
    if (response) {
      const status = response.status
      if (status === 401) {
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.href = '/login'
        })
      } else if (status === 403) {
        ElMessage({
          message: '当前操作无权限',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        ElMessage({
          message: message || '后端接口未知异常',
          type: 'error',
          duration: 5 * 1000
        })
      }
    } else {
      ElMessage({
        message: '网络连接异常',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

interface RequestConfig extends AxiosRequestConfig {
  url: string
  method?: string
}

function request<T = any>(config: RequestConfig): Promise<T> {
  return service.request<any, T>(config)
}

export default request
