import { message,  } from 'antd';
import { getToken, UnityAction } from './utils';

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [option] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

//节流阀
let flag = false;
let tokenFlag = false;

export default function request(url, option, jwt) {
  const number = new Date().getTime();
  // console.log(API_HOST);
  const time = url.indexOf('?') > -1 ? `&time=${number}` : `?time=${number}`;
  if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
    if (url.indexOf('/api/') === -1) {
      url = `/api/v1${url}${time}`;
    }
    // API_HOST在config/config.js的define中配置
    // url = API_HOST + url
  }
  let token = getToken();

  const options = {
    ...option,
  };

  const defaultOptions = {
    credentials: 'include',
  };
  const newOptions = { ...defaultOptions, ...options };

  newOptions.headers = {
    ...newOptions.headers,
    'JWT-TOKEN': jwt ? jwt : `${token}`,
  };
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      };
    }
  }
  
  return (
    fetch(url, newOptions)
      .then(response => {
        if (response.status === 204) {
          return response.text();
        }
        return response.json();
      })
      .then(response => {
        if (typeof response === 'string') {
          return response;
        }
        //当http status正常但response里显示token超时则报错
        else if ([401, 601, 602, 603].includes(response.code)) {
          const error = new Error(response.data);
          error.name = response.code;
          error.response = response;
          throw error;
        } else if (response.code !== 200) {
          if (flag) throw e;

          flag = true;
          setTimeout(() => {
            flag = false;
          }, 3000);
          message.error(response.msg);
          // return false;
          throw new Error(response.msg);
        } else {
          return response;
        }
      })
      .catch(e => {
        const status = e.name;
        if (status == 'AbortError') throw e;
        // environment should not be used

        if ([401, 601, 602, 603].includes(status)) {
          if (tokenFlag) throw e;

          tokenFlag = true;
          setTimeout(() => {
            tokenFlag = false;
          }, 3000);
          message.error('token失效，请重新登录');
          // 在unity端无需跳转页面,  发消息给unity 跳转至登录页
          UnityAction.sendMsg('sessionTimeout', {});
          throw e;
        }
    

        if (flag) throw e;

        flag = true;
        setTimeout(() => {
          flag = false;
        }, 3000);

        message.error('网络连接错误，请重试');
        throw e;
      })
  );
}
