import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 1115000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    // console.log('userStore.token',userStore.token)
    if (userStore.token) {
      config.headers['Token'] = `${userStore.token}`
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 这里可以根据后端的数据结构进行调整
    if (res.code === 200||res.code === 0) {
      return res
    } else {
      const userStore = useUserStore()
      if (res.code) {
        switch (res.code) {
          case 401:
            ElMessage.error(res.msg || '登录已过期，请重新登录')
            userStore.logout()
            // 跳转到登录页
            window.location.href = '/login'
            break
          case 403:
            ElMessage.error(res.msg || '没有权限访问')
            break
          case 404:
            ElMessage.error(res.msg || '请求的资源不存在')
            break
          case 500:
            ElMessage.error(res.msg || '服务器错误')
            break
          default:
            ElMessage.error(res.msg)
        }
      }
      // ElMessage.error(res.message || '请求失败')
      // return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    console.error('响应错误：', error)
    const userStore = useUserStore()
    
    if (error.response) {
      console.log('error.response',error.response);
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          userStore.logout()
          // 跳转到登录页
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          ElMessage.error(error.msg)
      }
    }
    
    return Promise.reject(error)
  }
)

// 封装GET请求
export function get(url, params) {
  return service({
    url,
    method: 'get',
    params
  })
}

// 封装POST请求
export function post(url, data, config = {}) {
  return service({
    url,
    method: 'post',
    data,
    ...config
  })
}

// 封装PUT请求
export function put(url, data) {
  return service({
    url,
    method: 'put',
    data
  })
}

// 封装DELETE请求
export function del(url, params) {
  return service({
    url,
    method: 'delete',
    params
  })
}

export default service 