/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { type AxiosInstance } from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { getCache, delCache } from '@/utils/store'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores'
import { platform } from '@/config/platform'
import onlyLast from './only-last'

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: (params: any) =>
          qs.stringify(params, {
            arrayFormat: 'repeat',
            allowDots: true,
          }),
      }
    }
    onlyLast.processRequest(config)

    config.headers['X-Tenant-Id'] = platform.tenantId

    if ('Authorization' in config.headers && 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 = response?.data ?? {}
  const message = data.message ?? data.msg
  let errorMsg = message
  let showed = false
  if (errorMsg) {
    if (String(errorMsg).includes('服务器')) {
      errorMsg = '网络不稳定，请稍后再试~'
    }
    if (show) {
      ElMessage.error(String(errorMsg))
      showed = true
    }
  }
  if (errorMsg && String(errorMsg).includes('非本平台用户')) {
    delCache('token')
    delCache('workToken')
    router.replace('/login')
  }
  return {
    message: errorMsg,
    showed,
  }
}

instance.interceptors.response.use(
  response => {
    const { code, message } = response.data ?? {}
    if (!onlyLast.processResponse(response.config)) {
      return Promise.reject(response)
    }

    if (response.headers['content-type']?.includes('octet-stream') || 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) {
        ElMessage.error('登录已过期，请重新登录')
        user.$reset()
      }
      delCache('token')
      delCache('workToken')
      router.replace('/login')
    }

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

export const http = instance
