import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
import store from '@/store'
import { ElMessage } from 'element-plus'
import { triggerTooltip } from '@/hooks/useErrorTrigger'
import { getUserEnvInfo, getTodayRangeLocal } from '@/utils'

const baseURL = import.meta.env.VITE_BASE_URL

const service = axios.create({
  baseURL: baseURL,
  timeout: 30 * 1000
})

// 请求前的统一处理
service.interceptors.request.use((config) => {
  const token = store.state.user.token
  // JWT鉴权处理
  if (store.getters['user/token']) {
    config.headers["token"] = store.state.user.token;
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
},
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    // 如果是 Blob（比如验证码图片），直接返回完整 response
    const contentType = response.headers['content-type']
    if (response.config.responseType === 'blob' || contentType?.includes('application/octet-stream') || contentType?.includes('image')) {
      return response
    }

    const res = response.data
    /*  if (res.code === 200) {
       return res
     } else {
       showError(res)
       return Promise.reject(res)
     } */
    if (res.Authorization) {
      return res;
    } else if (res.status === 200 || res.code === 200) {
      return res;
    } else {
      showError(res);
      return Promise.reject(res);
    }
  },
  (error) => {
    console.log(error)

    const { config, response } = error || {}
    const { url, method, data, params } = config || {}
    const status = response?.status
    const statusText = response?.statusText
    const responseData = response?.data

    const { os, browser, networkType, isMobile } = getUserEnvInfo()

    let errorTitle = `请求错误接口: ${url}`

    let errorTemplate = `
      请求失败：
      接口地址: ${method?.toUpperCase()} ${url}
      请求参数: ${params}
      请求体: ${data}
      状态码: ${status} ${statusText || ''}
      返回内容: ${responseData || error.message}
      操作系统: ${os}
      浏览器: ${browser}
      网络类型: ${networkType}
      是否移动设备: ${isMobile}
      时间: ${getTodayRangeLocal('now')}
    `
    console.log('请求失败 :===>>', errorTemplate);

    // 触发 tooltip 展示
    triggerTooltip(errorTitle, errorTemplate)

    const badMessage = error.message || error
    const code = parseInt(badMessage.toString().replace('Error: Request failed with status code ', ''))
    showError({ code, message: badMessage })
    return Promise.reject(error)
  }
)

// 错误处理
function showError(error) {
  // token过期，清除本地数据，并跳转至登录页面
  if (error.code === 403) {
    ElMessage({
      message: error.msg || error.message || '请求错误',
      type: 'error',
      duration: 1000
    })
    // to re-login
    setTimeout(() => {
      store.dispatch("user/loginOut");
    }, 1000);
  }
  else if (error.code === 1024) {
    ElMessage({
      message: "token过期，请重新登录",
      type: "error",
      duration: 1000,
    });
    // to re-login
    setTimeout(() => {
      store.dispatch("user/loginOut");
    }, 1000);
  } else {
    ElMessage({
      message: error.msg || error.message || '服务异常',
      type: 'error',
      duration: 3 * 1000
    })
  }

}

export default service