import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_New_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000,
  transformRequest: [function(data, headers) {
    const QueryParamer = []
    for (var d in data) {
      if (d.indexOf('_') >= 0) {
        if (data[d] != null && data[d] != undefined && data[d] + '' != '') {
          var o = d.split('_')[1]
          var q = d.split('_')[2]
          if (o == 'Range') {
            QueryParamer.push(
              { Filed: q,
                Value: data[d][0],
                Method: 'GrE' })
            QueryParamer.push(
              { Filed: q,
                Value: data[d][1],
                Method: 'LeE' })
          } else {
            QueryParamer.push(
              { Filed: q,
                Value: data[d].toString(),
                Method: o })
          }
        }
      }
    }
    try {
      if (data.QueryParamer) { data.QueryParamer = [] }
    } catch (ex) {
      console.log(ex.message)
    }
    if (QueryParamer.length > 0) { data.QueryParamer = QueryParamer }

    headers['Content-Type'] = 'application/json'
    return JSON.stringify(data)
  }]
  // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // config.transformRequest = function(data,headers){

    //   return data;
    // }
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = 'token ' + getToken()
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data.data || response.data.Data || response.data
    if (Object.prototype.toString.call(res) === '[object Array]') {
      for (var i = 0; i < res.length; i++) {
        for (var r in res[i]) {
          if (res[i][r] != null && res[i][r].toString().search(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?/i) >= 0) {
            res[i][r] = res[i][r].toString().replace('T', ' ')
          }
        }
      }
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    try {
      MessageBox.alert(error.response.data.message || error.response.data)
    } catch (ex) {
      MessageBox.alert(error)
    }
    return Promise.reject(error.response.data.message || error.response.data)
  }
)

export default service
