/* eslint-disable */
import axios, { AxiosInstance } from 'axios'
import qs from 'qs'
import router from '@/router'
import { getCache, delCache } from '@/utils'
import { storeToRefs } from 'pinia'
import { globalStore, userStore } from '@/stores'
import hud from '@/utils/hud'
import onlyLast from './only-last'
import sass from '@/utils/sass'

// let controller = new AbortController()
const timeout = 90000
const instance: AxiosInstance = axios.create({
  baseURL: '/api/main',
  method: 'get',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout,
})

/**
 * 处理请求头
 */
instance.interceptors.request.use(
  (config: any) => {
    config.baseURL = config.baseURL || '/api/main'
    config.timeout = config.timeout || timeout
    if (config.method === 'get') {
      config.paramsSerializer = {
        serialize: function (params: any) {
          return qs.stringify(params, {
            arrayFormat: 'repeat',
            allowDots: true,
          })
        },
      }
    }
    onlyLast.processRequest(config)

    // 租户id
    config.headers['X-Tenant-Id'] = sass.platform.tenantId

    // 自定义token
    if (config.headers['Authorization'] || config.headers['Authorization'] === '') {
      return config
    }

    if (config.baseURL === '/api/campus') {
      config.headers['Authorization'] = getCache('workToken')
    } else {
      config.headers['Authorization'] = getCache('token')
    }
    return config
  },
  error => Promise.reject(error),
)

const buildError = (response: any, show = true) => {
  const {
    data: { message, msg },
  } = response

  let errorMsg = message || msg
  let showed = false
  if (errorMsg) {
    if (errorMsg.includes('服务器')) {
      errorMsg = '网络不稳定，请稍后再试~'
    }
    // if (traceId) {
    //   errorMsg = `${errorMsg}[${traceId}]`
    // }
    if (show) {
      hud.error(errorMsg)
      showed = true
    }
  }
  if (errorMsg?.includes('非本平台用户')) {
    // 重新登录

    delCache('token')
    delCache('workToken')
    router.replace('/login')
  }
  return {
    message: errorMsg,
    showed,
  }
}

/**
 * 拦截器
 */
instance.interceptors.response.use(
  response => {
    const {
      data: { code, message },
    } = response
    if (!onlyLast.processResponse(response.config)) {
      // 过滤请求
      return Promise.reject(response)
    }

    // 文件流不拦截
    if (response.headers['content-type']?.indexOf('octet-stream') !== -1 || code == 200)
      return response

    return Promise.reject(buildError(response))
  },
  async error => {
    const { response } = error

    if (!onlyLast.processResponse(error.config)) {
      // 过滤请求
      return Promise.reject(error)
    }

    if (response?.status === 401 || response?.status === 403) {
      const user = userStore()
      const { token } = storeToRefs(user)
      if (token.value) {
        hud.error('登录已过期，请重新登录')
        user.$reset()
      }
      delCache('token')
      delCache('workToken')
      router.replace('/login')
      // 解锁
      const { system } = storeToRefs(globalStore())
      system.value.isLock = false
    }

    console.log('error2', response)

    return Promise.reject(buildError(response, false))
  },
)

export const http = instance
