import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

export function createService(baseUrl) {
  // create an axios instance
  const service = axios.create({
    baseURL: baseUrl, // api的base_url
    headers: {
      'Cache-Control': 'no-cache'
    },
    timeout: 300000 // request timeout,
  })

  // request interceptor
  service.interceptors.request.use(
    config => {
      const token = getToken()
      if (token) {
        var tokenName = process.env.VUE_APP_Token_Name
        if (tokenName) {
          config.headers[tokenName] = token // 让每个请求携带token\
        } else {
          config.headers['EMP-Token'] = token // 让每个请求携带token\
        }
      }
      return config
    },
    error => {
      // Do something with request error
      // console.log(error); // for debug
      return Promise.reject(error)
    }
  )

  // respone interceptor
  service.interceptors.response.use(
    response => {
      // var result = response.data.result;
      // return result;
      if (response.data.result) {
        var result = response.data.result
        response.data = result
        return result
      } else {
        return response.data
      }
    },
    error => {
      var msg = error.message
      if (error.response && error.response.data.error) {
        msg = error.response.data.error.message
        var err = error.response.data.error
        if (err === 'invalid_grant' || err === 'invalid_request') {
          msg = error.response.data.error_description
          var errDes = error.response.data.error_description
          if (errDes === 'invalid_username_or_password') {
            msg = '无效的用户名或密码'
          }
        }
        if (err.validationErrors && err.validationErrors.length) {
          msg = err.validationErrors.map(t => t.message).join('\r\n')
        }
      }

      // if (!msg && error.response) {
      //   msg = `系统发生未知错误${error.response.status},请稍后尝试！`;
      // }

      if (error.response && error.response.status === 401) {
        msg = '令牌失效或未登陆！'
      }

      // if (error.response && error.response.status === 403) {
      //   msg = "权限不足！";
      // }
      if (msg) {
        Message.error(msg)
      }

      return Promise.reject(error)
    }
  )

  return service
}

export const appservice = createService(process.env.VUE_APP_API)

const service = createService(process.env.VUE_APP_BASE_API)
export default service
