import axios from "axios"
import {
  contentType,
  invalidCode,
  messageDuration,
  noPermissionCode,
  requestTimeout,
  successCode,
  tokenName,
  debounce,
} from "@/config/settings"
import { Loading, Message, MessageBox } from "element-ui"
import store from "@/store"
import qs from "qs"
import router from "@/router"
import _ from "lodash"
// 'http://192.168.1.150:12999/'
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === "development"
      ? "/api"
      : process.env.VUE_APP_BASE_API,
  timeout: requestTimeout,
  headers: {
    "Content-Type": contentType,
  },
})
const whiteUrl = [
  "oauth/token", //获取token
  "/disease-data/tj", // 同济患者信息
  "/cloud-upms/dict/batch/type", //字典
  "/cloud-auth/mobile/token/social", //单点登录
]
let loadingInstance
service.interceptors.request.use(
  (config) => {
    if (
      store.getters["user/accessToken"] &&
      !whiteUrl.find((url) => config.url.includes(url))
    ) {
      config.headers[
        "Authorization"
      ] = `Bearer ${store.getters["user/accessToken"]}`
    }
    if (config.data) {
      // config.data = _.pickBy(config.data, _.identity);
    }
    if (process.env.NODE_ENV !== "test") {
      if (contentType === "application/x-www-form-urlencoded;charset=UTF-8") {
        if (config.data && !config.data.param) {
          config.data = qs.stringify(config.data)
        }
      }
    }
    const needLoading = () => {
      let status = false
      debounce.forEach((item) => {
        if (_.includes(config.url, item)) {
          status = true
        }
      })
      return status
    }
    if (needLoading()) {
      loadingInstance = Loading.service()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

const errorMsg = (message) => {
  return Message({
    message: message,
    type: "error",
    duration: messageDuration,
  })
}

service.interceptors.response.use(
  (response) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    const { status, data, config, type } = response
    const { code, msg, access_token } = data
    const isExcelExport = config.responseType === "blob" //是否导出excel
    if (code !== successCode && !access_token && !isExcelExport) {
      switch (code) {
        case invalidCode:
          errorMsg(msg || `后端接口${code}异常`)
          store.dispatch("user/resetAccessToken")
          break
        case noPermissionCode:
          errorMsg(msg || `暂无权限`)
          router.push({
            path: "/401",
          })
          break
        default:
          errorMsg(msg || `后端接口${code}异常`)
          break
      }
      return Promise.reject(
        JSON.stringify({
          url: config.url,
          code,
          msg,
        }) || "Error"
      )
    } else {
      return data
    }
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    /*网络连接过程异常处理*/
    let response = error.response
    let status = response?.status
    if (status === 401) {
      errorMsg("权限过期，请重新登录")
      store.dispatch("user/resetAccessToken").then(() => {
        // location.reload()
        router.push({
          path: "/home",
        })
      })
      return Promise.reject(error)
    }
    if (response) {
      let errs = ""
      switch (status) {
        case 400:
          errs = "错误请求"
          break
        case 401:
          errs = "未授权，请重新登录"
          break
        case 403:
          errs = "拒绝访问"
          break
        case 404:
          errs = "请求错误,未找到该资源"
          break
        case 405:
          errs = "请求方法未允许"
          break
        case 408:
          errs = "请求超时"
          break
        case 409:
          errs = "服务器在完成请求时发生冲突"
          break
        case 410:
          errs = "请求的资源已被永久删除"
          break
        case 411:
          errs = "需要有效长度"
          break
        case 413:
          errs = "请求实体过大"
          break
        case 414:
          errs = "请求的 URI 过长"
          break
        case 415:
          errs = "不支持的媒体类型"
          break
        case 500:
          errs = navigator.onLine ? "服务器端出错" : "未连接网络，请稍后再试"
          break
        case 501:
          errs = "网络未实现"
          break
        case 502:
          errs = "网络错误"
          break
        case 503:
          errs = "服务不可用"
          break
        case 504:
          errs = "网络超时"
          break
        case 505:
          errs = "http版本不支持该请求"
          break
        default:
          errs = `连接错误${error.response.status}`
      }
      errs = (response.data && response.data.msg) || errs
      errorMsg(errs)
      error.message = errs
    } else {
      let msg = "连接到服务器失败"
      if (!navigator.onLine) {
        msg = "未连接网络，请稍后再试"
        MessageBox.confirm("未连接网络，请稍后再试", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          showCancelButton: true,
        }).then(() => {})
      }
      errorMsg(msg)
      error.message = msg
    }
    return Promise.reject(error)
  }
)
export default service
