import axios from 'axios'
import { Loading, Message } from 'element-ui'
import { getItem } from '@/utils/index'
import { isCheckTimeout } from '@/utils/auth'
import store from '@/store'

const pendingMap = new Map()

const loadingInstance = {
  target: null,
  count: 0
}

const myAxios = (axiosConfig, scustomOptions, loadingOptions) => {
  const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 1000000
  })

  // 自定义配置
  let customOptions = Object.assign(
    {
      repeatRequestCancel: true, // 是否开启取消重复请求, 默认为 true
      loading: false, // 是否开启loading层效果, 默认为false
      reductDataFormat: true, // 是否开启简洁的数据结构响应, 默认为true
      errorMessageShow: true, // 是否开启接口错误信息展示,默认为true
      codeMessageShow: true // 是否开启code不为0时的信息提示, 默认为false
    },
    scustomOptions
  )

  // 请求拦截
  service.interceptors.request.use(
    (config) => {
      removePending(config)
      customOptions.repeatRequestCancel && addPending(config)
      // 创建loading实例
      if (customOptions.loading) {
        loadingInstance.count++
        if (loadingInstance.count === 1) {
          loadingInstance.target = Loading.service(loadingOptions)
        }
      }
      // 自动携带token
      if (getItem('token')) {
        // 主动处理登录超时
        if (isCheckTimeout()) {
          store.dispatch('user/loginOut')
          Message({
            type: 'error',
            message: '登录超时'
          })
        }
        config.headers.Authorization = getItem('token')
      }

      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截
  service.interceptors.response.use(
    (response) => {
      removePending(response.config)
      customOptions.loading && closeLoading(customOptions) // 关闭loading
      // 处理流文件
      if (response.request.responseType == 'blob') {
        const { data, status, headers } = response
        return { data, headers }
      }

      if (customOptions.codeMessageShow && response.data && response.data.code != 200) {
        Message({
          type: 'error',
          message: response.data.message || response.data.msg
        })
        if (response.data.code == 401) {
          store.dispatch('user/loginOut')
        }
        return Promise.reject(response.data) // code不等于200, 页面具体逻辑就不执行了
      }

      return customOptions.reductDataFormat ? response.data : response
    },
    (error) => {
      error.config && removePending(error.config)
      customOptions.loading && closeLoading(customOptions) // 关闭loading
      customOptions.errorMessageShow && httpErrorStatusHandle(error) // 处理错误状态码
      return Promise.reject(error)
    }
  )

  return service(axiosConfig)
}

export default myAxios

/**
 * 处理异常
 * @param {*} error
 */
const httpErrorStatusHandle = (error) => {
  const {
    message,
    msg,
    response: { status, statusText }
  } = error
  // 处理被取消的请求
  if (axios.isCancel(error)) {
    return console.error('请求的重复请求：' + error.message || error.msg)
  }

  let strMessage = ''
  if (error && error.response) {
    switch (status) {
      case 302:
        strMessage = '接口重定向了！'
        break
      case 400:
        strMessage = '参数不正确！'
        break
      case 401:
        strMessage = '您未登录，或者登录已经超时，请先登录！'
        store.dispatch('user/loginOut')
        break
      case 403:
        strMessage = '您没有权限操作！'
        break
      case 404:
        strMessage = `请求地址出错: ${error.response.config.url}`
        break // 在正确域名下
      case 408:
        strMessage = '请求超时！'
        break
      case 409:
        strMessage = '系统已存在相同数据！'
        break
      case 500:
        strMessage = '服务器内部错误！'
        break
      case 501:
        strMessage = '服务未实现！'
        break
      case 502:
        strMessage = '网关错误！'
        break
      case 503:
        strMessage = '服务不可用！'
        break
      case 504:
        strMessage = '服务暂时无法访问，请稍后再试！'
        break
      case 505:
        strMessage = 'HTTP版本不受支持！'
        break
      case 520:
        strMessage = statusText
        break
      default:
        strMessage = '异常问题，请联系管理员！'
        break
    }
  }

  if ((msg && msg.includes('timeout')) || (message && message.includes('timeout'))) {
    strMessage = '网络请求超时！'
  }
  if ((msg && msg.includes('Network')) || (message && message.includes('Network'))) {
    strMessage = window.navigator.onLine ? '服务端异常！' : '您断网了！'
  }

  Message({
    type: 'error',
    message: strMessage
  })
}

/**
 * 关闭Loading层实例
 * @param {*} options
 */
const closeLoading = (options) => {
  if (options.loading && loadingInstance.count > 0) loadingInstance.count--
  if (loadingInstance.count === 0) {
    loadingInstance.target.close()
    loadingInstance.target = null
  }
}

/**
 * 储存每个请求的唯一cancel回调, 以此为标识
 * @param {*} config
 */
const addPending = (config) => {
  const pendingKey = getPendingKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingMap.has(pendingKey)) {
        pendingMap.set(pendingKey, cancel)
      }
    })
}

/**
 * 删除重复的请求
 * @param {*} config
 */
const removePending = (config) => {
  const pendingKey = getPendingKey(config)
  if (pendingMap.has(pendingKey)) {
    const cancelToken = pendingMap.get(pendingKey)
    // cancelToken(pendingKey)
    pendingMap.delete(pendingKey)
  }
}

const getPendingKey = (config) => {
  let { url, method, params, data } = config
  if (typeof data === 'string' && data.indexOf('}') != -1) {
    data = JSON.parse(data) // response 里面返回的config.data是个字符串对象
  }
  return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
}
