// An highlighted block
/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
/* eslint-disable no-underscore-dangle */
import { extend } from 'umi-request';
import { notification } from 'antd';
import { getUrlSearchParams, getToken } from './utils';
import localStorage from './localStorage';
import config from '../../config/env.config';
import IframeBridge from './iframeBridge';

let isRefreshing = true;
const subscriber = [];

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};
const errorHandler = error => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  }

  return response;
};
const request = extend({
  // prefix: '/server',
  prefix: `${config.api}`,
  errorHandler,
  // responseType: 'arrayBuffer',
  // 默认错误处理
  // credentials: 'include', // 默认请求是否带上cookie
});
const addSubscriber = callback => subscriber.push(callback);
const wait = async seconds => new Promise(resolve => setTimeout(resolve, seconds));
const onAccessTokenFetched = () => {
  console.log('subscriber :>> ', subscriber);
  subscriber.forEach(callback => callback());
  // subscriber = [];
};
const refreshRequest = async (url, options) => {
  console.log('url, options :>> ', url, options);
  const promise = new Promise(resolve => addSubscriber(() => resolve(request(url, options))));
  if (isRefreshing) {
    isRefreshing = false;
    await wait(500);
    const data = await refreshtoken();
    if (data.code === 2000) {
      localStorage.set('token', data.data.accessToken);
    }
    console.log('1111111 :>> ', subscriber.length);
    onAccessTokenFetched();
    isRefreshing = true;
  }
  return promise;
};

// 判断是否从tob进入
const searchPrams = getUrlSearchParams();
const isTob = searchPrams.source === 'tob';
/**
 * 异常处理程序
 */

// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
  const token = getToken();
  if (!token && !url.includes('/v2/oauth/login') && !url.includes('/v2/sms/send')) {
    window.location.href = `${window.origin}/user/login`;
  }
  const { headers } = options;
  const header = {
    ...headers,
    'Access-Token': token,
    // 'Content-Type': headers['Content-Type'] ? headers['Content-Type'] : 'application/json',
  };
  return {
    url,
    options: { ...options, headers: header },
  };
});

function refreshtoken() {
  return request.get(`/v2/oauth/refreshtoken?refreshtoken=${localStorage.get('refreshtoken')}`);
}
// response拦截器, 处理response
request.interceptors.response.use(async (response, options) => {
  if (options.responseType === 'arrayBuffer') {
    return response;
  }
  const data = await response.clone().json();
  if (data.code === 4033) {
    // TODO 该接口是否需要提示权限信息
    if (options.role) {
      notification.warning({
        message: '没有权限访问！',
      });
    }
    // token过期
    const url = response.url.replace(options.prefix, '');
    return refreshRequest(url, options);
  }
  if (data.code === 4011) {
    const loginPath = window.__POWERED_BY_QIANKUN__
      ? `${window.origin}/access/login`
      : `${window.origin}/user/login`;

    notification.warning({
      message: data.msg,
    });
    if (!isTob) {
      window.location.href = loginPath;
    } else {
      const iframeBridgeModel = new IframeBridge();
      iframeBridgeModel.run({ event: 'toLogin' });
    }
  }
  if (data.businessCode && data.businessCode !== '0000' && !options.notTip) {
    notification.warning({
      message: data.detail || data.msg || '操作失败',
    });
  }
  return response;
});

export default request;
