"use strict";
/* eslint-disable */
import axios from "axios"
import router from '../router/index'
import {
  browser
} from '@/utils/common'
import {
  Toast
} from 'vant'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  // transformRequest: [function(data) {
  //     console.log(data)
  //     if(!data.qStringify) {
  //       data = qs.stringify({
  //           ...data
  //       })
  //     }
  //     return data
  // }]

};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 判断用户是否登录
    let userInfo = localStorage.getItem('Authorization')
    if (userInfo) {
      config.headers['Authorization'] = userInfo
    }
    // config.headers['Authorization'] ='bearer 8ffb419c-0d24-46b8-8faf-135ff24fa1d9'
    return config;
  },
  function (error) {
    Toast('网络错误')
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    if (response.data.code == 403 || response.data.code == 403) {
      // window.localStorage.removeItem('userInfo') // 删除用户信息
      window.localStorage.removeItem('Authorization') // 删除用户信息
      if (browser().android) {
        EXAM.postMessage(JSON.stringify({
          api: 'login'
        }))
      } else if (browser().iPhone) {
        window.webkit.messageHandlers.EXAM.postMessage(JSON.stringify({
          api: 'login'
        }))
      } else {
        const examId = window.localStorage.getItem("examId")
        const organId = window.localStorage.getItem("organId")
        router.replace({
          path: 'signUpAccount',
          query: {
            examId: examId,
            organId: organId
          }
        })
      }
    }
    return response;
  },
  function (error) {
    Toast.clear()
    Toast('网络错误')
    // Do something with response error
    return Promise.reject(error);
  }
);

// Plugin.install = function(Vue) {
//   Vue.axios = _axios;
//   window.axios = _axios;
//   Object.defineProperties(Vue.prototype, {
//     axios: {
//       get() {
//         return _axios;
//       }
//     },
//     $axios: {
//       get() {
//         return _axios;
//       }
//     },
//   });
// };

// Vue.use(Plugin)
export default _axios