import { notification ,message} from 'antd';
import axios from 'axios';
import cookie from 'react-cookies';
import Login from './components/Login';

let actionUrl = '';
if (window.location.href.indexOf('localhost') > -1) {
  // actionUrl = 'http://117.50.100.12:8008';
  // actionUrl = 'http://192.168.31.74:8081';
  actionUrl = "https://test-search.trustie.net";
} else if(window.location.href.indexOf('testforgeplus')>-1){
  actionUrl = "https://test-search.trustie.net";
  // actionUrl = 'https://testforgeplus.trustie.net';
  axios.defaults.withCredentials = true;
}else if (window.location.href.indexOf('wiki-api') > -1) {
  actionUrl = "https://wiki-api.trustie.net";
  axios.defaults.withCredentials = true;
}

export const httpUrl = actionUrl;
export const TokenKey = 'autologin_trustie';

// 创建axios实例
const service = axios.create({
  baseURL: httpUrl,
  timeout: 10000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
  if (cookie.load(TokenKey)) {
    console.log(cookie.load(TokenKey));
    config.headers['Authorization'] = cookie.load(TokenKey); // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if (window.location.port === "3007") {
    // 模拟token为登录用户
    const taskToken = sessionStorage.taskToken;
    if (config.url.indexOf('?') === -1) {
      config.url = `${config.url}?token=${taskToken}`;
    } else {
      config.url = `${config.url}&token=${taskToken}`;
    }
  }
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  // Promise.reject(error);
});
// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response||{};
    if (res.status === 400) {
      message.error(res.data.message || '操作失败');
      return Promise.reject('error');
    }
    if (res.status === 401) {
      message.error(res.data.message || '登录信息已过期');
      return Promise.reject('error');
    }
    if (res.status === 403) {
      message.error(res.data.message || '无权限！');
      return Promise.reject('error');
    }
    if (res.status === 40001) {
      notification.open({
        message: "提示",
        description: '账户或密码错误！',
      });
      return Promise.reject('error');
    }
    if (response.status !== 200 && res.status !== 200) {
      notification.open({
        message: "提示",
        description: res.message,
      });
    } else {
      return response.data;
    }
  },
  error => {
    console.log(error);
    let res = error.response||{};
    if (res.status === 400) {
      message.error(res.data.message || '操作失败');
      return Promise.reject('error');
    }
    if (res.status === 401) {
      message.error(res.data.message || '登录信息已过期');
      Login();
      return Promise.reject('error');
    }
    if (res.status === 403) {
      message.error(res.data.message || '无权限！');
      return Promise.reject('error');
    }
    notification.open({
      message: "提示",
      description: error.message,
    });
    return Promise.reject(error);
  }
);

export default service;
