import { request } from 'umi';
import { downloadBlob } from './download';

/**
 *
 * 自定义修改 umi-request 行为
 *
 * 默认错误处理行为是通过 message 组件报错
 * 也可以设置 option.showType 来修改默认行为
 *
 * export enum ErrorShowType {
 *   SILENT = 0, // 不提示错误
 *   WARN_MESSAGE = 1, // 警告信息提示
 *   ERROR_MESSAGE = 2, // 错误信息提示
 *   NOTIFICATION = 4, // 通知提示
 *   REDIRECT = 9, // 页面跳转，会跳转到 /exception 页面
 * }
 *
 */

function requestInterceptor(url, options) {
  const headers = options.headers || {};
  const token = localStorage.getItem('token')
    ? { Authorization: localStorage.getItem('token') }
    : {};

  const prefix = `${API_BASE}/api/admin`;

  return {
    url: `${prefix}${url}`,
    options: {
      ...options,
      headers: {
        ...headers,
        ...token,
      },
    },
  };
}

async function responseInterceptor(response, ctx) {
  const contextType = response.headers.get('content-type');
  if (contextType.indexOf('json') > -1) {
    const result = await response.clone().json();
    if (result?.token || result?.data?.token) {
      localStorage.setItem('token', result?.token || result?.data?.token);
    }
  }

  if (contextType.indexOf('application/vnd.ms-excel') > -1) {
    const data = await response.clone().blob();
    const content = response.headers.get('content-disposition');
    const fileName = content.replace('attachment;filename=', '');
    downloadBlob(data, decodeURIComponent(fileName));
  }

  return response;
}

// https://umijs.org/plugins/plugin-request
export const requestConfig = {
  errorConfig: {
    adaptor: (resData, ctx) => {
      if (typeof resData === 'string') {
        // 可能是 excel 导出
        return {
          success: true,
        }
      }

      const showError = ctx.req.options?.showType;

      return {
        ...resData,
        success: resData.code === 1000,
        errorMessage: resData.message,
        showType: isNaN(showError) ? 1 : showError, // 默认通过 message 组件报错
      };
    },
  },
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptor],
};

export default (...args) => request(...args).then((r) => r.data);

export function queryTable(apiRequest) {
  return function (params) {
    return apiRequest({
      ...params,
      pageNum: params.current,
    })
      .then((res) => {
        return {
          data: res.records,
          success: true,
          total: res.total,
        };
      })
      .catch((err) => {
        return {
          success: false,
        };
      });
  };
}
