import axios from 'axios'
// import BASE_URL from '../config/env'
import store from '../store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import { Message } from 'element-ui'
import { resetServerTime } from './index'
import { localStore } from '@/utils'
/* eslint-disable-next-line */

const log = require('electron-log')

// 创建axios实例
const service = axios.create({
  baseURL: localStore.get('serverUrl') // api的base_url
  // timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    // config.data.SaToken = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    Object.assign(config, {
      headers: { 'SaToken': token }
    })
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug

  log.error(JSON.stringify(error))

  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(response => {
  // store.commit('SET_DIFF_TIME', response.headers.date)
  if (process.env.NODE_ENV === 'production') {
    resetServerTime(response.headers.date)
  }
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
  const { code, msg, logId } = response.data

  if (msg.includes('请登录后再访问') && getToken()) {
    store.dispatch('LogOut').then(() => {
      router.push('/login')
    })
  } else if (code !== '200') {
    if (code === '999990') {
      Message({
        message: `${msg}${logId ? ` [错误代码为：${logId}]` : ''}`,
        type: 'error'
      })
    } else {
      Message({
        message: msg,
        type: 'error'
      })
    }
    return Promise.reject(response.data)
  } else {
    return response.data
  }
}, error => {
  let message = ''
  if (error.response.data && error.response.data.message) {
    message = error.response.data.message
  } else {
    message = '网络出错了'
  }
  Message({
    message: message,
    type: 'error'
  })

  log.error(JSON.stringify(error.response.config.data))
  log.error(JSON.stringify(error.response.data))

  return Promise.reject(error)
})

export default service
