import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';
import { history } from 'umi';
import { stateActions } from '../valtio/actions';
import { state } from '../valtio/state';

const downloadFile = (disposition: string, data: any) => {
  const blob = new Blob([data]);
  const start = "filename*=utf-8''";
  let fileName = '';
  let dis = disposition.replace('UTF-8', 'utf-8');
  // console.log(dis, 'dis');
  if (dis.includes(start)) {
    fileName = dis.substr(dis.indexOf(start) + start.length);
    fileName = decodeURI(fileName);
  }
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink: any = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
  } else {
    // IE10+下载
    // navigator.msSaveBlob(blob, fileName);
  }
};

export const requestConfig: RequestConfig = {
  baseURL: '/api/',
  timeout: 1000 * 60,
  method: 'POST',
  errorConfig: {
    errorThrower: (res) => {
      console.log('errorThrower', res);
    },
    // 错误接收及处理
    errorHandler: (error: any) => {
      if (error) {
        if (error.errorMessage !== '用户未登录') {
          message.error(error.errorMessage);
        }
        switch (error.errorCode) {
          case 10000:
            if (history.location.pathname !== '/login') history.push('/login');
            break;
        }
      }
    },
  },

  // 请求拦截器
  requestInterceptors: [
    (url: string, options: any) => {
      stateActions.addLoading();
      return {
        url: url,
        options: {
          ...options,
          headers: {
            authorization: 'Bearer ' + state.storage.access_token,
          },
        },
      };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      stateActions.subLoading();
      const { headers } = response;
      // console.log(headers['content-disposition'], 'response');
      if (headers['content-disposition']) {
        downloadFile(headers['content-disposition'], response.data);
        return false;
      }
      const { data = {} as any } = response;
      if (!data.success && data.type !== 'application/vnd.ms-excel') {
        return Promise.reject(response.data);
      }
      return response;
    },
  ],
};
