import axios from 'axios'
import Config from '../config'
import store from '../vuexStore'
// axios.defaults.baseURL = Config.Host

if (sessionStorage.getItem('access_token')) {
  axios.defaults.headers.common['Access-Token'] = sessionStorage.getItem('access_token')
}
if (sessionStorage.getItem('lang')) {
  axios.defaults.headers.common['Language'] = sessionStorage.getItem('lang')
}
if (sessionStorage.getItem('CLIENT')) {
  axios.defaults.headers.common['CLIENT'] = sessionStorage.getItem('CLIENT')
}

class Service {
  constructor() {
    this.axio = axios
  }

  // session过期
  SessionExpire() {
    // 状态管理去处理过期事件
    console.log(store, 'store')
    store.commit('InfoExpire', true)
    // this.vue.$store.commit('InfoExpire', true)
  }

  // 统一登出
  // Logout() {
  //   this.router.push({
  //     name: 'login',
  //   })
  //   location.reload()
  // }

  // method GET
  get(url, params) {
    return this.axio
      .get(url, params)
      .then((response) => {
        if (response.data.code == Config.Code.StatusSessionExpire) {
          this.SessionExpire()
        } else {
          return response.data
        }
      })
      .catch(() => {
        this.SessionExpire()

        return {
          code: Config.Code.StatusFail,
          msg: 'System error',
        }
      })
  }

  // method POST
  post(url, params) {
    return this.axio
      .post(url, params)
      .then((response) => {
        if (response.data.code == Config.Code.StatusSessionExpire) {
          this.SessionExpire()
        } else if (response.data.code == Config.Code.StatusSNotFound) {
          return {
            code: Config.Code.StatusFail,
            msg: 'System error',
          }
        } else {
          return response.data
        }
      })
      .catch(() => {
        return {
          code: Config.Code.StatusFail,
          msg: 'System error',
        }
      })
  }
}

export default Service
