import axios from "axios";
import { message } from 'antd';

const instance = axios.create({
  baseURL: import.meta.env.VITE_SERVER_BASE,
  timeout: 1000,
});


// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  const { headers = {}, responseType = 'json', download = false } = config;
  const token = sessionStorage.getItem('token') || '';

  // 在发送请求之前做些什么
  return {
    ...config,
    headers: {
      ...headers,
      responseType: download ? 'blob' : responseType,
      Authorization: token,
    }
  };
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么

  const { data, config } = response;
  if (config.download) {
    return downloadBlob(response.data, '下载文件');
  }
  
  if (data.code === 1000) {
    if (data.data.token) {
      sessionStorage.setItem('token', data.data.token);
    }

    return data.data;
  } else if (data.code === 1001) {
    if (!config.silent) {
      message.error('未登录或者超时, 请重新登录');
    }
  } else {
    if (!config.silent) {
      const errMsg = data.message || '系统错误';
      message.error(errMsg.indexOf('exception') > -1 ? '服务异常' : errMsg);
    }
  }

  return Promise.reject(response);
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么

  console.error(error);

  return Promise.reject("网络异常, 请重试...");
});

export default instance;

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

export function queryDict(apiRequest) {
  return function (params, labelKey = 'name', valueKey = 'id') {
    const { current, pageSize, ...leftParams } = params || {};
    return apiRequest({
      pageSize: 9999,
      pageNum: 1,
      ...(leftParams || {}),
    })
      .then((res) => {
        return res?.records?.map((x) => ({
          label: x[labelKey],
          value: x[valueKey],
          ...x,
        }));
      })
      .catch((err) => {
        return {
          success: false,
        };
      });
  };
}

function downloadBlob(response) {
  let fileName = '未知文件';
  const contentDisposition = response.headers['content-disposition'];
  if (contentDisposition) {
    const parts = contentDisposition.split(';filename=');
    if (parts[1]) {
      fileName = parts[1];
    }
  }

  const url = window.URL.createObjectURL(response.data);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName);
  link.click();
  window.URL.revokeObjectURL(url);
}
