import axios from 'axios';
import { requestProxy } from "./indexEduplus2RequestProxy";
import { broadcastChannelOnmessage, isDev, queryString } from 'educoder';
import { notification } from 'antd';

import './index.css';

let message501 = false;
broadcastChannelOnmessage('refreshPage', () => {
  window.location.reload();
})

function locationurl(list) {
  // if (window.location.port !== "3007") {
  window.location.href = list
  // }
}
// TODO 开发期多个身份切换
let debugType = ""
if (isDev) {
  const _search = window.location.search;
  let parsed = {};
  if (_search) {
    parsed = queryString.parse(_search);
  }
  debugType = window.location.search.indexOf('debug=t') !== -1 ? 'teacher' :
  window.location.search.indexOf('debug=s') !== -1 ? 'student' :
  window.location.search.indexOf('debug=a') !== -1 ? 'admin' : parsed.debug || 'admin'
}                 
window._debugType = debugType;
export function initAxiosInterceptors(props) {
  // 判断网络是否连接
  initOnlineOfflineListener();

  var proxy = "https://testforgeplus.educoder.net";
  //响应前的设置
  axios.interceptors.request.use(
    config => {
      if(config.url.indexOf("http") !== -1) {
        return config
      }
      requestProxy(config);
      let url = `/api${config.url}`;

      if (`${config[0]}` !== `true`) {
        if (window.location.port === "3007") {
          config.url = `${proxy}${url}`;
          if (config.url.indexOf('?') === -1) {
            config.url = `${config.url}?debug=${debugType}`;
          } else {
            config.url = `${config.url}&debug=${debugType}`;
          }
        } else {
          config.url = url;
        }
      }
      return config;
    },
    err => {
      return Promise.reject(err);
  });

  axios.interceptors.response.use(function (response) {
    if (response === undefined) {
      return
    }
    const config = response.config;
    if (response.data.status === -1) {
      if (window.location.pathname.startsWith('/tasks/')) {
        props.showSnackbar(response.data.message || '服务器异常，请联系管理员。')
      } else {
        notification.open({
          message: "提示",
          description: response.data.message || '服务器异常，请联系管理员。',
          style: {
            zIndex: 99999999
          },
        });
      }
      throw new axios.Cancel('Operation canceled by the user.');
    }

    if (response.data.status === 403 || response.data.status === "403") {
      locationurl('/403');
    }

    if (response.data.status === 404) {
      let responseURL = response.request ? response.request.responseURL:'';
      if (responseURL.indexOf('/api/users/') === -1 || responseURL.indexOf('/api/organizations/') === -1 || responseURL.indexOf('/api/owners/') === -1) {
        locationurl('/nopage');
      }
    }

    if (response.data.status === 500) {
      locationurl('/500');
    }

    if (response.data.status === 501) {
      if (message501 === false) {
        message501 = true
        notification.open({
          message: "提示",
          description: response.data.message || '访问异常，请求不合理',
          style: {
            zIndex: 99999999
          }
        })
      }
      window.setTimeout(function () {
        message501 = false
      }, 2000);
    }
    return response;
  }, function (error) {
    return Promise.reject(error);
  });
}


function initOnlineOfflineListener() {
  const $ = window.$
  $(window).bind("online", () => {
    notification.destroy()
    notification.success({
      duration: 2,
      message: '网络恢复正常',
      description:
        '网络恢复正常，感谢使用。',
    })
  });
  $(window).bind("offline", () => {
    notification.destroy()

    notification.warning({
      duration: null,
      message: '网络异常',
      description:
        '网络异常，请检测网络后重试。',
    })
  });
}
