/**
 * axios 实例
 */
import axios from 'axios';
import router from '@/router';
import { MessageBox, Message } from 'element-ui';
import { API_BASE_URL, TOKEN_HEADER_NAME, LAYOUT_PATH } from '@/config/setting';
import { getToken, setToken } from './token-util';
import { logout } from './page-tab-util';
import JSONBIG from 'json-bigint';

const service = axios.create({
  baseURL: API_BASE_URL,
  transformResponse: [
    function (data) {
      const json = JSONBIG({
        storeAsString: true
      });
      const res = json.parse(data);
      return res;
    }
  ]
});

/**
 * 添加请求拦截器
 */
service.interceptors.request.use(
  (config) => {
    // 添加 token 到 header
    const token = getToken();
    if (token && config.headers) {
      config.headers.common[TOKEN_HEADER_NAME] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 添加响应拦截器
 */
// 添加响应拦截器
// 添加响应拦截器
// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    // token 自动续期
    if (
      response.data.code === '-1' &&
      response.config?.showErrorToast !== false
    ) {
      Message.error(response.data.message);
    }

    // Check if the response content type is 'blob'
    const isBlob =
      response.headers['content-type'] &&
      response.headers['content-type'].toLowerCase().includes('blob');

    // Return the original response for blob data
    if (isBlob) {
      return response;
    }

    // Parse the JSON data for non-blob responses
    try {
      const token = response.headers[TOKEN_HEADER_NAME.toLowerCase()];
      if (token) {
        setToken(token);
      }

      // Parse JSON data
      const json = JSONBIG({
        storeAsString: true
      });
      const data = json.parse(response.data);

      return data;
    } catch (error) {
      console.error('JSON parsing error:', error);
      return Promise.reject(error);
    }
  }
  // ...
);

export default service;
