import axios from 'axios'
import { getToken } from '@/utils/auth'
import qs from 'qs'
import router from '@/router'
import { blobToJson } from '@/utils'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 120000 // request timeout
})

// request interceptor
// 发送请求拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = `Bearer ${getToken()}`
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
// 请求返回之后的拦截器
service.interceptors.response.use(
  async response => {
    const res = response.data

    if (response.request.responseType === 'blob') {
      // 返回的文件流当报错时转化成json
      if (response.headers['content-type'] === 'application/json') {
        try {
          const result = await blobToJson(res)
          return Promise.reject(result.msg)
        } catch (error) {
          return Promise.reject(error)
        }
      }
      const name = response.headers['content-disposition']

      return {
        data: res,
        name: name ? decodeURI(name.replace('attachment;filename=', '')) : '未命名'
      }
    }

    // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    if ([50008, 50012, 50014, 402000, 401].includes(res.code)) {
      router.push({ path: '/login-local' })
      return Promise.reject(res.message)
    }
    // 登录验证码过期
    if (res.code === 60902) {
      return Promise.reject(res)
    }
    if (res.code !== 200) {
      if (res.data && Object.keys(res.data)?.length) {
        return Promise.reject(res)
      }
      return Promise.reject(res.message)
    }
    return res
  },
  error => {
    return Promise.reject(error.message || error)
  }
)

// 请求方法
const http = {
  post (url, params, config = {}) {
    return service.post(url, params, {
      transformRequest: [(params) => {
        return JSON.stringify(params)
      }],
      headers: {
        'Content-Type': 'application/json'
      },
      ...config
    })
  },
  get (url, params) {
    return service.get(url, {
      params: params,
      paramsSerializer: (params) => {
        return qs.stringify(params)
      }
    })
  },
  put (url, params) {
    return service.put(url, {
      ...params
    })
  },
  del (url, params) {
    return service.delete(url, {
      params: params
    })
  },
  formData (url, params) {
    return service.post(url, params, {
      timeout: 600000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  upload (url, params) {
    return service.post(url, params, {
      timeout: 600000,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  download (url, params) {
    return service.post(url, params, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      },
      responseType: 'blob'
    })
  },
  getDownload (url, params) {
    return service.get(url, {
      params,
      timeout: 10000,
      responseType: 'blob'
    })
  }
}
export default http
