// 引用axios
import axios from 'axios'
import { h } from 'vue'
import { ElLink, ElMessage, ElMessageBox } from 'element-plus'
import { SuccessResultCode, SystemFailResultCode, WarningResultCode } from '@cacp/ui'
import config from '@/config'
import { noAuth } from './authhelper'

const JWT_KEY = 'x-customs-jwt'

const Axios = axios.create({
  // API 请求的默认前缀
  baseURL: `${config.SERVICE_API}`,
  timeout: config.SERVICE_TIMEOUT, // 请求超时时间
  withCredentials: true, // 自动携带cookie
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'x-auth-mode': config.AUTH_MODE ?? 'JWT'
  }
})

// 请求拦截
Axios.interceptors.request.use(
  (req) => {
    // 头部如需带上token,在此处配置
    if (!config.AUTH_MODE || config.AUTH_MODE === 'JWT') {
      req.headers.set(JWT_KEY, sessionStorage.getItem(JWT_KEY))
    }
    return req
  },
  (err) => {
    ElMessage.error({ message: err.message, duration: 0, showClose: true })
    return Promise.reject(err)
  }
)

// 响应拦截
Axios.interceptors.response.use(
  (res) => {
    if (res.headers[JWT_KEY]) {
      if (res.headers[JWT_KEY] === 'CLEAN') {
        sessionStorage.removeItem(JWT_KEY)
      } else {
        sessionStorage.setItem(JWT_KEY, res.headers[JWT_KEY])
      }
    }
    const contentType = res.headers['content-type']
    if (typeof contentType === 'string' && contentType.startsWith('application/json')) {
      // 只处理后端返回Resut<T>JSON对象时的错误提示，其他格式原样返回（例如：mime是未知文件流下载或已知文件等类型 ）
      if (res.data && (res.data.code != SuccessResultCode || res.data.code != WarningResultCode) && res.data.message) {
        ElMessage.error({
          message: res.data.message,
          duration: 0,
          showClose: true
        })
      }
    }
    return res
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      const { code, additionalMessage } = err.response.data
      // console.log(code, additionalMessage, err)
      noAuth(code, additionalMessage)
      return
    }

    if (err.response && err.response.data) {
      const msg = err.response.data.message ?? '网络异常'
      ElMessage.error({
        message: h('div', [
          msg,
          h(
            ElLink,
            {
              type: 'danger',
              style: 'margin-left:12px',
              onClick: () => {
                ElMessageBox({
                  title: msg,
                  message: () =>
                    h('div', { style: 'white-space:normal;word-break:break-word;' }, JSON.stringify(err.response.data)),
                  customClass: 'cacp-request-message-box',
                  showConfirmButton: false
                }).catch(() => {})
              }
            },
            () => '详情'
          )
        ]),
        duration: 0,
        showClose: true
      })
      return {
        data: {
          code: SystemFailResultCode,
          data: err.response.data,
          message: msg
        }
      }
    }

    ElMessage.error({
      message: err.message || '网络异常，请稍后重试！',
      duration: 0,
      showClose: true
    })
    return {
      data: { code: SystemFailResultCode, data: null, message: err.message }
    }
  }
)

export default Axios
