import axios from 'axios'
import router from '../router'
let instance = axios.create({
  headers: {
    'content-type': 'application/json'
  }
})
instance.defaults.baseURL = process.env.REQUEST_URL
// instance.defaults.baseURL = config.baseURL
instance.defaults.withCredentials = true

const jmKGDatas = process.env.jmOpenOrNo
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  if (navigator.onLine) {
  } else {
    alert('网络异常，请检测网络是否链接！')
    location.reload()
  }
  // 在发送请求之前做些什么
  // let UserToken = Cookies.get('UserToken')
  let UserToken = localStorage.getItem('UserToken')
  config.headers = {
    'laravel-session-admin': UserToken
  }
  if (UserToken == undefined || undefined == '') {
    router.push({name: 'Login'})
  }
  if (jmKGDatas == true && (config.method == 'post' || config.method == 'put')) {
    let strDatas = JSON.stringify(config.data)
    const encrypted = window.pywebview.api.aes_encrypt(strDatas)
    return encrypted.then(res => {
      let obj = {}
      obj.encrypt_str = res
      config.url = config.url
      config.data = obj
      return config
    })
  } else {
    return config
  }
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  if (navigator.onLine) {      
  } else {
    alert('网络异常，请检测网络是否链接！')
    return false
  }
  // 对响应数据做点什么
  if (response.status == '200') {
    if (response.data.code == '10002') {
      console.log('这里是10002进入了未登录状态')
      router.push({name: 'Login'})
    } else if (response.data.code === 401) {
      router.push({name: 'Login'})
    } else if (response.data.code === 500) {
      // Vue.prototype.$message.error('服务器异常，请联系管理员')
      // return
    }
    if (response.data.code == 4006) {
      router.push({name: 'initialization'})
      let htmls = 'resCont'
      return Promise.reject(htmls)
    }
    if (response.data.code == '10001') {
      let err = response.data.errors
      let html = ''
      Object.keys(err).forEach(function (key) {
        html += err[key]
      })
      return Promise.reject(html)
    }
  }
  if (jmKGDatas == true) {
    const decrypted = window.pywebview.api.aes_decrypt(response.data.encrypt_str)
    return decrypted.then(res => {
      let jmDatas = JSON.parse(res)
      return jmDatas
    })
  } else {
    return response.data
  }
}, function (error) {
  // 对响应错误做点什么
  console.log('--- 401 res error response ---', error)
  if (error && error.response && error.response.status == '401') {
    console.log('error.response', error.response)
  } else if (error.code == 'ERR_BAD_RESPONSE') {
    return false
  }
  return Promise.reject(error)
})

export default instance
