import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth'

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '',
  timeout: 10000, // 毫秒
  headers: {
    'Content-Type': 'application/zip; charset=utf-8'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      // 保持与原项目相同的Token头设置
      config.headers['Token'] = token
    }
    return config
  },
  (err) => {
    console.log('请求出错')
    return Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    let result = res.data

    if (typeof res.data === 'string') {
      try {
        result = JSON.parse(res.data)
      } catch (e) {
        // 不是JSON格式，保持原样
      }
    } else {
      // 4000 token无效或者过期
      if (result.code === 4000) {
        removeToken()
        window.location.reload()
      }

      if (result.code === 0) {
        result.ok = true
      } else {
        result.ok = false
        ElMessage.error(result.msg || '请求失败')
      }
    }

    return result
  },
  (err) => {
    ElMessage.error('网络请求出错, 请检查网络')
    return Promise.reject(err)
  }
)

// HTTP 请求方法常量
export const GET = 'get'
export const POST = 'post'
export const PUT = 'put'
export const DELETE = 'delete'

// 请求函数类型
export interface RequestConfig {
  url: string
  method: 'get' | 'post' | 'put' | 'delete'
  params?: any
  data?: any
  headers?: Record<string, string>
}

export interface ApiResponse<T = any> {
  code: number
  data: T
  message: string
}

export interface QueryParams {
  page?: number
  size?: number
  project?: string
  spider?: string
  scrapydServerId?: string
  order_prop?: string
  order_type?: string
  status?: any
  job?: any
}

// 请求函数
export const request = (config: RequestConfig) => {
  return instance(config)
}

export interface UserQueryParams {
  page?: number
  size?: number
  username?: string
  nickname?: string
  password?: string
  role?: number
  status?: any
  id?: number
  ids?: any
  scrapydServerId?: string
  project?: string
  spiders?: any
  times?: any
  job_id?: string
  scrapyd_server_id?: string
  schedule_type?: string
  spider?: string
  cron?: string
  options?: string
  sat_name?: string
  ntc_id?: string
  filters?: any
  norad_cat_id?: string
  object_name?: string
  name?: string
  spacecraft?: string
  station?: string
  interval?: number[]
  schedule_job_id?: string
}
