import axios from 'axios';
import { getQueryString } from './utils';
//禁用F12功能
function disableF12() {
  document.onkeydown = function() {
    var e = window.event || arguments[0];
    if (e.keyCode == 123) {
      return false;
    } else if (e.ctrlKey && e.shiftKey && e.keyCode == 73) {
      return false;
    }
  };
  //禁用鼠标右键
  document.oncontextmenu = function() {
    return false;
  };
}
// disableF12();

const baseURL = 'http://52.83.169.190:8003/';
const token = getQueryString('token') || localStorage.getItem('token');

const request = axios.create({
  baseURL,
  timeout: 15000,
  headers: {
    accessToken: token,
  },
});

// 封装同步Ajax请求
function checkAjaxToken() {
  const token = getQueryString('token') || localStorage.getItem('token');
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://69.235.144.91:8048/yszh-login/auth/checkToken', false);
  xhr.setRequestHeader('accessToken', token);
  xhr.send(null);
  console.log(xhr); //准备状态
  if (xhr.status == 200 && JSON.parse(xhr.responseText).code == 200) {
    // 获取响应结果
    // console.log(xhr.responseText);
    token && localStorage.setItem('token', token);
    return true;
  } else {
    console.log('状态码：' + xhr.status + ',原因:' + xhr.responseText);
    return false;
  }
}
// checkAjaxToken();

//拦截器
// request.interceptors.request.use((config) => {
//   console.log('config',config);
//   if (checkAjaxToken()) {
//     return config;
//   } else {
//     console.log('token校验失败...');
//     window.open('http://ysplatform.atelligence-ai.com/#/login', '_self');
//   }
// });

request.interceptors.response.use(
  (res) => {
    return res;
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          console.log('请求错误');
          break;
        case 401:
          console.log('未授权访问');
          break;
        case 404:
          console.log('页面未找到');
          break;
        default:
          console.log('其他错误信息');
      }
    }
    return err;
  }
);

export default request;
