import axios from 'axios';
import { message } from '@/utils/elementUtils';
const isDev = process.env.NODE_ENV !== 'production';

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    // this.requestKeys = {}
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      timeout: 50000, // 问后台响应限制时长
      headers: {
      },
    };
    return config;
  }

  interceptors(service) {
    // 请求
    service.interceptors.request.use(
      (config) => {
        if (!config?.headers) {
          throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      },
    );

    // 响应
    service.interceptors.response.use(
      (response) => {
        const contentDisposition = response.headers['content-disposition'];
        let fileName;
        if (contentDisposition) {
          // 正则匹配filename并提取文件名
          const match = contentDisposition.match(/filename="?([^";]*)"?/);
          if (match) {
            fileName = decodeURI(match[1]);
          }
        }
        if (fileName) {
          return {
            fileName: fileName,
            data: response.data,
            headers: { 'content-disposition': fileName },
          };
        } else if (!response.success) {
          console.log(response.data, 'response.data');
          message(response.data.msg || '服务器出错！', 'error');
          return Promise.reject(response.data);
        } else {
          return response.data;
        }
      },
      async(error) => {
        if (error?.response?.config?.responseType === 'blob') {
          // 流报错处理
          const reader = new FileReader();
          reader.onload = (e) => {
            if (e.target && typeof e.target.result === 'string') {
              const err = JSON.parse(e.target.result);
              message(err.msg, 'error');
            }
          };
          reader.readAsText(error?.response?.data); // 读取为text
        }

        message.error('请求失败，请检查网络连接或联系管理员');
        if (error.code) {
          const can_cel_text = 'cancel';
          return Promise.reject(can_cel_text);
        } else {
          return Promise.reject(error);
        }
      },
    );
  }
  request(options) {
    const service = axios.create();

    options = Object.assign(this.getInsideConfig(), options);
    if ('ContentType' in options) {
      options.headers['Content-Type'] = options.ContentType;
      delete options.ContentType;
    }
    this.interceptors(service);
    return service(options);
  }
}

export default HttpRequest;
