import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import { emitter } from '@/utils/bus.js'
import router from '@/router/index'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 99999
})

let acitveAxios = 0
let timer

const showLoading = () => {
  acitveAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      emitter.emit('showLoading')
    }
  }, 400)
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
    clearTimeout(timer)
    emitter.emit('closeLoading')
  }
}

// http request 拦截器
service.interceptors.request.use(
  config => {
    // 移除开头的斜杠
    if (config.url && config.url.startsWith('/')) {
      config.url = config.url.slice(1)
    }

    // 获取完整的请求URL
    const baseURL = import.meta.env.VITE_BASE_API
    const fullURL = window.location.origin + baseURL + '/' + config.url // 这里添加斜杠

    // 详细的请求信息日志
    console.log('请求详情:', {
      原始URL: config.url,
      基础URL: baseURL,
      完整URL: fullURL,
      请求方法: config.method,
      请求数据: config.data
    })

    const isCmsEndpoint = config.url && config.url.includes('cms');
    // 统一处理 headers
    const userStore = useUserStore()
    config.headers = {
      'Content-Type': 'application/json',
      'x-user-id': userStore.userInfo.ID,
      'x-user-name': userStore.userInfo.userName,
      ...config.headers
    }

    if (isCmsEndpoint) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`;
    }

    // 确保 baseURL 正确设置
    config.baseURL = baseURL

    return config
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }
    console.error('请求错误:', error)
    ElMessage({
      showClose: true,
      message: error,
      type: 'error'
    })
    return error
  }
)

// http response 拦截器
service.interceptors.response.use(
  response => {
    const userStore = useUserStore()

    // 打印响应信息
    console.log('响应详情:', {
      状态码: response.status,
      响应数据: response.data,
      响应头: response.headers,
      请求URL: response.config.url
    })

    if (!response.config.donNotShowLoading) {
      closeLoading()
    }

    if (response.headers['new-token']) {
      userStore.setToken(response.headers['new-token'])
    }

    if (response.data.code === 100000 || response.headers.success === 'true') {
      if (response.headers.message) {
        response.data.message = decodeURI(response.headers.message)
      }
      return response.data
    } else {
      ElMessage({
        showClose: true,
        message: response.data.message || decodeURI(response.headers.message),
        type: 'error'
      })
      if (response.data.data && response.data.data.reload) {
        userStore.token = ''
        localStorage.clear()
        router.push({ name: 'Login', replace: true })
      }
      if (response.data.code === 30042 || response.data.code == 30041) {
        userStore.LoginOut()
        router.push({ name: 'Login', replace: true })
      }
      return response.data.message ? response.data : response
    }
  },
  error => {
    if (!error.config.donNotShowLoading) {
      closeLoading()
    }

    // 打印详细错误信息
    console.error('请求失败:', {
      错误信息: error.message,
      请求配置: error.config,
      响应状态: error.response?.status,
      响应数据: error.response?.data,
      完整错误: error
    })

    if (!error.response) {
      ElMessageBox.confirm(
        `
        <p>检测到请求错误</p>
        <p>${error}</p>
        `,
        '请求报错',
        {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '稍后重试',
          cancelButtonText: '取消'
        }
      )
      return
    }

    switch (error.response.status) {
      case 500:
        ElMessageBox.confirm(
          `
        <p>检测到接口错误${error}</p>
        <p>错误码<span style="color:red"> 500 </span>：此类错误内容常见于后台panic，请先查看后台日志，如果影响您正常使用可强制登出清理缓存</p>
        `,
          '接口报错',
          {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '清理缓存',
            cancelButtonText: '取消'
          }
        ).then(() => {
          const userStore = useUserStore()
          userStore.ClearStorage()
          router.push({ name: 'Login', replace: true })
        })
        break
      case 404:
        ElMessageBox.confirm(
          `
          <p>检测到接口错误${error}</p>
          <p>错误码<span style="color:red"> 404 </span>：此类错误多为接口未注册（或未重启）或者请求路径（方法）与api路径（方法）不符--如果为自动化代码请检查是否存在空格</p>
          `,
          '接口报错',
          {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '我知道了',
            cancelButtonText: '取消'
          }
        )
        break
    }

    return error
  }
)

export default service
