import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // api 的 base_url
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // console.log('config', config)
    // Do something before request is sent
    if (userStore.token) {
      config.headers['xunjian-token'] = getToken()
      // config.headers['xunjian-token'] = 'e70b4b09-93fc-40e7-b090-1ba03c9a2ac0'
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const array = [601, 602, 603, 604, 605, 640, 641, 642]
    if (res.errno === 501) {
      ElMessageBox.alert('系统未登录，请先登录', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        userStore.FedLogOut.then(() => {
          location.reload()
        })
      })
      return Promise.reject('error')
    } else if (res.errno === 502) {
      ElMessageBox.alert('无权限操作', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject('error')
    } else if (array.includes(res.errno)) {
      ElMessageBox.alert(res.errmsg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return response
    } else if (res.errno === 402) {
      ElMessageBox.alert('数据异常', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject('error')
    } else if (res.errno === -1 || res.errno === 1) {
      let rss = (res.data == null ? '' : res.data) + (res.errmsg == null ? '' : res.errmsg);
      ElMessageBox.alert(rss, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject(res)
      // throw new Error(res.errmsg)
    } else if (res.errno !== 0) {
      // 非5xx的错误属于业务错误，留给具体页面处理
      if (response.status == 200) {
        return response
      }
    } else {
      return response
    }
  }, error => {
    // console.log('err' + error)// for debug
    ElMessage({
      message: '登录连接超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
