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

// 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
    // 判断用户是否登录
    if (browser().android || browser().iPhone) { // app里面
      let userInfo = decodeURI(localStorage.getItem('Authorization'))
      userInfo = userInfo ? userInfo[0].toUpperCase() + userInfo.slice(1) : userInfo
      if (userInfo) {
        config.headers['Authorization'] = userInfo
      }
    } else { // 网页里面
      let auth = decodeURI(localStorage.getItem('userInfo'))
      auth = auth ? auth[0].toUpperCase() + auth.slice(1) : auth
      if (auth) {
        config.headers['Authorization'] = auth
      }
    }
    const tenantId = sessionStorage.getItem('tenantId')
    if(tenantId && tenantId != 'undefined') {
      config.headers['tenantId'] = tenantId
    }

    // config.headers['Authorization'] = 'bearer 5848d682-f5a3-4ce1-b86d-5b5f466ae665'
    return config;
  },
  function (error) {
    // 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) {
      window.localStorage.removeItem('userInfo') // 删除用户信息
      window.localStorage.removeItem('Authorization') // 删除用户信息
      // android ios 注册方法
      if (browser().android) {
        DAYA.postMessage(JSON.stringify({ api: 'login' }))
      } else if (browser().iPhone) {
        window.webkit.messageHandlers.DAYA.postMessage(JSON.stringify({ api: 'login' }))
      }
    }
    return response;
  },
  function (error) {
    // 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
