// 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 JSONbig from 'json-bigint';
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: $t('request.data.returned.successfully'),
  201: $t('data.saved.successfully'),
  202: $t('a.request.is.queued.async.task'),
  204: $t('data.deleted.successfully'),
  400: $t('invalid.request.no.data.modified'),
  401: $t('no.permission.tokencredentials.error'),
  403: $t('authorized.but.access.forbidden'),
  404: $t('request.targets.nonexistent.record'),
  406: $t('unsupported.format'),
  410: $t('resource.permanently.deleted'),
  422: $t('validation.error.when.creating.object'),
  500: $t('server.error.please.check'),
  502: $t('gateway.error'),
  503: $t('service.unavailable.server.overloadmaintenance'),
  504: $t('gateway.timeout'),
};
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;
  }
  let data = await response.clone().json();
  if (response.ok) {
    const dataText = await response.clone().text(); // 获取原始的JSON字符串
    data = JSONbig.parse(dataText); // 使用json-bigint来解析大整数
    // data = { ...response, data: parsedData };
  }
  // const data = await response.clone().json();
  if (data.code === 4033) {
    // TODO 该接口是否需要提示权限信息
    if (options.role) {
      notification.warning({
        message: $t('no.access.permission'),
      });
    }
    // 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 || $t('operation.failed'),
      duration: typeof options.duration === 'undefined' ? 4.5 : options.duration,
    });
  }
  return data;
});

export default request;
