import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
import router from '@/router'
import emitter from '@/utils/mitt'
import userInfoStore from '@/stores/userInfo'
class HttpRequest {
  getInsideConfig() {
    const config = {
      baseURL: import.meta.env.VITE_BASE_URL,
      timeout: 600000,
      withCredentials: false,
      headers: {
        'Content-Type': 'application/json; charset=utf-8'
      }
    }
    return config
  }

  // 请求拦截
  interceptors(instance: AxiosInstance, url: string | number | undefined) {
    instance.interceptors.request.use(
      (config: any) => {
        const userInfo = userInfoStore()
        config.headers.token = userInfo.token
        return config
      },
      (error: any) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截
    instance.interceptors.response.use(
      (res: any) => {
        const { data } = res
        console.log('返回数据处理', res)
        if (data.code === 0) {
          return data
        } else if (data.code === 401 || data.code === 404) {
          const userInfo = userInfoStore()
          userInfo.token = ''
          router.push({
            name: 'login',
            query: {
              // currentRoute存储了当前路由信息的对象
              redirect: router.currentRoute.value.fullPath
            }
          })
          emitter.emit('hiddenLoading', '')
        } else {
          return data
        }
      },
      (error: any) => {
        console.log('error==>', error)
        if (error.response && (error.response.status === 401)) {
          const userInfo = userInfoStore()
          userInfo.token = ''
          router.push({
            name: 'login',
            query: {
              // currentRoute存储了当前路由信息的对象
              redirect: router.currentRoute.value.fullPath
            }
          })
        }
        emitter.emit('hiddenLoading', '')
      }
    )
  }

  request(options: AxiosRequestConfig, openDefaultData = false) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    if (!options.url) {
      throw new Error('URL is not defined in request options')
    }

    this.interceptors(instance, options.url)
    if (options.data && openDefaultData) {
      options.data = JSON.stringify(options.data)
    }
    if (options.url.includes('?')) {
      options.url = options.url + '&t=' + new Date().getTime()
    } else {
      options.url = options.url + '?t=' + new Date().getTime()
    }
    return instance(options)
  }
}

const http = new HttpRequest()
export default http
