import Vue from 'vue'
import axios from 'axios'

import router from '@/router/index'
import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'


//自动打包、让内外网都能登陆的设置，但是npm run dev 后只能选localhost展示了
//后端框架才需要这段——本地手动打包时可注释
// const DoMainString = document.querySelector("html").getAttribute("domain");
// axios.defaults.baseURL = process.env.VUE_APP_BASE_API
// if (DoMainString) {
//   axios.defaults.baseURL = DoMainString
// }

// var reg =  /(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/;
// var browserUrl = window.location.hostname
// if (reg.test(browserUrl)){
//   axios.defaults.baseURL = window.location.protocol +"//"+ browserUrl + ":8087/"
// }
//后端框架才需要这段——本地手动打包时可注释


//正常本地打包地址
axios.defaults.baseURL = process.env.VUE_APP_BASE_API




// create an axios instance
const service = axios.create({
  //baseURL: process.env.VUE_APP_BASE_API, // 根目录路径
  // baseURL: 'http://192.168.1.77:8092',
  // baseURL: 'http://192.168.1.70:8087',

  //baseURL: 'http://192.168.1.96.8090',
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'  //此处是增加的代码，设置请求头的类型
    // if (process.env.VUE_APP_BASE_API !== '/dev-api') {
    //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    //   config.withCredentials = false
    // }

    // if (store.getters.token) {

    //   if (process.env.VUE_APP_BASE_API === '/dev-api') {
    //     config.headers['X-Token'] = getToken()
    //   } else {
    //     config.headers['token'] = getToken()
    //   }
    // }
    //  console.log(sessionStorage.getItem("g_token"))

     config.headers['Authorization'] = 'Bearer '+ window.sessionStorage.getItem("g_token")
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

   // console.log("response-------------",response)
     const res = response.data

    //console.log(res)

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        // message: res.msg + res.code,
        message: '请求超时'+  res.msg,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //   // to re-login
      //   MessageBox.confirm('你已经注销登陆,你可以取消或重新登陆', '确认注销', {
      //     confirmButtonText: '重新登陆',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     // store.dispatch('user/resetToken').then(() => {
      //     //   location.reload()
      //     // })
      //   })
      // }
      // if (res.code === 20002) {
      //   // store.dispatch('user/resetToken').then(() => {
      //   //   location.reload()
      //   // })
      // }
      if (res.code === undefined) {
        return res
      } else {
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    console.log('error' + error) // for debug

    if (error.response.data.code === 10000) {

      // Message({
      //   // message: res.msg + res.code,
      //   message:'Token失效，已经注销登陆,你可以退出重新登陆',
      //   type: 'error',
      //   duration: 5 * 1000
      // })

      MessageBox.confirm('你已经注销登陆,你可以退出重新登陆' , {
        confirmButtonText: '重新登陆',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
         //清空token
        window.sessionStorage.clear()
        //跳转登录页
        router.push('/login')
        location.reload()

      })

      
    }
    let config = error.config
    if (!config) {
      Message({ message: error.msg, type: 'error', duration: 5 * 1000 })
      return Promise.reject(error)
    }
    Message({
      message: "操作错误！"+error.response.data.errors[0],
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
