import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'
import { Base64 } from 'js-base64'
import router from '@/router'
import { message } from '@/utils/message'

let url = decodeURI(window.location.search || window.location.hash)
let baseURL = ''
//获取哈希地址信息
function queryURLParams(url) {
  let result = {},
    reg1 = /([^?=&#]+)=([^?=&#]+)/g,
    reg2 = /#([^?=&#]+)/g
  url.replace(reg1, (n, x, y) => (result[x] = y))
  url.replace(reg2, (n, x) => (result['HASH'] = x))
  return result
}
export function getCookie(key) {
  if (document.cookie.indexOf(key) < 0) {
    return
  }
  let cookies = document.cookie.split(';')
  for (let i = 0; i < cookies.length; i++) {
    let temp = cookies[i].split('=')
    if (temp[0].replace(/\s/g, '') === key) {
      return decodeURIComponent(temp[1])
    }
  }
}
let paramsObj = queryURLParams(url)
if (process.env.NODE_ENV === 'development') {
  baseURL = process.env.VUE_APP_BASE_API
  paramsObj.token =
    'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJCSTEwMDEiLCJpbnN0SWQiOiIxNzQ3Nzg5ODU1MjgwMTg5NTM5Iiwia2lkIjoibXhrX2F1dGhfandrIiwiaXNzIjoiaHR0cHM6Ly9xZXZvYy5jb20vIiwic3R5bGUiOiJ3ZWIiLCJleHAiOjE3Mjg2OTY1OTAsImlhdCI6MTcyNTA5NjU5MCwidXNlcklkIjoiMTc3MjUzMTcxMDcyNDQ5NzQxMCIsImp0aSI6IjEwMjczMTE0MDMzMDU3OTU1ODQifQ.7lzjMIs4w_9uq_03sL27CLPhbLZZmd3p5e4u2BRxeXUlPRZUVvlBgu5Qpzh9dekBeUFFxp5CZwoc5pvarBy5Nw'
  if (!getToken() || getToken() !== paramsObj.token) {
    setToken(paramsObj.token)
  }
} else {
  baseURL = _CONFIG.APIHead
  let token = getCookie('congress')
  if (token) {
    if (!getToken() || getToken() !== token) {
      setToken(token)
    }
  }
}
// function getQueryVariable(variable) {
//   var query = window.location.search.substring(1);
//   var vars = query.split("&");
//   for (var i=0;i<vars.length;i++) {
//     var pair = vars[i].split("=");
//     if(pair[0] == variable){return pair[1];}
//   }
//   return(false);
// }
// create an axios instance
const service = axios.create({
  baseURL, // url = base url + request url
  withCredentials: false // send cookies when cross-domain requests
  // timeout: define.timeout, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    let token = ''
    if (process.env.NODE_ENV === 'development') {
      token = paramsObj.token
    } else {
      token = getCookie('congress')
    }
    config.headers['Authorization'] = 'bearer ' + token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    //获取状态码
    const status = response.data.code || response.status
    const message = response.data.msg || response.data.error_description || '未知错误'
    if (status === 401)
      store.dispatch('user/logout').then(() =>
        router.push({
          path: '/'
        })
      )
    if (status !== 200) {
      Message({
        message: message,
        type: 'error',
        duration: 1500
      })
      return Promise.reject(new Error(message))
    } else {
      return response
    }
  },
  (error) => {
    if (error.response) {
      const status = error.response.data.code
      if (status === 401) {
        if (process.env.NODE_ENV === 'development') {
          console.log(status) // for debug
        } else {
          console.log(status) // for debug
          window.open(document.location.origin + '/#/login', '_self')
          //清理缓存
          window.localStorage.clear()
          let pathUrl = window.location.href
          localStorage.setItem('USER_WORK_PATH', pathUrl)
        }
      }
    }
    try {
      message({
        message: '请求出错，请重试',
        type: 'error',
        duration: 1500
      })
    } catch (e) {
      console.log(e)
    }
    return Promise.reject(error)
  }
)

export default service
