import axios from 'axios'

import store from '@/store'
// import { getToken } from '@/utils/auth'

// import router from '@/router'
import Vue from 'vue'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://mk.sunplus.wang/WebAPI',
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
  // responseType: 'json',
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  // }
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      let TOKEN = localStorage.getItem('token')
      config.headers.Authorization = `${TOKEN}`

    }
    // config.headers['content-type'] = 'multipart/form-data'
    return config
  },
  error => {
    // do something with request error
    console.log(error, 'err') // 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 => {

    const res = response.data
    if (response.config.url == "/pre_interface/V5.0/insertBasicInfo" || response.config.url == '/pre_interface/V5.0/getPreItem' || response.config.url == '/pre_interface/V5.0/setStatus') {

      return res
    }
    const meta = response.config['meta'] || {};
    if (meta['ignoreResponse']) return res;

    if (response.headers['access-control-expose-headers']) {
      let str = response.headers['access-control-expose-headers'].split(';')

      document.cookie = str[0]
    }
    if (response.config.url == "/captchaImage") {
      return res
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.ResultCode !== 0) {
      // if (res.code !== 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.ResultCode === -5 || res.ResultCode === -9 || res.ResultCode == -8) {
        // store.commit('user/LOGOUT')
        Vue.prototype.$message({
          message: res.ResultInfo,
          type: 'error',
          showClose: true,
        })

        Vue.router.replace('/')

      } else if (res.ResultCode === 401) {

        let isAllow = sessionStorage.getItem('isAllow')
        if (isAllow === 'true' || !isAllow) {
          // debugger
          Vue.prototype.$message({
            message: '登录过期,请重新登录',
            type: 'error',
            showClose: true,
          })
          sessionStorage.setItem('isAllow', 'false')
          Vue.prototype.$router1.replace('/')
        }



      } else {
        Vue.prototype.$message({
          message: res.ResultInfo || `API 错误 (${res.ResultCode})`,
          type: 'error',
          showClose: true,
        })

      }
      return Promise.reject(new Error(res.ResultInfo || 'Error'))
    } else {

      return res
    }
  },
  error => {

    Vue.prototype.$message({
      message: error.message,
      type: 'error',
      showClose: true,
    })

    return Promise.reject(error)
  }
)

export default service