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

const baseURL = 'http://69.235.144.91:9001/yszh/1/api/';
// const baseURL='http://52.83.230.236:9001/yszh/1/api/',
axios.defaults.headers['content-type'] = 'application/json'; //这样写有风险,可能会有请求头是form-data的格式

const token = getQueryString('token') || localStorage.getItem('token');
const request = axios.create({
  baseURL,
  timeout: 15000,
  headers: {
    accessToken: token,
  },
});

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

//拦截器
request.interceptors.request.use((config) => {
  // config.headers.Authorization = localStorage.getItem('token');
  console.log('token---', '拦截器方法校验token');
  console.log(config);

  if (getQueryString('token') || localStorage.getItem('token')) {
    checkToken(config);
  } else {
    console.log('token为空....');
    localStorage.removeItem('token');
    window.open('http://69.235.144.91:3048/#/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;
