import axios from 'axios'
import { ElMessage } from 'element-plus'
// import router from '@/router'

const httpRequest = axios.create({
  // timeout: 60000,
  withCredentials: true,
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function (config) {
    const params = new URLSearchParams(window.location.search)

    if (config.method === 'get')
      config.params = Object.assign({}, config.params, {
        experiment_id: params.get('experiment_id'),
        student_id: params.get('student_id') || undefined,
        force_tgc: params.get('force_tgc') || undefined
      })

    if (config.method === 'post')
      config.data = Object.assign({}, config.data, {
        experiment_id: params.get('experiment_id'),
        student_id: params.get('student_id') || undefined,
        force_tgc: params.get('force_tgc') || undefined
      })

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { data } = response
    // 未登录
    if (data.code === 4001) {
      location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      return Promise.reject(data)
    }
    if (data.code === 1 || data.code === -1) {
      ElMessage.error(data.message || data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      // 未登录
      if (status === 403) {
        location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
        // } else if (status === 401 || status === 402) {
        //   // 未授权
        //   router.push('/401')
      } else {
        ElMessage.error(message || error.message)
        console.error(`${status}: ${message}`)
      }
    } else {
      console.log(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default httpRequest
