import axios from 'axios'; // 引入axios

// const userid = localStorage.getItem('userid') ? localStorage.getItem('userid') : ''
const userid = localStorage.getItem('persId')
  ? localStorage.getItem('persId')
  : '';
const orgId = localStorage.getItem('currentOrgId')
  ? localStorage.getItem('currentOrgId')
  : '';
// const orgId = localStorage.getItem('orgId') ? localStorage.getItem('orgId') : ''

const accessToken = localStorage.getItem('accessToken')
  ? localStorage.getItem('accessToken')
  : '';
//
let baseURL = '';
const RESOURCE_CODE =
  import.meta.env.VUE_APP_RESOURCE_CODE || '6ace62b8e2bb467d98286d260aebcef2';
if (import.meta.env.MODE === 'development') {
  baseURL = '/pdcApi';
} else {
  baseURL = '/modular-source/' + RESOURCE_CODE + '/pdcApi';
}
// 创建axios实例
const service = axios.create({
  // api的base_url 目前开发阶段使用本机代理
  // baseURL: '/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi',
  baseURL,
  headers: {
    persId: userid, // 从缓存中取出
    orgId: orgId,
    accessToken: accessToken,
    Authorization: sessionStorage.getItem('Authorization'),
  },
  timeout: 100000, // 请求超时
  withCredentials: true,
});

// request interceptor 请求拦截器，在每次ajax请求之前调用
service.interceptors.request.use(
  (config) => {
    // config.headers['persId'] = localStorage.getItem('userid') ? localStorage.getItem('userid') : ''
    config.headers['persId'] = localStorage.getItem('persId')
      ? localStorage.getItem('persId')
      : '';
    config.headers['orgId'] = localStorage.getItem('currentOrgId')
      ? localStorage.getItem('currentOrgId')
      : '';
    // config.headers['orgId'] = localStorage.getItem('orgId') ? localStorage.getItem('orgId') : ''
    config.headers['accessToken'] = localStorage.getItem('accessToken')
      ? localStorage.getItem('accessToken')
      : '';
    config.headers['Authorization'] = sessionStorage.getItem('Authorization');
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

// respone interceptor 响应拦截器，在每次ajax请求响应后、分发到特定相应方法之前调用，通用处理响应状态
service.interceptors.response.use(
  (response) => {
    // console.log(response.data, 'response')
    // to-do 通用状态处理
    if (
      response.data.code == 10005 ||
      response.data.code == 10006 ||
      response.data.code == 9999
    ) {
      localStorage.removeItem('userid');
      localStorage.removeItem('accessToken');
    }
    if (response.data.code === 401) {
      window.location.reload();
    }
    return response.data;
  },
  (error) => {
    // 响应错误状态处理
    return Promise.reject(error);
  },
);

export default service;
