/*
 * @Author: Mm
 * @Date: 2025-05-07 14:14:01
 * @LastEditors: Mm
 * @LastEditTime: 2025-07-30 09:26:34
 * 不写bug的程序员不是一个好程序员!
 */
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useAppConfig } from '@vben/hooks';

import { useAccessStore } from '@vben/stores';
const accessStore = useAccessStore();
function formatToken(token) {
  return token ? `Bearer ${token}` : null;
}
const { apiURL, clientId, enableEncrypt } = useAppConfig(
  import.meta.env,
  import.meta.env.PROD,
);

const service = axios.create({
  baseURL: apiURL,
  timeout: 500000,
});

service.defaults.withCredentials = true; // 让ajax携带cookie
service.interceptors.request.use(
  // 每次请求都自动携带Cookie
  (config) => {
    config.headers.Authorization = formatToken(accessStore.accessToken);
    // config.headers.wflowToken = localStorage.getItem('wflow-token');

    // 添加全局clientId
    config.headers.clientId = clientId;
    return config;
  },
  // eslint-disable-next-line handle-callback-err
  (error) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (rsp) => {
    if (rsp.data.code === 500) {
      ElMessage({ message: rsp.data.msg, type: 'error' });
      return new Error(rsp.data.msg);
    } else {
      return rsp;
    }
  },
  // 拦截异常的响应
  (err) => {

    //throw 'request error'
    if (
      err.response.status === 500 &&
      err.response.data.message.indexOf('Token')
    ) {
      const err = '未登录或登录状态已过期，请点击头像切换人员登录';
      ElMessage({ message: err, type: 'error' });
      return new Error(err);
    }

    return Promise.reject(err);
  },
);

export function syncRequest(config) {
  let ajax = new XMLHttpRequest();
  ajax.withCredentials = true;
  //ajax.responseType = 'json'
  ajax.open(config.method, globalProps.BASE_URL + config.url, false);
  ajax.onload = function (e) {
    if (ajax.readyState === 4) {
      if (ajax.status === 200 && config.success) {
        config.success(ajax.responseText);
      } else if (config.fail) {
        config.fail(ajax.responseText);
      }
    }
  };
  ajax.onerror = function (e) {
    if (config.fail) {
      config.fail(ajax.responseText);
    }
  };
  if (config.data) {
    if (config.type === 'json') {
      ajax.setRequestHeader('Content-type', 'application/json');
      ajax.send(JSON.stringify(config.data));
    } else {
      ajax.setRequestHeader(
        'Content-type',
        'application/x-www-form-urlencoded',
      );
      let form = new FormData();
      for (const key in config.data) {
        form.set(key, config.data[key]);
      }
      ajax.send(form);
    }
  } else {
    ajax.send(null);
  }
}

export default service;
