import { fetchEventSource } from '@microsoft/fetch-event-source'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// TODO: 完善拦截器

// 判断是否在 Electron 环境中
const isElectron = window && window.process && window.process.type

const service = axios.create({
  baseURL: isElectron ? process.env.VITE_APP_BASE_API : '',
  timeout: 30000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 自动注入 token
    if (!config.headers['Authorization']) {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
    }
    // 支持自定义 Content-Type
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json'
    return config
  },
  error => {
    ElMessage.error('请求发送失败')
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log(response, 'response')
    // 统一处理后端自定义 code
    if (response.data && response.data.code !== undefined && response.data.code !== 200) {
      ElMessage.error(response.data.message || '请求失败')
      // 401 未登录/登录失效
      if (response.data.code === 401) {
        // 可跳转登录页
      }
      return Promise.reject(response.data)
    }
    return response.data
  },
  error => {
    // 统一处理 HTTP 错误
    let msg = '请求出错'
    if (error.response) {
      msg = error.response.data?.message || `HTTP ${error.response.status}`
    } else if (error.message) {
      msg = error.message
    }
    ElMessage.error(msg)
    return Promise.reject(error)
  }
)

// SSE 请求方法
export const sseRequest = (config) => {
  return new Promise((resolve) => {
    try {
      const url = new URL(`${config.url}`, window.location.origin)
      const ctrl = new AbortController()
      let messageQueue = []
      let resolveQueue = null

      const messageGenerator = async function* () {
        const source = new fetchEventSource(url.toString(), {
          method: 'POST',
          headers: {
            'Authorization': config.headers?.Authorization || `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream',
          },
          body: JSON.stringify(config.params),
          signal: ctrl.signal,
          openWhenHidden: true,
          onmessage: (event) => {
            try {
              const data = JSON.parse(event.data)
              if (resolveQueue) {
                resolveQueue(data)
                resolveQueue = null
              } else {
                messageQueue.push(data)
              }
            } catch (error) {
              console.error('Error parsing SSE message:', error)
            }
          },
          onerror: (error) => {
            console.error('EventSource failed:', error)
            ctrl.abort()
            if (resolveQueue) {
              resolveQueue(null)
              resolveQueue = null
            }
          },
          onclose: () => {
            console.log('Connection closed')
            if (resolveQueue) {
              resolveQueue(null)
              resolveQueue = null
            }
          }
        })

        try {
          while (true) {
            if (messageQueue.length > 0) {
              yield messageQueue.shift()
            } else {
              const message = await new Promise(resolve => {
                resolveQueue = resolve
              })
              if (message === null) {
                break
              }
              yield message
            }
          }
        } finally {
          ctrl.abort()
        }
      }

      resolve(messageGenerator())
    } catch (error) {
      console.error('SSE request setup failed:', error)
      resolve((async function* () {})())
    }
  })
}

// 常规HTTP请求方法
export const httpRequest = (config) => {
  return new Promise((resolve, reject) => {
    try {
      const {
        url,
        method = 'GET',
        params = {},
        data = {},
        headers = {},
        ...restConfig
      } = config

      // 构建请求配置
      const reqMethod = method.toUpperCase()
      const requestConfig = {
        url,
        method: reqMethod,
        headers: {
          ...headers,
          'Content-Type': headers['Content-Type'] || 'application/json'
        },
        ...restConfig
      }
      if (["GET", "DELETE"].includes(reqMethod)) {
        requestConfig.params = params || data
      } else {
        requestConfig.data = data || params
      }
      console.log(requestConfig, 'requestConfig')
      // 发送请求
      service(requestConfig)
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          // 错误已在拦截器中处理
          reject(error)
        })
    } catch (error) {
      ElMessage.error('请求配置异常')
      reject(error)
    }
  })
}

export default httpRequest
