import {
  AxiosConfig,
  AxiosResponse,
  AxiosRequestHeaders,
  InternalAxiosRequestConfig
} from './types'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import Cookies from 'js-cookie'

const config: AxiosConfig = {
  /**
   * api请求基础路径
   */
  baseUrl: {
    // 开发环境接口前缀
    // base: '',
    base: '/api',

    // 打包生产环境接口前缀
    dev: '/pro',
    // dev: '/ordb',

    // 打包生产环境接口前缀
    pro: '/pro',

    // 打包测试环境接口前缀
    test: ''
  },

  /**
   * 接口成功返回状态码
   */
  code: 0,

  /**
   * 接口成功返回状态码
   */
  status: 200,

  /**
   * 接口请求超时时间
   */
  timeout: 60000,

  /**
   * 默认接口请求类型
   * 可选值：application/x-www-form-urlencoded multipart/form-data application/json
   */
  defaultHeaders: 'multipart/form-data',

  interceptors: {
    //请求拦截
    // requestInterceptors: (config) => {
    //   return config
    // },
    // 响应拦截器
    // responseInterceptors: (result: AxiosResponse) => {
    //   return result
    // }
  }
}

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    (config.headers as AxiosRequestHeaders)['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  }
  if (
    config.method === 'post' &&
    config.data &&
    (config.headers as AxiosRequestHeaders)['Content-Type'] === 'application/json'
  ) {
    // JSON请求格式
    config.data = {
      head: {},
      env: {},
      body: config.data
    }
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  config.headers.set('Authorization', Cookies.get(ACCESS_TOKEN))
  return config
}

const statusDesc = {
  403: '服务器拒绝执行此请求[403]',
  404: '您访问的链接丢失了[404]',
  405: '请求的方法不被允许[405]',
  408: '服务器等待请求已超时[408]',
  500: '系统内部发生错误[500]',
  501: '服务器不支持此请求[501]',
  504: '网关超时[504]',
  502: '服务器接收响应无效[502]',
  600: '系统内部发生错误[600]'
}

const defaultResponseInterceptors = (response: AxiosResponse<any>) => {
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (response.data.code === config.code) {
    return response.data
  } else if (response.status === config.status) {
    if (response.status === 200 && response?.data?.head) {
      const status = +response.data.head.status
      const msg = response.data.head.msg || '未知错误'
      // const data = response.data.head.info ;
      // if (data.message) {
      //     Message(data.message);
      //     return Promise.reject(data.message);
      // }
      if (status === 200) {
        return response.data
      } else if (status === 401) {
        ElMessage.error('登录过期,请重新登录')
        window.location.hash = '/login'
        return Promise.reject('登录过期,请重新登录')
      } else if (status === 404) {
        ElMessage.error('接口404报错')
        return Promise.reject('接口404报错')
      } else if (status === 500) {
        return Promise.reject({ title: msg, errorMsg: response.data.head.info })
      } else if (statusDesc[status]) {
        return Promise.reject(statusDesc[status])
      }
      return Promise.reject('未知错误')
    }
    // 存在json时返回body
    // if (response?.data?.body) {
    //   return response.data
    // } else {
    //   return response
    // }
  } else {
    ElMessage.error((response as any).message || (response as any).msg)
  }
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
export const ACCESS_TOKEN = 'SESSION'
export default config
