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();

//对axios二次封装
const token = getQueryString('token') || localStorage.getItem('token');

function checkFetchToken() {
  fetch('http://69.235.144.91:8048/yszh-login/auth/checkToken', {
    method: 'GET',
    headers: {
      accessToken: token,
    },
  })
    .then((res) => res.json())
    .then((res) => {
      console.log('fetch--res', res);
      if (res.code === 200) {
        //校验通过,存储token
        token && localStorage.setItem('token', token);
      } else {
        alert('token校验失败,返回登录页');
        // window.open('http://localhost:3000/#/login', '_self');
        // window.open('http://69.235.144.91:3048/#/login', '_self');
        window.open('http://ysplatform.atelligence-ai.com/#/login', '_self');
      }
    })
    .catch(function(err) {
      console.log('err', err);
      // window.open('http://69.235.144.91:3048/#/login', '_self');
      window.open('http://ysplatform.atelligence-ai.com/#/login', '_self');
    });
}
checkFetchToken();
const baseURL = 'http://52.83.169.190:8002/'; //线上正式环境
// const baseURL = 'http://69.235.144.91:8002/';  测试环境

const request = axios.create({
  baseURL,
  timeout: 15000,
  headers: {
    // 'Content-Type': 'application/json',
    // 部分接口需要formdate格式的数据  'Content-Type': 'application/x-www-form-urlencoded' qs.stringify(data)
    accessToken: token,
  },
});

//拦截器
request.interceptors.request.use((config) => {
  // alert('拦截器..');
  console.log('token---', '拦截器方法校验token');
  console.log(config);
  if (localStorage.getItem('token')) {
    config.headers['accessToken'] = localStorage.getItem('token');
    return config;
  } else {
    console.log('token为空....');
    // window.open('http://69.235.144.91:3048/#/login', '_self');
    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;
