import axios, { AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'

// api路径
const API_URL: string = import.meta.env.VITE_APP_BASE_URL

const service: AxiosInstance = axios.create({
  timeout: 15000
})

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers = { 'Authorization': `${token}`, ...config.headers }
    }
    return config
  }
)

// 数据返回拦截
service.interceptors.response.use(
  res => {
    // 数据请求成功后 相应操作
    const responseData = res.data
    if (responseData.code !== 200) {
      if (responseData.hasOwnProperty('msg')) ElMessage.error(responseData.msg)
      else ElMessage.error(responseData.message)
    }
    return responseData
  },
  error => {
    // 数据请求失败后的相应操作
    const response = error.response;
    // 根据返回的code值来做不同的处理(和后端约定)
    switch (response.status) {
      case 401:
        if (response.data.code === 911) {
          window.location.href = "/#/login";
          sessionStorage.clear()
          return ElMessage.error('请重新登录')
        }
        ElMessage.error('错误请求')
        break;
      case 403:
        // 没有权限
        ElMessage.error('没有权限')
        break;
      case 500:
        // 服务端错误
        ElMessage.error('服务端错误(500)')
        break;
      case 503:
        // 服务端错误
        ElMessage.error('服务端错误(503)')
        break;
      default:
        ElMessage.error(`服务端错误${response.status}`)
        break;
    }
    return error
  }
)

interface ParamData {
  url: string;
  method?: 'post' | 'get' | 'delete' | 'put';
  data?: any;
  params?: any;
  headers?: any;
}

export function request(params: ParamData) {
  if (params.url.indexOf('http') === -1) {
    params.url = API_URL + params.url
  }

  return service(params)
}
