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
}

let paramsObj = queryURLParams(url)
if (process.env.NODE_ENV === 'development') {
  baseURL = process.env.VUE_APP_BASE_API
  paramsObj.token =
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ0ZW5hbnRfaWQiOiJvd3RlZWgyIiwidXNlcl9uYW1lIjoiMTg2MTgyNDI2OTAiLCJtb2JpbGUiOiIxODYxODI0MjY5MCIsInRva2VuX3R5cGUiOiJhY2Nlc3NfdG9rZW4iLCJyb2xlX25hbWUiOiJhZG1pbiznoJTnpaXmtYvor5UsbmlzaSByZXByZWhlbmRlcml0IHV0IGV1IiwicG9zdF9pZCI6IjE3NjcwNjM5NjEzNjQ3OTk0OTAiLCJ1c2VyX2lkIjoiMTc2NzA2Mzk2NDkzNDE1MjE5MyIsInJvbGVfaWQiOiIxNzY3MDYzOTYwNDc5ODAxMzQ2LDE3OTYwNzYzMjk5NDgxMzk1MjIsMTc5NjExMzg2MzMxMDgyMzQyNiIsIm5pY2tfbmFtZSI6IueuoeeQhuWRmCIsImRldGFpbCI6eyJ0eXBlIjoid2ViIiwidXNlckZsYWciOjAsInRoaXJkVXNlcklkIjoiQTAwMDAwMSIsInRoaXJkRGVwdElkIjoiMTc2NzA2Mzk2MDg1NzI4ODcwNSIsInRoaXJkUG9zdElkIjoiY2VvIn0sImRlcHRfaWQiOiIxNzY3MDYzOTYwODU3Mjg4NzA1IiwiYWNjb3VudCI6IjE4NjE4MjQyNjkwIiwiY2xpZW50X2lkIjoic2FiZXIiLCJleHAiOjE3MjQ5Mzc4NDcsIm5iZiI6MTcyNDkwMTg0N30.NiOMsqW0yPbSPxcM-6OGCEY3nIPr9ITxYC1JaEuXTusUQn4ANKFmRD-duCI_3Le68x2dUJZEt5RzoIQ-RN456g'
  if (!getToken() || getToken() !== paramsObj.token) {
    setToken(paramsObj.token)
  }
} else {
  baseURL = APP_CONFIG.API_URL
  let token = localStorage.getItem('saber-access-token')
  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) => {
    config.headers['Authorization'] = `Basic ${Base64.encode(`${'saber'}:${'saber_secret'}`)}`
    if (store.getters.token) {
      config.headers['Blade-Auth'] = 'bearer ' + getToken()
    }
    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: '/login'
        })
      )
    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
