import axios from 'axios'

const user = JSON.parse(localStorage.getItem('userInfo'));
const token = user?.token
// 'c1c1pMQo4Us5DJoGZAkH6tD4xPNyUrrAXWkRMFTIER5IPK_anjiSNszbiamfCG_aHwWMPq7_bNN1GRdY_aSJj7Rb'

const Request = axios.create({
  baseURL: window.globalVariables.api,
  method: 'post',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
})

Request.interceptors.request.use(
  (config) => {
    // do something before request is sent
    config.data = Object.assign(
      {
        token,
        api: 'json',
        // fake: 1,
      },
      config.data || {}
    )
    if (config.method === 'get') {
      config.params = Object.assign(
        {
          token,
          api: 'json',
          fake: 1,
        },
        config.params || {}
      )
    }
    return config
  },
  (error) => {
    // do something with request error
    console.error('request error: ', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
Request.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data
    if (!['1', '0'].includes(code)) {
      ElMessage.error(msg)
    }
    return response.data
  },
  (error) => {
    console.error('response error: ' + error) // for debug
    return Promise.reject(error)
  }
)

export default Request
