import axios from 'axios'
import Message from 'ant-design-vue/es/message/index'
// import loginApi from './login'
// import { logout } from '@/util/logout'

axios.defaults.withCredentials = true

// const baseUrl = '/api/'
const baseUrl = '/api/feature/'

// let requestQueen = []
// let canRequest = true

export default function ajax(firstUrl, data = {}, type = 'GET', header = {}) {
  return new Promise((resolve, reject) => {
    let option = {}
    let url = baseUrl + firstUrl
    let homeHeader = { Authorization: `Bearer ${sessionStorage.getItem('access_token')}` } // 除登录外的header
    let headers = Object.assign(homeHeader, header)
    if (['POST', 'PUT', 'PATCH', 'FORM_POST', 'FORM_PUT'].includes(type.toUpperCase())) {
      option = {
        url,
        method: type.toUpperCase(),
        headers,
        data
      }
    } else if (['GET', 'DELETE'].includes(type.toUpperCase())) {
      option = {
        url,
        method: type.toUpperCase(),
        params: data,
        headers
      }
    }
    axios(option).then((res) => {
      if (res.status === 200) {
        const status = res.data.code
        switch (status) {
          case 0:
            break
          case 4001: // token失效
            // 如果请求是4001，直接加入请求缓存队列，通过回调函数保存当前resolve
            // requestQueen.push(() => {
            //   resolve(ajax(firstUrl, data, type, header))
            // })
            // if (canRequest) { // 如果是可以请求，也就是说当前是第一个4001返回的请求
            //   canRequest = false // 设置不能继续请求
            //   if (sessionStorage.getItem('refresh_token')) { // 判断有无refresh_token，有的话就去刷新token
            //     loginApi.refreshToken().then(async res => {
            //       canRequest = true
            //       if (res.code === 2000) { // 刷新token成功
            //         for (let i of requestQueen) { // 成功后将队列全部重试
            //           await i()
            //         }
            //       } else { // 刷新token不成功
            //         Message.error('登录过期, 请重新登录')
            //         // logout()
            //       }
            //       requestQueen = [] // 无论成功与否，清空请求队列
            //     })
            //   } else { // 因为某些原因丢失了refresh_token,直接退出
            //     Message.error('登录过期, 请重新登录')
            //     // logout()
            //   }
            // }
            break
          case 4000:
            console.log(`${url}Bad Request`)
            Message.error('Bad Request')
            break
          case 4003:
            console.log(`${url}禁止访问`)
            Message.error('禁止访问')
            break
          case 4004:
            console.log(`${url}资源未找到`)
            Message.error('资源未找到')
            break
          case 4005:
            Message.error(`${url}接口不支持${type}方式请求`)
            break
          case 5000:
            console.log(`${url}接口业务异常`)
            break
          case -1:
            console.log(`${url}接口系统错误`)
            Message.error(`${url}接口系统错误`)
            break
          default:
            console.log('未知错误')
            break
        }
        if (status !== 4001) {
          resolve(res.data)
        }
      } else {
        reject(res)
      }
    })
      .catch((error) => {
        if (error.response) {
          Message.error(`http错误, ${error.response.status},${error.response.statusText}`)
          console.log('http错误', error)
          console.log('url', option.url)
        } else {
          Message.error(`未知http错误, ${error.message}`)
          console.log('http错误', error)
          console.log('url', error.config.url)
        }
        reject(error)
      })
  })
}
