import axios from 'axios';
import { getQueryString } from './utils';
import { message } from 'antd';

//禁用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();

//对axios二次封装
// console.log('getQueryString', getQueryString('token'));
// console.log('localStorage', localStorage.getItem('token'));
const token = getQueryString('token') || localStorage.getItem('token');
const request = axios.create({
  baseURL: 'http://tcal.atelligence-ai.com/',
  timeout: 15000,
  headers: {
    // 'Content-Type': 'application/json',
    accessToken: token,
  },
});

function checkToken(config) {
  request
    .get('http://69.235.144.91:8048/yszh-login/auth/checkToken')
    .then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        console.log('token 检验通过');
        return config;
      } else {
        // message.error('请重新登录');
        console.log('token校验没通过  返回登录页');
        // window.open('http://localhost:3000/#/login', '_self');
        window.open('http://69.235.144.91:3048/#/login', '_self');
      }
    })
    .catch((err) => {
      console.log('token校验报错  返回登录页');
      // message.error('请重新登录');
      window.open('http://69.235.144.91:3048/#/login', '_self');
      console.log('err', err);
    });
}
checkToken();

//拦截器
request.interceptors.request.use((config) => {
  // alert('拦截器..');
  console.log('token---', '拦截器方法校验token');
  if (!!token) {
    checkToken(config);
  } else {
    console.log('token为空....');
    window.open('http://69.235.144.91:3048/#/login', '_self');
  }
  // return config;
});

request.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (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;
