import Vue from 'vue'
import store from '@/store'
import { find } from 'lodash'
import types from './http.type'
import { notification } from 'ant-design-vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { server_code, interface_code } from './http.code'

// 用户认证信息 header 名
const Authorization = 'X-Access-Token'

/**
 * 请求拦截
 * @param {Object} config 请求配置
 * @author Matrix
 * @since 2022/06/26
 */
export const requestCommon = config => {
  const access_token = Vue.ls.get(ACCESS_TOKEN)
  if (access_token) config.headers[Authorization] = access_token
  if (config.method === 'get') {
    if (config.url.indexOf('sys/dict/getDictItems') < 0) {
      config.params = {
        ...config.params,
        _t: new Date().getTime()
      }
    }
  }
}

/**
 * 服务错误处理
 * @param {Object} err 错误信息
 * @author Matrix
 * @since 2022/06/26
 */
export const errorCommon = err => {
  const error = find(server_code.Error, { code: err.response.status })
  if (error && Object.keys(error).length > 0) {
    if (error.isRouter) {
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      })
    } else {
      notification[error.type]({
        message: error.title,
        description: error.message,
        duration: 4
      })
    }
  } else {
    notification.error({
      message: '系统提示',
      description: '未知错误，请联系管理员！',
      duration: 4
    })
  }
}

/**
 * 响应拦截
 * @param {Object} response 响应参数
 * @author Matrix
 * @since 2022/06/26
 */
export const responseCommon = response => {
  if (response.status === server_code.OK) {
    const code = String(response.data[types.code])
    if (code === interface_code.OK) {
      return Promise.resolve(response.data)
    } else {
      const isObject = Object.prototype.toString.call(response.data) === '[object Object]'
      if (isObject) {
        const error = find(interface_code.Error, { code: response.data[types.code] })
        const type = error?.type ?? 'warn'
        const title = error?.title ?? '系统警告'
        const message = (error?.message ?? response.data[types.message]) || '发生未知错误！'
        notification[type]({ message: title, description: message, duration: 4 })
        const isRouter = error?.isRouter
        if (isRouter) {
          store.dispatch('Logout').then(() => {
            if (window.__POWERED_BY_QIANKUN__) {
              window.location.href = process.env.VUE_APP_MAIN_PUBLIC_PATH
            } else {
              window.location.href = process.env.VUE_APP_PUBLIC_PATH
            }
          })
        } else {
          return Promise.reject(message)
        }
      } else {
        return Promise.resolve(response.data)
      }
    }
  }
}
